clang 22.0.0git
SemaDecl.cpp
Go to the documentation of this file.
1//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for declarations.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TypeLocBuilder.h"
16#include "clang/AST/ASTLambda.h"
18#include "clang/AST/CharUnits.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclObjC.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
29#include "clang/AST/StmtCXX.h"
30#include "clang/AST/Type.h"
36#include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
37#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
38#include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
39#include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
41#include "clang/Sema/DeclSpec.h"
44#include "clang/Sema/Lookup.h"
46#include "clang/Sema/Scope.h"
48#include "clang/Sema/SemaARM.h"
49#include "clang/Sema/SemaCUDA.h"
50#include "clang/Sema/SemaHLSL.h"
52#include "clang/Sema/SemaObjC.h"
55#include "clang/Sema/SemaPPC.h"
57#include "clang/Sema/SemaSYCL.h"
59#include "clang/Sema/SemaWasm.h"
60#include "clang/Sema/Template.h"
61#include "llvm/ADT/STLForwardCompat.h"
62#include "llvm/ADT/SmallPtrSet.h"
63#include "llvm/ADT/SmallString.h"
64#include "llvm/ADT/StringExtras.h"
65#include "llvm/Support/SaveAndRestore.h"
66#include "llvm/TargetParser/Triple.h"
67#include <algorithm>
68#include <cstring>
69#include <optional>
70#include <unordered_map>
71
72using namespace clang;
73using namespace sema;
74
76 if (OwnedType) {
77 Decl *Group[2] = { OwnedType, Ptr };
79 }
80
82}
83
84namespace {
85
86class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
87 public:
88 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
89 bool AllowTemplates = false,
90 bool AllowNonTemplates = true)
91 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
92 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
93 WantExpressionKeywords = false;
94 WantCXXNamedCasts = false;
95 WantRemainingKeywords = false;
96 }
97
98 bool ValidateCandidate(const TypoCorrection &candidate) override {
99 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
100 if (!AllowInvalidDecl && ND->isInvalidDecl())
101 return false;
102
103 if (getAsTypeTemplateDecl(ND))
104 return AllowTemplates;
105
106 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
107 if (!IsType)
108 return false;
109
110 if (AllowNonTemplates)
111 return true;
112
113 // An injected-class-name of a class template (specialization) is valid
114 // as a template or as a non-template.
115 if (AllowTemplates) {
116 auto *RD = dyn_cast<CXXRecordDecl>(ND);
117 if (!RD || !RD->isInjectedClassName())
118 return false;
119 RD = cast<CXXRecordDecl>(RD->getDeclContext());
120 return RD->getDescribedClassTemplate() ||
122 }
123
124 return false;
125 }
126
127 return !WantClassName && candidate.isKeyword();
128 }
129
130 std::unique_ptr<CorrectionCandidateCallback> clone() override {
131 return std::make_unique<TypeNameValidatorCCC>(*this);
132 }
133
134 private:
135 bool AllowInvalidDecl;
136 bool WantClassName;
137 bool AllowTemplates;
138 bool AllowNonTemplates;
139};
140
141} // end anonymous namespace
142
144 TypeDecl *TD, SourceLocation NameLoc) {
145 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
146 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
147 if (DCK != DiagCtorKind::None && LookupRD && FoundRD &&
148 FoundRD->isInjectedClassName() &&
149 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) {
150 Diag(NameLoc,
152 ? diag::ext_out_of_line_qualified_id_type_names_constructor
153 : diag::err_out_of_line_qualified_id_type_names_constructor)
154 << TD->getIdentifier() << /*Type=*/1
155 << 0 /*if any keyword was present, it was 'typename'*/;
156 }
157
158 DiagnoseUseOfDecl(TD, NameLoc);
159 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
160}
161
162namespace {
163enum class UnqualifiedTypeNameLookupResult {
164 NotFound,
165 FoundNonType,
166 FoundType
167};
168} // end anonymous namespace
169
170/// Tries to perform unqualified lookup of the type decls in bases for
171/// dependent class.
172/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
173/// type decl, \a FoundType if only type decls are found.
174static UnqualifiedTypeNameLookupResult
176 SourceLocation NameLoc,
177 const CXXRecordDecl *RD) {
178 if (!RD->hasDefinition())
179 return UnqualifiedTypeNameLookupResult::NotFound;
180 // Look for type decls in base classes.
181 UnqualifiedTypeNameLookupResult FoundTypeDecl =
182 UnqualifiedTypeNameLookupResult::NotFound;
183 for (const auto &Base : RD->bases()) {
184 const CXXRecordDecl *BaseRD = Base.getType()->getAsCXXRecordDecl();
185 if (BaseRD) {
186 } else if (auto *TST = dyn_cast<TemplateSpecializationType>(
187 Base.getType().getCanonicalType())) {
188 // Look for type decls in dependent base classes that have known primary
189 // templates.
190 if (!TST->isDependentType())
191 continue;
192 auto *TD = TST->getTemplateName().getAsTemplateDecl();
193 if (!TD)
194 continue;
195 if (auto *BasePrimaryTemplate =
196 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
197 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
198 BaseRD = BasePrimaryTemplate;
199 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
201 CTD->findPartialSpecialization(Base.getType()))
202 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
203 BaseRD = PS;
204 }
205 }
206 }
207 if (BaseRD) {
208 for (NamedDecl *ND : BaseRD->lookup(&II)) {
209 if (!isa<TypeDecl>(ND))
210 return UnqualifiedTypeNameLookupResult::FoundNonType;
211 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
212 }
213 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
214 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
215 case UnqualifiedTypeNameLookupResult::FoundNonType:
216 return UnqualifiedTypeNameLookupResult::FoundNonType;
217 case UnqualifiedTypeNameLookupResult::FoundType:
218 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
219 break;
220 case UnqualifiedTypeNameLookupResult::NotFound:
221 break;
222 }
223 }
224 }
225 }
226
227 return FoundTypeDecl;
228}
229
231 const IdentifierInfo &II,
232 SourceLocation NameLoc) {
233 // Lookup in the parent class template context, if any.
234 const CXXRecordDecl *RD = nullptr;
235 UnqualifiedTypeNameLookupResult FoundTypeDecl =
236 UnqualifiedTypeNameLookupResult::NotFound;
237 for (DeclContext *DC = S.CurContext;
238 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
239 DC = DC->getParent()) {
240 // Look for type decls in dependent base classes that have known primary
241 // templates.
242 RD = dyn_cast<CXXRecordDecl>(DC);
243 if (RD && RD->getDescribedClassTemplate())
244 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
245 }
246 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
247 return nullptr;
248
249 // We found some types in dependent base classes. Recover as if the user
250 // wrote 'MyClass::II' instead of 'II', and this implicit typename was
251 // allowed. We'll fully resolve the lookup during template instantiation.
252 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
253
254 ASTContext &Context = S.Context;
255 NestedNameSpecifier NNS(Context.getCanonicalTagType(RD).getTypePtr());
256 QualType T =
257 Context.getDependentNameType(ElaboratedTypeKeyword::None, NNS, &II);
258
259 CXXScopeSpec SS;
260 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
261
262 TypeLocBuilder Builder;
263 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
264 DepTL.setNameLoc(NameLoc);
266 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
267 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
268}
269
271 Scope *S, CXXScopeSpec *SS, bool isClassName,
272 bool HasTrailingDot, ParsedType ObjectTypePtr,
273 bool IsCtorOrDtorName,
274 bool WantNontrivialTypeSourceInfo,
275 bool IsClassTemplateDeductionContext,
276 ImplicitTypenameContext AllowImplicitTypename,
277 IdentifierInfo **CorrectedII) {
278 bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
279 // FIXME: Consider allowing this outside C++1z mode as an extension.
280 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
281 getLangOpts().CPlusPlus17 && IsImplicitTypename &&
282 !HasTrailingDot;
283
284 // Determine where we will perform name lookup.
285 DeclContext *LookupCtx = nullptr;
286 if (ObjectTypePtr) {
287 QualType ObjectType = ObjectTypePtr.get();
288 if (ObjectType->isRecordType())
289 LookupCtx = computeDeclContext(ObjectType);
290 } else if (SS && SS->isNotEmpty()) {
291 LookupCtx = computeDeclContext(*SS, false);
292
293 if (!LookupCtx) {
294 if (isDependentScopeSpecifier(*SS)) {
295 // C++ [temp.res]p3:
296 // A qualified-id that refers to a type and in which the
297 // nested-name-specifier depends on a template-parameter (14.6.2)
298 // shall be prefixed by the keyword typename to indicate that the
299 // qualified-id denotes a type, forming an
300 // elaborated-type-specifier (7.1.5.3).
301 //
302 // We therefore do not perform any name lookup if the result would
303 // refer to a member of an unknown specialization.
304 // In C++2a, in several contexts a 'typename' is not required. Also
305 // allow this as an extension.
306 if (IsImplicitTypename) {
307 if (AllowImplicitTypename == ImplicitTypenameContext::No)
308 return nullptr;
309 SourceLocation QualifiedLoc = SS->getRange().getBegin();
310 // FIXME: Defer the diagnostic after we build the type and use it.
311 auto DB = DiagCompat(QualifiedLoc, diag_compat::implicit_typename)
312 << Context.getDependentNameType(ElaboratedTypeKeyword::None,
313 SS->getScopeRep(), &II);
315 DB << FixItHint::CreateInsertion(QualifiedLoc, "typename ");
316 }
317
318 // We know from the grammar that this name refers to a type,
319 // so build a dependent node to describe the type.
320 if (WantNontrivialTypeSourceInfo)
321 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc,
322 (ImplicitTypenameContext)IsImplicitTypename)
323 .get();
324
327 IsImplicitTypename ? ElaboratedTypeKeyword::Typename
329 SourceLocation(), QualifierLoc, II, NameLoc);
330 return ParsedType::make(T);
331 }
332
333 return nullptr;
334 }
335
336 if (!LookupCtx->isDependentContext() &&
337 RequireCompleteDeclContext(*SS, LookupCtx))
338 return nullptr;
339 }
340
341 // In the case where we know that the identifier is a class name, we know that
342 // it is a type declaration (struct, class, union or enum) so we can use tag
343 // name lookup.
344 //
345 // C++ [class.derived]p2 (wrt lookup in a base-specifier): The lookup for
346 // the component name of the type-name or simple-template-id is type-only.
347 LookupNameKind Kind = isClassName ? LookupTagName : LookupOrdinaryName;
348 LookupResult Result(*this, &II, NameLoc, Kind);
349 if (LookupCtx) {
350 // Perform "qualified" name lookup into the declaration context we
351 // computed, which is either the type of the base of a member access
352 // expression or the declaration context associated with a prior
353 // nested-name-specifier.
354 LookupQualifiedName(Result, LookupCtx);
355
356 if (ObjectTypePtr && Result.empty()) {
357 // C++ [basic.lookup.classref]p3:
358 // If the unqualified-id is ~type-name, the type-name is looked up
359 // in the context of the entire postfix-expression. If the type T of
360 // the object expression is of a class type C, the type-name is also
361 // looked up in the scope of class C. At least one of the lookups shall
362 // find a name that refers to (possibly cv-qualified) T.
363 LookupName(Result, S);
364 }
365 } else {
366 // Perform unqualified name lookup.
367 LookupName(Result, S);
368
369 // For unqualified lookup in a class template in MSVC mode, look into
370 // dependent base classes where the primary class template is known.
371 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
372 if (ParsedType TypeInBase =
373 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
374 return TypeInBase;
375 }
376 }
377
378 NamedDecl *IIDecl = nullptr;
379 UsingShadowDecl *FoundUsingShadow = nullptr;
380 switch (Result.getResultKind()) {
382 if (CorrectedII) {
383 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
384 AllowDeducedTemplate);
385 TypoCorrection Correction =
386 CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS, CCC,
388 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
390 bool MemberOfUnknownSpecialization;
392 TemplateName.setIdentifier(NewII, NameLoc);
394 CXXScopeSpec NewSS, *NewSSPtr = SS;
395 if (SS && NNS) {
396 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
397 NewSSPtr = &NewSS;
398 }
399 if (Correction && (NNS || NewII != &II) &&
400 // Ignore a correction to a template type as the to-be-corrected
401 // identifier is not a template (typo correction for template names
402 // is handled elsewhere).
403 !(getLangOpts().CPlusPlus && NewSSPtr &&
404 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
405 Template, MemberOfUnknownSpecialization))) {
406 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
407 isClassName, HasTrailingDot, ObjectTypePtr,
408 IsCtorOrDtorName,
409 WantNontrivialTypeSourceInfo,
410 IsClassTemplateDeductionContext);
411 if (Ty) {
412 diagnoseTypo(Correction,
413 PDiag(diag::err_unknown_type_or_class_name_suggest)
414 << Result.getLookupName() << isClassName);
415 if (SS && NNS)
416 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
417 *CorrectedII = NewII;
418 return Ty;
419 }
420 }
421 }
422 Result.suppressDiagnostics();
423 return nullptr;
425 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
426 QualType T = Context.getDependentNameType(ElaboratedTypeKeyword::None,
427 SS->getScopeRep(), &II);
428 TypeLocBuilder TLB;
432 TL.setNameLoc(NameLoc);
434 }
435 [[fallthrough]];
438 Result.suppressDiagnostics();
439 return nullptr;
440
442 // Recover from type-hiding ambiguities by hiding the type. We'll
443 // do the lookup again when looking for an object, and we can
444 // diagnose the error then. If we don't do this, then the error
445 // about hiding the type will be immediately followed by an error
446 // that only makes sense if the identifier was treated like a type.
447 if (Result.getAmbiguityKind() == LookupAmbiguityKind::AmbiguousTagHiding) {
448 Result.suppressDiagnostics();
449 return nullptr;
450 }
451
452 // Look to see if we have a type anywhere in the list of results.
453 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
454 Res != ResEnd; ++Res) {
455 NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
457 RealRes) ||
458 (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
459 if (!IIDecl ||
460 // Make the selection of the recovery decl deterministic.
461 RealRes->getLocation() < IIDecl->getLocation()) {
462 IIDecl = RealRes;
463 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
464 }
465 }
466 }
467
468 if (!IIDecl) {
469 // None of the entities we found is a type, so there is no way
470 // to even assume that the result is a type. In this case, don't
471 // complain about the ambiguity. The parser will either try to
472 // perform this lookup again (e.g., as an object name), which
473 // will produce the ambiguity, or will complain that it expected
474 // a type name.
475 Result.suppressDiagnostics();
476 return nullptr;
477 }
478
479 // We found a type within the ambiguous lookup; diagnose the
480 // ambiguity and then return that type. This might be the right
481 // answer, or it might not be, but it suppresses any attempt to
482 // perform the name lookup again.
483 break;
484
486 IIDecl = Result.getFoundDecl();
487 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
488 break;
489 }
490
491 assert(IIDecl && "Didn't find decl");
492
493 TypeLocBuilder TLB;
494 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
495 checkTypeDeclType(LookupCtx,
496 IsImplicitTypename ? DiagCtorKind::Implicit
498 TD, NameLoc);
499 QualType T;
500 if (FoundUsingShadow) {
502 SS ? SS->getScopeRep() : std::nullopt,
503 FoundUsingShadow);
504 if (!WantNontrivialTypeSourceInfo)
505 return ParsedType::make(T);
506 TLB.push<UsingTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),
509 NameLoc);
510 } else if (auto *Tag = dyn_cast<TagDecl>(TD)) {
512 SS ? SS->getScopeRep() : std::nullopt, Tag,
513 /*OwnsTag=*/false);
514 if (!WantNontrivialTypeSourceInfo)
515 return ParsedType::make(T);
516 auto TL = TLB.push<TagTypeLoc>(T);
518 TL.setQualifierLoc(SS ? SS->getWithLocInContext(Context)
520 TL.setNameLoc(NameLoc);
521 } else if (auto *TN = dyn_cast<TypedefNameDecl>(TD);
522 TN && !isa<ObjCTypeParamDecl>(TN)) {
523 T = Context.getTypedefType(ElaboratedTypeKeyword::None,
524 SS ? SS->getScopeRep() : std::nullopt, TN);
525 if (!WantNontrivialTypeSourceInfo)
526 return ParsedType::make(T);
527 TLB.push<TypedefTypeLoc>(T).set(
528 /*ElaboratedKeywordLoc=*/SourceLocation(),
530 NameLoc);
531 } else if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(TD)) {
532 T = Context.getUnresolvedUsingType(ElaboratedTypeKeyword::None,
533 SS ? SS->getScopeRep() : std::nullopt,
534 UD);
535 if (!WantNontrivialTypeSourceInfo)
536 return ParsedType::make(T);
537 TLB.push<UnresolvedUsingTypeLoc>(T).set(
538 /*ElaboratedKeywordLoc=*/SourceLocation(),
540 NameLoc);
541 } else {
542 T = Context.getTypeDeclType(TD);
543 if (!WantNontrivialTypeSourceInfo)
544 return ParsedType::make(T);
546 TLB.push<ObjCTypeParamTypeLoc>(T).setNameLoc(NameLoc);
547 else
548 TLB.pushTypeSpec(T).setNameLoc(NameLoc);
549 }
551 }
552 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
553 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
554 if (!HasTrailingDot) {
555 // FIXME: Support UsingType for this case.
556 QualType T = Context.getObjCInterfaceType(IDecl);
557 if (!WantNontrivialTypeSourceInfo)
558 return ParsedType::make(T);
559 auto TL = TLB.push<ObjCInterfaceTypeLoc>(T);
560 TL.setNameLoc(NameLoc);
561 // FIXME: Pass in this source location.
562 TL.setNameEndLoc(NameLoc);
564 }
565 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
566 (void)DiagnoseUseOfDecl(UD, NameLoc);
567 // Recover with 'int'
568 return ParsedType::make(Context.IntTy);
569 } else if (AllowDeducedTemplate) {
570 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
571 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
572 // FIXME: Support UsingType here.
573 TemplateName Template = Context.getQualifiedTemplateName(
574 SS ? SS->getScopeRep() : std::nullopt, /*TemplateKeyword=*/false,
575 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
576 QualType T = Context.getDeducedTemplateSpecializationType(
580 TL.setNameLoc(NameLoc);
581 TL.setQualifierLoc(SS ? SS->getWithLocInContext(Context)
584 }
585 }
586
587 // As it's not plausibly a type, suppress diagnostics.
588 Result.suppressDiagnostics();
589 return nullptr;
590}
591
592// Builds a fake NNS for the given decl context.
595 for (;; DC = DC->getLookupParent()) {
596 DC = DC->getPrimaryContext();
597 auto *ND = dyn_cast<NamespaceDecl>(DC);
598 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
599 return NestedNameSpecifier(Context, ND, std::nullopt);
600 if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
601 return NestedNameSpecifier(Context.getCanonicalTagType(RD)->getTypePtr());
604 }
605 llvm_unreachable("something isn't in TU scope?");
606}
607
608/// Find the parent class with dependent bases of the innermost enclosing method
609/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
610/// up allowing unqualified dependent type names at class-level, which MSVC
611/// correctly rejects.
612static const CXXRecordDecl *
614 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
615 DC = DC->getPrimaryContext();
616 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
617 if (MD->getParent()->hasAnyDependentBases())
618 return MD->getParent();
619 }
620 return nullptr;
621}
622
624 SourceLocation NameLoc,
625 bool IsTemplateTypeArg) {
626 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
627
628 NestedNameSpecifier NNS = std::nullopt;
629 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
630 // If we weren't able to parse a default template argument, delay lookup
631 // until instantiation time by making a non-dependent DependentTypeName. We
632 // pretend we saw a NestedNameSpecifier referring to the current scope, and
633 // lookup is retried.
634 // FIXME: This hurts our diagnostic quality, since we get errors like "no
635 // type named 'Foo' in 'current_namespace'" when the user didn't write any
636 // name specifiers.
638 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
639 } else if (const CXXRecordDecl *RD =
641 // Build a DependentNameType that will perform lookup into RD at
642 // instantiation time.
643 NNS = NestedNameSpecifier(Context.getCanonicalTagType(RD)->getTypePtr());
644
645 // Diagnose that this identifier was undeclared, and retry the lookup during
646 // template instantiation.
647 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
648 << RD;
649 } else {
650 // This is not a situation that we should recover from.
651 return ParsedType();
652 }
653
654 QualType T =
655 Context.getDependentNameType(ElaboratedTypeKeyword::None, NNS, &II);
656
657 // Build type location information. We synthesized the qualifier, so we have
658 // to build a fake NestedNameSpecifierLoc.
659 NestedNameSpecifierLocBuilder NNSLocBuilder;
660 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
661 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
662
663 TypeLocBuilder Builder;
664 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
665 DepTL.setNameLoc(NameLoc);
667 DepTL.setQualifierLoc(QualifierLoc);
668 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
669}
670
672 // Do a tag name lookup in this scope.
673 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
674 LookupName(R, S, false);
677 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
678 switch (TD->getTagKind()) {
684 return DeclSpec::TST_union;
686 return DeclSpec::TST_class;
688 return DeclSpec::TST_enum;
689 }
690 }
691
693}
694
696 if (!CurContext->isRecord())
697 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
698
699 switch (SS->getScopeRep().getKind()) {
701 return true;
703 QualType T(SS->getScopeRep().getAsType(), 0);
704 for (const auto &Base : cast<CXXRecordDecl>(CurContext)->bases())
705 if (Context.hasSameUnqualifiedType(T, Base.getType()))
706 return true;
707 [[fallthrough]];
708 }
709 default:
710 return S->isFunctionPrototypeScope();
711 }
712}
713
715 SourceLocation IILoc,
716 Scope *S,
717 CXXScopeSpec *SS,
718 ParsedType &SuggestedType,
719 bool IsTemplateName) {
720 // Don't report typename errors for editor placeholders.
721 if (II->isEditorPlaceholder())
722 return;
723 // We don't have anything to suggest (yet).
724 SuggestedType = nullptr;
725
726 // There may have been a typo in the name of the type. Look up typo
727 // results, in case we have something that we can suggest.
728 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
729 /*AllowTemplates=*/IsTemplateName,
730 /*AllowNonTemplates=*/!IsTemplateName);
731 if (TypoCorrection Corrected =
734 // FIXME: Support error recovery for the template-name case.
735 bool CanRecover = !IsTemplateName;
736 if (Corrected.isKeyword()) {
737 // We corrected to a keyword.
738 diagnoseTypo(Corrected,
739 PDiag(IsTemplateName ? diag::err_no_template_suggest
740 : diag::err_unknown_typename_suggest)
741 << II);
742 II = Corrected.getCorrectionAsIdentifierInfo();
743 } else {
744 // We found a similarly-named type or interface; suggest that.
745 if (!SS || !SS->isSet()) {
746 diagnoseTypo(Corrected,
747 PDiag(IsTemplateName ? diag::err_no_template_suggest
748 : diag::err_unknown_typename_suggest)
749 << II, CanRecover);
750 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
751 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
752 bool DroppedSpecifier =
753 Corrected.WillReplaceSpecifier() && II->getName() == CorrectedStr;
754 diagnoseTypo(Corrected,
755 PDiag(IsTemplateName
756 ? diag::err_no_member_template_suggest
757 : diag::err_unknown_nested_typename_suggest)
758 << II << DC << DroppedSpecifier << SS->getRange(),
759 CanRecover);
760 } else {
761 llvm_unreachable("could not have corrected a typo here");
762 }
763
764 if (!CanRecover)
765 return;
766
767 CXXScopeSpec tmpSS;
768 if (Corrected.getCorrectionSpecifier())
769 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
770 SourceRange(IILoc));
771 // FIXME: Support class template argument deduction here.
772 SuggestedType =
773 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
774 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
775 /*IsCtorOrDtorName=*/false,
776 /*WantNontrivialTypeSourceInfo=*/true);
777 }
778 return;
779 }
780
781 if (getLangOpts().CPlusPlus && !IsTemplateName) {
782 // See if II is a class template that the user forgot to pass arguments to.
783 UnqualifiedId Name;
784 Name.setIdentifier(II, IILoc);
785 CXXScopeSpec EmptySS;
786 TemplateTy TemplateResult;
787 bool MemberOfUnknownSpecialization;
788 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
789 Name, nullptr, true, TemplateResult,
790 MemberOfUnknownSpecialization) == TNK_Type_template) {
791 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
792 return;
793 }
794 }
795
796 // FIXME: Should we move the logic that tries to recover from a missing tag
797 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
798
799 if (!SS || (!SS->isSet() && !SS->isInvalid()))
800 Diag(IILoc, IsTemplateName ? diag::err_no_template
801 : diag::err_unknown_typename)
802 << II;
803 else if (DeclContext *DC = computeDeclContext(*SS, false))
804 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
805 : diag::err_typename_nested_not_found)
806 << II << DC << SS->getRange();
807 else if (SS->isValid() && SS->getScopeRep().containsErrors()) {
808 SuggestedType =
809 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
810 } else if (isDependentScopeSpecifier(*SS)) {
811 unsigned DiagID = diag::err_typename_missing;
812 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
813 DiagID = diag::ext_typename_missing;
814
815 SuggestedType =
816 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
817
818 Diag(SS->getRange().getBegin(), DiagID)
819 << GetTypeFromParser(SuggestedType)
820 << SourceRange(SS->getRange().getBegin(), IILoc)
821 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
822 } else {
823 assert(SS && SS->isInvalid() &&
824 "Invalid scope specifier has already been diagnosed");
825 }
826}
827
828/// Determine whether the given result set contains either a type name
829/// or
830static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
831 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
832 NextToken.is(tok::less);
833
834 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
836 return true;
837
838 if (CheckTemplate && isa<TemplateDecl>(*I))
839 return true;
840 }
841
842 return false;
843}
844
845static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
846 Scope *S, CXXScopeSpec &SS,
847 IdentifierInfo *&Name,
848 SourceLocation NameLoc) {
849 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
850 SemaRef.LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
851 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
852 StringRef FixItTagName;
853 switch (Tag->getTagKind()) {
855 FixItTagName = "class ";
856 break;
857
859 FixItTagName = "enum ";
860 break;
861
863 FixItTagName = "struct ";
864 break;
865
867 FixItTagName = "__interface ";
868 break;
869
871 FixItTagName = "union ";
872 break;
873 }
874
875 StringRef TagName = FixItTagName.drop_back();
876 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
877 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
878 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
879
880 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
881 I != IEnd; ++I)
882 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
883 << Name << TagName;
884
885 // Replace lookup results with just the tag decl.
886 Result.clear(Sema::LookupTagName);
887 SemaRef.LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType());
888 return true;
889 }
890
891 return false;
892}
893
895 IdentifierInfo *&Name,
896 SourceLocation NameLoc,
897 const Token &NextToken,
899 DeclarationNameInfo NameInfo(Name, NameLoc);
900 ObjCMethodDecl *CurMethod = getCurMethodDecl();
901
902 assert(NextToken.isNot(tok::coloncolon) &&
903 "parse nested name specifiers before calling ClassifyName");
904 if (getLangOpts().CPlusPlus && SS.isSet() &&
905 isCurrentClassName(*Name, S, &SS)) {
906 // Per [class.qual]p2, this names the constructors of SS, not the
907 // injected-class-name. We don't have a classification for that.
908 // There's not much point caching this result, since the parser
909 // will reject it later.
911 }
912
913 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
914 LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType(),
915 /*AllowBuiltinCreation=*/!CurMethod);
916
917 if (SS.isInvalid())
919
920 // For unqualified lookup in a class template in MSVC mode, look into
921 // dependent base classes where the primary class template is known.
922 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
923 if (ParsedType TypeInBase =
924 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
925 return TypeInBase;
926 }
927
928 // Perform lookup for Objective-C instance variables (including automatically
929 // synthesized instance variables), if we're in an Objective-C method.
930 // FIXME: This lookup really, really needs to be folded in to the normal
931 // unqualified lookup mechanism.
932 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
933 DeclResult Ivar = ObjC().LookupIvarInObjCMethod(Result, S, Name);
934 if (Ivar.isInvalid())
936 if (Ivar.isUsable())
938
939 // We defer builtin creation until after ivar lookup inside ObjC methods.
940 if (Result.empty())
942 }
943
944 bool SecondTry = false;
945 bool IsFilteredTemplateName = false;
946
947Corrected:
948 switch (Result.getResultKind()) {
950 // If an unqualified-id is followed by a '(', then we have a function
951 // call.
952 if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
953 // In C++, this is an ADL-only call.
954 // FIXME: Reference?
957
958 // C90 6.3.2.2:
959 // If the expression that precedes the parenthesized argument list in a
960 // function call consists solely of an identifier, and if no
961 // declaration is visible for this identifier, the identifier is
962 // implicitly declared exactly as if, in the innermost block containing
963 // the function call, the declaration
964 //
965 // extern int identifier ();
966 //
967 // appeared.
968 //
969 // We also allow this in C99 as an extension. However, this is not
970 // allowed in all language modes as functions without prototypes may not
971 // be supported.
972 if (getLangOpts().implicitFunctionsAllowed()) {
973 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
975 }
976 }
977
978 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
979 // In C++20 onwards, this could be an ADL-only call to a function
980 // template, and we're required to assume that this is a template name.
981 //
982 // FIXME: Find a way to still do typo correction in this case.
984 Context.getAssumedTemplateName(NameInfo.getName());
986 }
987
988 // In C, we first see whether there is a tag type by the same name, in
989 // which case it's likely that the user just forgot to write "enum",
990 // "struct", or "union".
991 if (!getLangOpts().CPlusPlus && !SecondTry &&
992 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
993 break;
994 }
995
996 // Perform typo correction to determine if there is another name that is
997 // close to this name.
998 if (!SecondTry && CCC) {
999 SecondTry = true;
1000 if (TypoCorrection Corrected =
1001 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
1002 &SS, *CCC, CorrectTypoKind::ErrorRecovery)) {
1003 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
1004 unsigned QualifiedDiag = diag::err_no_member_suggest;
1005
1006 NamedDecl *FirstDecl = Corrected.getFoundDecl();
1007 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
1008 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1009 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
1010 UnqualifiedDiag = diag::err_no_template_suggest;
1011 QualifiedDiag = diag::err_no_member_template_suggest;
1012 } else if (UnderlyingFirstDecl &&
1013 (isa<TypeDecl>(UnderlyingFirstDecl) ||
1014 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
1015 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
1016 UnqualifiedDiag = diag::err_unknown_typename_suggest;
1017 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
1018 }
1019
1020 if (SS.isEmpty()) {
1021 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
1022 } else {// FIXME: is this even reachable? Test it.
1023 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1024 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
1025 Name->getName() == CorrectedStr;
1026 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
1027 << Name << computeDeclContext(SS, false)
1028 << DroppedSpecifier << SS.getRange());
1029 }
1030
1031 // Update the name, so that the caller has the new name.
1032 Name = Corrected.getCorrectionAsIdentifierInfo();
1033
1034 // Typo correction corrected to a keyword.
1035 if (Corrected.isKeyword())
1036 return Name;
1037
1038 // Also update the LookupResult...
1039 // FIXME: This should probably go away at some point
1040 Result.clear();
1041 Result.setLookupName(Corrected.getCorrection());
1042 if (FirstDecl)
1043 Result.addDecl(FirstDecl);
1044
1045 // If we found an Objective-C instance variable, let
1046 // LookupInObjCMethod build the appropriate expression to
1047 // reference the ivar.
1048 // FIXME: This is a gross hack.
1049 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1050 DeclResult R =
1051 ObjC().LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1052 if (R.isInvalid())
1054 if (R.isUsable())
1055 return NameClassification::NonType(Ivar);
1056 }
1057
1058 goto Corrected;
1059 }
1060 }
1061
1062 // We failed to correct; just fall through and let the parser deal with it.
1063 Result.suppressDiagnostics();
1065
1067 // We performed name lookup into the current instantiation, and there were
1068 // dependent bases, so we treat this result the same way as any other
1069 // dependent nested-name-specifier.
1070
1071 // C++ [temp.res]p2:
1072 // A name used in a template declaration or definition and that is
1073 // dependent on a template-parameter is assumed not to name a type
1074 // unless the applicable name lookup finds a type name or the name is
1075 // qualified by the keyword typename.
1076 //
1077 // FIXME: If the next token is '<', we might want to ask the parser to
1078 // perform some heroics to see if we actually have a
1079 // template-argument-list, which would indicate a missing 'template'
1080 // keyword here.
1082 }
1083
1087 break;
1088
1090 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1091 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1092 /*AllowDependent=*/false)) {
1093 // C++ [temp.local]p3:
1094 // A lookup that finds an injected-class-name (10.2) can result in an
1095 // ambiguity in certain cases (for example, if it is found in more than
1096 // one base class). If all of the injected-class-names that are found
1097 // refer to specializations of the same class template, and if the name
1098 // is followed by a template-argument-list, the reference refers to the
1099 // class template itself and not a specialization thereof, and is not
1100 // ambiguous.
1101 //
1102 // This filtering can make an ambiguous result into an unambiguous one,
1103 // so try again after filtering out template names.
1105 if (!Result.isAmbiguous()) {
1106 IsFilteredTemplateName = true;
1107 break;
1108 }
1109 }
1110
1111 // Diagnose the ambiguity and return an error.
1113 }
1114
1115 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1116 (IsFilteredTemplateName ||
1118 Result, /*AllowFunctionTemplates=*/true,
1119 /*AllowDependent=*/false,
1120 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1122 // C++ [temp.names]p3:
1123 // After name lookup (3.4) finds that a name is a template-name or that
1124 // an operator-function-id or a literal- operator-id refers to a set of
1125 // overloaded functions any member of which is a function template if
1126 // this is followed by a <, the < is always taken as the delimiter of a
1127 // template-argument-list and never as the less-than operator.
1128 // C++2a [temp.names]p2:
1129 // A name is also considered to refer to a template if it is an
1130 // unqualified-id followed by a < and name lookup finds either one
1131 // or more functions or finds nothing.
1132 if (!IsFilteredTemplateName)
1134
1135 bool IsFunctionTemplate;
1136 bool IsVarTemplate;
1138 if (Result.end() - Result.begin() > 1) {
1139 IsFunctionTemplate = true;
1140 Template = Context.getOverloadedTemplateName(Result.begin(),
1141 Result.end());
1142 } else if (!Result.empty()) {
1144 *Result.begin(), /*AllowFunctionTemplates=*/true,
1145 /*AllowDependent=*/false));
1146 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1147 IsVarTemplate = isa<VarTemplateDecl>(TD);
1148
1149 UsingShadowDecl *FoundUsingShadow =
1150 dyn_cast<UsingShadowDecl>(*Result.begin());
1151 assert(!FoundUsingShadow ||
1152 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1153 Template = Context.getQualifiedTemplateName(
1154 SS.getScopeRep(),
1155 /*TemplateKeyword=*/false,
1156 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
1157 } else {
1158 // All results were non-template functions. This is a function template
1159 // name.
1160 IsFunctionTemplate = true;
1161 Template = Context.getAssumedTemplateName(NameInfo.getName());
1162 }
1163
1164 if (IsFunctionTemplate) {
1165 // Function templates always go through overload resolution, at which
1166 // point we'll perform the various checks (e.g., accessibility) we need
1167 // to based on which function we selected.
1168 Result.suppressDiagnostics();
1169
1171 }
1172
1173 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1175 }
1176
1177 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1178 QualType T;
1179 TypeLocBuilder TLB;
1180 if (const auto *USD = dyn_cast<UsingShadowDecl>(Found)) {
1181 T = Context.getUsingType(ElaboratedTypeKeyword::None, SS.getScopeRep(),
1182 USD);
1183 TLB.push<UsingTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),
1184 SS.getWithLocInContext(Context), NameLoc);
1185 } else {
1186 T = Context.getTypeDeclType(ElaboratedTypeKeyword::None, SS.getScopeRep(),
1187 Type);
1188 if (isa<TagType>(T)) {
1189 auto TTL = TLB.push<TagTypeLoc>(T);
1191 TTL.setQualifierLoc(SS.getWithLocInContext(Context));
1192 TTL.setNameLoc(NameLoc);
1193 } else if (isa<TypedefType>(T)) {
1194 TLB.push<TypedefTypeLoc>(T).set(
1195 /*ElaboratedKeywordLoc=*/SourceLocation(),
1196 SS.getWithLocInContext(Context), NameLoc);
1197 } else if (isa<UnresolvedUsingType>(T)) {
1198 TLB.push<UnresolvedUsingTypeLoc>(T).set(
1199 /*ElaboratedKeywordLoc=*/SourceLocation(),
1200 SS.getWithLocInContext(Context), NameLoc);
1201 } else {
1202 TLB.pushTypeSpec(T).setNameLoc(NameLoc);
1203 }
1204 }
1206 };
1207
1208 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1209 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1210 DiagnoseUseOfDecl(Type, NameLoc);
1211 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1212 return BuildTypeFor(Type, *Result.begin());
1213 }
1214
1215 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1216 if (!Class) {
1217 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1218 if (ObjCCompatibleAliasDecl *Alias =
1219 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1220 Class = Alias->getClassInterface();
1221 }
1222
1223 if (Class) {
1224 DiagnoseUseOfDecl(Class, NameLoc);
1225
1226 if (NextToken.is(tok::period)) {
1227 // Interface. <something> is parsed as a property reference expression.
1228 // Just return "unknown" as a fall-through for now.
1229 Result.suppressDiagnostics();
1231 }
1232
1233 QualType T = Context.getObjCInterfaceType(Class);
1234 return ParsedType::make(T);
1235 }
1236
1238 // We want to preserve the UsingShadowDecl for concepts.
1239 if (auto *USD = dyn_cast<UsingShadowDecl>(Result.getRepresentativeDecl()))
1243 }
1244
1245 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1246 (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1248 }
1249
1250 // We can have a type template here if we're classifying a template argument.
1255
1256 // Check for a tag type hidden by a non-type decl in a few cases where it
1257 // seems likely a type is wanted instead of the non-type that was found.
1258 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1259 if ((NextToken.is(tok::identifier) ||
1260 (NextIsOp &&
1261 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1262 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1263 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1264 DiagnoseUseOfDecl(Type, NameLoc);
1265 return BuildTypeFor(Type, *Result.begin());
1266 }
1267
1268 // If we already know which single declaration is referenced, just annotate
1269 // that declaration directly. Defer resolving even non-overloaded class
1270 // member accesses, as we need to defer certain access checks until we know
1271 // the context.
1272 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1273 if (Result.isSingleResult() && !ADL &&
1274 (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(FirstDecl)))
1275 return NameClassification::NonType(Result.getRepresentativeDecl());
1276
1277 // Otherwise, this is an overload set that we will need to resolve later.
1278 Result.suppressDiagnostics();
1280 Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1281 Result.getLookupNameInfo(), ADL, Result.begin(), Result.end(),
1282 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false));
1283}
1284
1287 SourceLocation NameLoc) {
1288 assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1289 CXXScopeSpec SS;
1290 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1291 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1292}
1293
1296 IdentifierInfo *Name,
1297 SourceLocation NameLoc,
1298 bool IsAddressOfOperand) {
1299 DeclarationNameInfo NameInfo(Name, NameLoc);
1300 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1301 NameInfo, IsAddressOfOperand,
1302 /*TemplateArgs=*/nullptr);
1303}
1304
1307 SourceLocation NameLoc,
1308 const Token &NextToken) {
1309 if (getCurMethodDecl() && SS.isEmpty())
1310 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1311 return ObjC().BuildIvarRefExpr(S, NameLoc, Ivar);
1312
1313 // Reconstruct the lookup result.
1314 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1315 Result.addDecl(Found);
1316 Result.resolveKind();
1317
1318 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1319 return BuildDeclarationNameExpr(SS, Result, ADL, /*AcceptInvalidDecl=*/true);
1320}
1321
1323 // For an implicit class member access, transform the result into a member
1324 // access expression if necessary.
1325 auto *ULE = cast<UnresolvedLookupExpr>(E);
1326 if ((*ULE->decls_begin())->isCXXClassMember()) {
1327 CXXScopeSpec SS;
1328 SS.Adopt(ULE->getQualifierLoc());
1329
1330 // Reconstruct the lookup result.
1331 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1333 Result.setNamingClass(ULE->getNamingClass());
1334 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1335 Result.addDecl(*I, I.getAccess());
1336 Result.resolveKind();
1338 nullptr, S);
1339 }
1340
1341 // Otherwise, this is already in the form we needed, and no further checks
1342 // are necessary.
1343 return ULE;
1344}
1345
1365
1367 assert(DC->getLexicalParent() == CurContext &&
1368 "The next DeclContext should be lexically contained in the current one.");
1369 CurContext = DC;
1370 S->setEntity(DC);
1371}
1372
1374 assert(CurContext && "DeclContext imbalance!");
1375
1376 CurContext = CurContext->getLexicalParent();
1377 assert(CurContext && "Popped translation unit!");
1378}
1379
1381 Decl *D) {
1382 // Unlike PushDeclContext, the context to which we return is not necessarily
1383 // the containing DC of TD, because the new context will be some pre-existing
1384 // TagDecl definition instead of a fresh one.
1385 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1386 CurContext = cast<TagDecl>(D)->getDefinition();
1387 assert(CurContext && "skipping definition of undefined tag");
1388 // Start lookups from the parent of the current context; we don't want to look
1389 // into the pre-existing complete definition.
1390 S->setEntity(CurContext->getLookupParent());
1391 return Result;
1392}
1393
1397
1399 // C++0x [basic.lookup.unqual]p13:
1400 // A name used in the definition of a static data member of class
1401 // X (after the qualified-id of the static member) is looked up as
1402 // if the name was used in a member function of X.
1403 // C++0x [basic.lookup.unqual]p14:
1404 // If a variable member of a namespace is defined outside of the
1405 // scope of its namespace then any name used in the definition of
1406 // the variable member (after the declarator-id) is looked up as
1407 // if the definition of the variable member occurred in its
1408 // namespace.
1409 // Both of these imply that we should push a scope whose context
1410 // is the semantic context of the declaration. We can't use
1411 // PushDeclContext here because that context is not necessarily
1412 // lexically contained in the current context. Fortunately,
1413 // the containing scope should have the appropriate information.
1414
1415 assert(!S->getEntity() && "scope already has entity");
1416
1417#ifndef NDEBUG
1418 Scope *Ancestor = S->getParent();
1419 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1420 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1421#endif
1422
1423 CurContext = DC;
1424 S->setEntity(DC);
1425
1426 if (S->getParent()->isTemplateParamScope()) {
1427 // Also set the corresponding entities for all immediately-enclosing
1428 // template parameter scopes.
1430 }
1431}
1432
1434 assert(S->getEntity() == CurContext && "Context imbalance!");
1435
1436 // Switch back to the lexical context. The safety of this is
1437 // enforced by an assert in EnterDeclaratorContext.
1438 Scope *Ancestor = S->getParent();
1439 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1440 CurContext = Ancestor->getEntity();
1441
1442 // We don't need to do anything with the scope, which is going to
1443 // disappear.
1444}
1445
1447 assert(S->isTemplateParamScope() &&
1448 "expected to be initializing a template parameter scope");
1449
1450 // C++20 [temp.local]p7:
1451 // In the definition of a member of a class template that appears outside
1452 // of the class template definition, the name of a member of the class
1453 // template hides the name of a template-parameter of any enclosing class
1454 // templates (but not a template-parameter of the member if the member is a
1455 // class or function template).
1456 // C++20 [temp.local]p9:
1457 // In the definition of a class template or in the definition of a member
1458 // of such a template that appears outside of the template definition, for
1459 // each non-dependent base class (13.8.2.1), if the name of the base class
1460 // or the name of a member of the base class is the same as the name of a
1461 // template-parameter, the base class name or member name hides the
1462 // template-parameter name (6.4.10).
1463 //
1464 // This means that a template parameter scope should be searched immediately
1465 // after searching the DeclContext for which it is a template parameter
1466 // scope. For example, for
1467 // template<typename T> template<typename U> template<typename V>
1468 // void N::A<T>::B<U>::f(...)
1469 // we search V then B<U> (and base classes) then U then A<T> (and base
1470 // classes) then T then N then ::.
1471 unsigned ScopeDepth = getTemplateDepth(S);
1472 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1473 DeclContext *SearchDCAfterScope = DC;
1474 for (; DC; DC = DC->getLookupParent()) {
1475 if (const TemplateParameterList *TPL =
1476 cast<Decl>(DC)->getDescribedTemplateParams()) {
1477 unsigned DCDepth = TPL->getDepth() + 1;
1478 if (DCDepth > ScopeDepth)
1479 continue;
1480 if (ScopeDepth == DCDepth)
1481 SearchDCAfterScope = DC = DC->getLookupParent();
1482 break;
1483 }
1484 }
1485 S->setLookupEntity(SearchDCAfterScope);
1486 }
1487}
1488
1490 // We assume that the caller has already called
1491 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1492 FunctionDecl *FD = D->getAsFunction();
1493 if (!FD)
1494 return;
1495
1496 // Same implementation as PushDeclContext, but enters the context
1497 // from the lexical parent, rather than the top-level class.
1498 assert(CurContext == FD->getLexicalParent() &&
1499 "The next DeclContext should be lexically contained in the current one.");
1500 CurContext = FD;
1502
1503 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1504 ParmVarDecl *Param = FD->getParamDecl(P);
1505 // If the parameter has an identifier, then add it to the scope
1506 if (Param->getIdentifier()) {
1507 S->AddDecl(Param);
1508 IdResolver.AddDecl(Param);
1509 }
1510 }
1511}
1512
1514 // Same implementation as PopDeclContext, but returns to the lexical parent,
1515 // rather than the top-level class.
1516 assert(CurContext && "DeclContext imbalance!");
1517 CurContext = CurContext->getLexicalParent();
1518 assert(CurContext && "Popped translation unit!");
1519}
1520
1521/// Determine whether overloading is allowed for a new function
1522/// declaration considering prior declarations of the same name.
1523///
1524/// This routine determines whether overloading is possible, not
1525/// whether a new declaration actually overloads a previous one.
1526/// It will return true in C++ (where overloads are always permitted)
1527/// or, as a C extension, when either the new declaration or a
1528/// previous one is declared with the 'overloadable' attribute.
1530 ASTContext &Context,
1531 const FunctionDecl *New) {
1532 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1533 return true;
1534
1535 // Multiversion function declarations are not overloads in the
1536 // usual sense of that term, but lookup will report that an
1537 // overload set was found if more than one multiversion function
1538 // declaration is present for the same name. It is therefore
1539 // inadequate to assume that some prior declaration(s) had
1540 // the overloadable attribute; checking is required. Since one
1541 // declaration is permitted to omit the attribute, it is necessary
1542 // to check at least two; hence the 'any_of' check below. Note that
1543 // the overloadable attribute is implicitly added to declarations
1544 // that were required to have it but did not.
1545 if (Previous.getResultKind() == LookupResultKind::FoundOverloaded) {
1546 return llvm::any_of(Previous, [](const NamedDecl *ND) {
1547 return ND->hasAttr<OverloadableAttr>();
1548 });
1549 } else if (Previous.getResultKind() == LookupResultKind::Found)
1550 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1551
1552 return false;
1553}
1554
1555void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1556 // Move up the scope chain until we find the nearest enclosing
1557 // non-transparent context. The declaration will be introduced into this
1558 // scope.
1559 while (S->getEntity() && S->getEntity()->isTransparentContext())
1560 S = S->getParent();
1561
1562 // Add scoped declarations into their context, so that they can be
1563 // found later. Declarations without a context won't be inserted
1564 // into any context.
1565 if (AddToContext)
1566 CurContext->addDecl(D);
1567
1568 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1569 // are function-local declarations.
1570 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1571 return;
1572
1573 // Template instantiations should also not be pushed into scope.
1574 if (isa<FunctionDecl>(D) &&
1575 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1576 return;
1577
1578 if (isa<UsingEnumDecl>(D) && D->getDeclName().isEmpty()) {
1579 S->AddDecl(D);
1580 return;
1581 }
1582 // If this replaces anything in the current scope,
1584 IEnd = IdResolver.end();
1585 for (; I != IEnd; ++I) {
1586 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1587 S->RemoveDecl(*I);
1588 IdResolver.RemoveDecl(*I);
1589
1590 // Should only need to replace one decl.
1591 break;
1592 }
1593 }
1594
1595 S->AddDecl(D);
1596
1597 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1598 // Implicitly-generated labels may end up getting generated in an order that
1599 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1600 // the label at the appropriate place in the identifier chain.
1601 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1602 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1603 if (IDC == CurContext) {
1604 if (!S->isDeclScope(*I))
1605 continue;
1606 } else if (IDC->Encloses(CurContext))
1607 break;
1608 }
1609
1610 IdResolver.InsertDeclAfter(I, D);
1611 } else {
1612 IdResolver.AddDecl(D);
1613 }
1615}
1616
1618 bool AllowInlineNamespace) const {
1619 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1620}
1621
1623 DeclContext *TargetDC = DC->getPrimaryContext();
1624 do {
1625 if (DeclContext *ScopeDC = S->getEntity())
1626 if (ScopeDC->getPrimaryContext() == TargetDC)
1627 return S;
1628 } while ((S = S->getParent()));
1629
1630 return nullptr;
1631}
1632
1634 DeclContext*,
1635 ASTContext&);
1636
1638 bool ConsiderLinkage,
1639 bool AllowInlineNamespace) {
1641 while (F.hasNext()) {
1642 NamedDecl *D = F.next();
1643
1644 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1645 continue;
1646
1647 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1648 continue;
1649
1650 F.erase();
1651 }
1652
1653 F.done();
1654}
1655
1657 if (auto *VD = dyn_cast<VarDecl>(D))
1658 return VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1659 if (auto *FD = dyn_cast<FunctionDecl>(D))
1660 return FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1661 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1662 return RD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1663
1664 return false;
1665}
1666
1668 // [module.interface]p7:
1669 // A declaration is attached to a module as follows:
1670 // - If the declaration is a non-dependent friend declaration that nominates a
1671 // function with a declarator-id that is a qualified-id or template-id or that
1672 // nominates a class other than with an elaborated-type-specifier with neither
1673 // a nested-name-specifier nor a simple-template-id, it is attached to the
1674 // module to which the friend is attached ([basic.link]).
1675 if (New->getFriendObjectKind() &&
1676 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1677 New->setLocalOwningModule(Old->getOwningModule());
1679 return false;
1680 }
1681
1682 // Although we have questions for the module ownership of implicit
1683 // instantiations, it should be sure that we shouldn't diagnose the
1684 // redeclaration of incorrect module ownership for different implicit
1685 // instantiations in different modules. We will diagnose the redeclaration of
1686 // incorrect module ownership for the template itself.
1688 return false;
1689
1690 Module *NewM = New->getOwningModule();
1691 Module *OldM = Old->getOwningModule();
1692
1693 if (NewM && NewM->isPrivateModule())
1694 NewM = NewM->Parent;
1695 if (OldM && OldM->isPrivateModule())
1696 OldM = OldM->Parent;
1697
1698 if (NewM == OldM)
1699 return false;
1700
1701 if (NewM && OldM) {
1702 // A module implementation unit has visibility of the decls in its
1703 // implicitly imported interface.
1704 if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1705 return false;
1706
1707 // Partitions are part of the module, but a partition could import another
1708 // module, so verify that the PMIs agree.
1709 if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1710 getASTContext().isInSameModule(NewM, OldM))
1711 return false;
1712 }
1713
1714 bool NewIsModuleInterface = NewM && NewM->isNamedModule();
1715 bool OldIsModuleInterface = OldM && OldM->isNamedModule();
1716 if (NewIsModuleInterface || OldIsModuleInterface) {
1717 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1718 // if a declaration of D [...] appears in the purview of a module, all
1719 // other such declarations shall appear in the purview of the same module
1720 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1721 << New
1722 << NewIsModuleInterface
1723 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1724 << OldIsModuleInterface
1725 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1726 Diag(Old->getLocation(), diag::note_previous_declaration);
1727 New->setInvalidDecl();
1728 return true;
1729 }
1730
1731 return false;
1732}
1733
1735 // [module.interface]p1:
1736 // An export-declaration shall inhabit a namespace scope.
1737 //
1738 // So it is meaningless to talk about redeclaration which is not at namespace
1739 // scope.
1740 if (!New->getLexicalDeclContext()
1741 ->getNonTransparentContext()
1742 ->isFileContext() ||
1743 !Old->getLexicalDeclContext()
1745 ->isFileContext())
1746 return false;
1747
1748 bool IsNewExported = New->isInExportDeclContext();
1749 bool IsOldExported = Old->isInExportDeclContext();
1750
1751 // It should be irrevelant if both of them are not exported.
1752 if (!IsNewExported && !IsOldExported)
1753 return false;
1754
1755 if (IsOldExported)
1756 return false;
1757
1758 // If the Old declaration are not attached to named modules
1759 // and the New declaration are attached to global module.
1760 // It should be fine to allow the export since it doesn't change
1761 // the linkage of declarations. See
1762 // https://github.com/llvm/llvm-project/issues/98583 for details.
1763 if (!Old->isInNamedModule() && New->getOwningModule() &&
1764 New->getOwningModule()->isImplicitGlobalModule())
1765 return false;
1766
1767 assert(IsNewExported);
1768
1769 auto Lk = Old->getFormalLinkage();
1770 int S = 0;
1771 if (Lk == Linkage::Internal)
1772 S = 1;
1773 else if (Lk == Linkage::Module)
1774 S = 2;
1775 Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1776 Diag(Old->getLocation(), diag::note_previous_declaration);
1777 return true;
1778}
1779
1782 return true;
1783
1785 return true;
1786
1787 return false;
1788}
1789
1791 const NamedDecl *Old) const {
1792 assert(getASTContext().isSameEntity(New, Old) &&
1793 "New and Old are not the same definition, we should diagnostic it "
1794 "immediately instead of checking it.");
1795 assert(const_cast<Sema *>(this)->isReachable(New) &&
1796 const_cast<Sema *>(this)->isReachable(Old) &&
1797 "We shouldn't see unreachable definitions here.");
1798
1799 Module *NewM = New->getOwningModule();
1800 Module *OldM = Old->getOwningModule();
1801
1802 // We only checks for named modules here. The header like modules is skipped.
1803 // FIXME: This is not right if we import the header like modules in the module
1804 // purview.
1805 //
1806 // For example, assuming "header.h" provides definition for `D`.
1807 // ```C++
1808 // //--- M.cppm
1809 // export module M;
1810 // import "header.h"; // or #include "header.h" but import it by clang modules
1811 // actually.
1812 //
1813 // //--- Use.cpp
1814 // import M;
1815 // import "header.h"; // or uses clang modules.
1816 // ```
1817 //
1818 // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1819 // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1820 // reject it. But the current implementation couldn't detect the case since we
1821 // don't record the information about the importee modules.
1822 //
1823 // But this might not be painful in practice. Since the design of C++20 Named
1824 // Modules suggests us to use headers in global module fragment instead of
1825 // module purview.
1826 if (NewM && NewM->isHeaderLikeModule())
1827 NewM = nullptr;
1828 if (OldM && OldM->isHeaderLikeModule())
1829 OldM = nullptr;
1830
1831 if (!NewM && !OldM)
1832 return true;
1833
1834 // [basic.def.odr]p14.3
1835 // Each such definition shall not be attached to a named module
1836 // ([module.unit]).
1837 if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule()))
1838 return true;
1839
1840 // Then New and Old lives in the same TU if their share one same module unit.
1841 if (NewM)
1842 NewM = NewM->getTopLevelModule();
1843 if (OldM)
1844 OldM = OldM->getTopLevelModule();
1845 return OldM == NewM;
1846}
1847
1849 if (D->getDeclContext()->isFileContext())
1850 return false;
1851
1852 return isa<UsingShadowDecl>(D) ||
1855}
1856
1857/// Removes using shadow declarations not at class scope from the lookup
1858/// results.
1861 while (F.hasNext())
1863 F.erase();
1864
1865 F.done();
1866}
1867
1868/// Check for this common pattern:
1869/// @code
1870/// class S {
1871/// S(const S&); // DO NOT IMPLEMENT
1872/// void operator=(const S&); // DO NOT IMPLEMENT
1873/// };
1874/// @endcode
1876 // FIXME: Should check for private access too but access is set after we get
1877 // the decl here.
1879 return false;
1880
1881 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1882 return CD->isCopyConstructor();
1883 return D->isCopyAssignmentOperator();
1884}
1885
1886bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1887 const DeclContext *DC = D->getDeclContext();
1888 while (!DC->isTranslationUnit()) {
1889 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1890 if (!RD->hasNameForLinkage())
1891 return true;
1892 }
1893 DC = DC->getParent();
1894 }
1895
1896 return !D->isExternallyVisible();
1897}
1898
1899// FIXME: This needs to be refactored; some other isInMainFile users want
1900// these semantics.
1901static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1903 return false;
1904 return S.SourceMgr.isInMainFile(Loc);
1905}
1906
1908 assert(D);
1909
1910 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1911 return false;
1912
1913 // Ignore all entities declared within templates, and out-of-line definitions
1914 // of members of class templates.
1915 if (D->getDeclContext()->isDependentContext() ||
1917 return false;
1918
1919 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1920 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1921 return false;
1922 // A non-out-of-line declaration of a member specialization was implicitly
1923 // instantiated; it's the out-of-line declaration that we're interested in.
1924 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1925 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1926 return false;
1927
1928 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1929 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1930 return false;
1931 } else {
1932 // 'static inline' functions are defined in headers; don't warn.
1933 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1934 return false;
1935 }
1936
1937 if (FD->doesThisDeclarationHaveABody() &&
1938 Context.DeclMustBeEmitted(FD))
1939 return false;
1940 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1941 // Constants and utility variables are defined in headers with internal
1942 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1943 // like "inline".)
1944 if (!isMainFileLoc(*this, VD->getLocation()))
1945 return false;
1946
1947 if (Context.DeclMustBeEmitted(VD))
1948 return false;
1949
1950 if (VD->isStaticDataMember() &&
1951 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1952 return false;
1953 if (VD->isStaticDataMember() &&
1954 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1955 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1956 return false;
1957
1958 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1959 return false;
1960 } else {
1961 return false;
1962 }
1963
1964 // Only warn for unused decls internal to the translation unit.
1965 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1966 // for inline functions defined in the main source file, for instance.
1967 return mightHaveNonExternalLinkage(D);
1968}
1969
1971 if (!D)
1972 return;
1973
1974 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1975 const FunctionDecl *First = FD->getFirstDecl();
1977 return; // First should already be in the vector.
1978 }
1979
1980 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1981 const VarDecl *First = VD->getFirstDecl();
1983 return; // First should already be in the vector.
1984 }
1985
1987 UnusedFileScopedDecls.push_back(D);
1988}
1989
1990static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts,
1991 const NamedDecl *D) {
1992 if (D->isInvalidDecl())
1993 return false;
1994
1995 if (const auto *DD = dyn_cast<DecompositionDecl>(D)) {
1996 // For a decomposition declaration, warn if none of the bindings are
1997 // referenced, instead of if the variable itself is referenced (which
1998 // it is, by the bindings' expressions).
1999 bool IsAllIgnored = true;
2000 for (const auto *BD : DD->bindings()) {
2001 if (BD->isReferenced())
2002 return false;
2003 IsAllIgnored = IsAllIgnored && (BD->isPlaceholderVar(LangOpts) ||
2004 BD->hasAttr<UnusedAttr>());
2005 }
2006 if (IsAllIgnored)
2007 return false;
2008 } else if (!D->getDeclName()) {
2009 return false;
2010 } else if (D->isReferenced() || D->isUsed()) {
2011 return false;
2012 }
2013
2014 if (D->isPlaceholderVar(LangOpts))
2015 return false;
2016
2017 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||
2018 D->hasAttr<CleanupAttr>())
2019 return false;
2020
2021 if (isa<LabelDecl>(D))
2022 return true;
2023
2024 // Except for labels, we only care about unused decls that are local to
2025 // functions.
2026 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
2027 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
2028 // For dependent types, the diagnostic is deferred.
2029 WithinFunction =
2030 WithinFunction || (R->isLocalClass() && !R->isDependentType());
2031 if (!WithinFunction)
2032 return false;
2033
2034 if (isa<TypedefNameDecl>(D))
2035 return true;
2036
2037 // White-list anything that isn't a local variable.
2039 return false;
2040
2041 // Types of valid local variables should be complete, so this should succeed.
2042 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2043
2044 const Expr *Init = VD->getInit();
2045 if (const auto *Cleanups = dyn_cast_if_present<ExprWithCleanups>(Init))
2046 Init = Cleanups->getSubExpr();
2047
2048 const auto *Ty = VD->getType().getTypePtr();
2049
2050 // Only look at the outermost level of typedef.
2051 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
2052 // Allow anything marked with __attribute__((unused)).
2053 if (TT->getDecl()->hasAttr<UnusedAttr>())
2054 return false;
2055 }
2056
2057 // Warn for reference variables whose initializtion performs lifetime
2058 // extension.
2059 if (const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(Init);
2060 MTE && MTE->getExtendingDecl()) {
2061 Ty = VD->getType().getNonReferenceType().getTypePtr();
2062 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
2063 }
2064
2065 // If we failed to complete the type for some reason, or if the type is
2066 // dependent, don't diagnose the variable.
2067 if (Ty->isIncompleteType() || Ty->isDependentType())
2068 return false;
2069
2070 // Look at the element type to ensure that the warning behaviour is
2071 // consistent for both scalars and arrays.
2072 Ty = Ty->getBaseElementTypeUnsafe();
2073
2074 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2075 if (Tag->hasAttr<UnusedAttr>())
2076 return false;
2077
2078 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2079 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2080 return false;
2081
2082 if (Init) {
2083 const auto *Construct =
2084 dyn_cast<CXXConstructExpr>(Init->IgnoreImpCasts());
2085 if (Construct && !Construct->isElidable()) {
2086 const CXXConstructorDecl *CD = Construct->getConstructor();
2087 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2088 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2089 return false;
2090 }
2091
2092 // Suppress the warning if we don't know how this is constructed, and
2093 // it could possibly be non-trivial constructor.
2094 if (Init->isTypeDependent()) {
2095 for (const CXXConstructorDecl *Ctor : RD->ctors())
2096 if (!Ctor->isTrivial())
2097 return false;
2098 }
2099
2100 // Suppress the warning if the constructor is unresolved because
2101 // its arguments are dependent.
2103 return false;
2104 }
2105 }
2106 }
2107
2108 // TODO: __attribute__((unused)) templates?
2109 }
2110
2111 return true;
2112}
2113
2115 FixItHint &Hint) {
2116 if (isa<LabelDecl>(D)) {
2118 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
2119 /*SkipTrailingWhitespaceAndNewline=*/false);
2120 if (AfterColon.isInvalid())
2121 return;
2123 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
2124 }
2125}
2126
2129 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2130}
2131
2133 DiagReceiverTy DiagReceiver) {
2134 if (D->isDependentType())
2135 return;
2136
2137 for (auto *TmpD : D->decls()) {
2138 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2139 DiagnoseUnusedDecl(T, DiagReceiver);
2140 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2141 DiagnoseUnusedNestedTypedefs(R, DiagReceiver);
2142 }
2143}
2144
2147 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2148}
2149
2152 return;
2153
2154 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2155 // typedefs can be referenced later on, so the diagnostics are emitted
2156 // at end-of-translation-unit.
2158 return;
2159 }
2160
2161 FixItHint Hint;
2163
2164 unsigned DiagID;
2165 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2166 DiagID = diag::warn_unused_exception_param;
2167 else if (isa<LabelDecl>(D))
2168 DiagID = diag::warn_unused_label;
2169 else
2170 DiagID = diag::warn_unused_variable;
2171
2172 SourceLocation DiagLoc = D->getLocation();
2173 DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
2174}
2175
2177 DiagReceiverTy DiagReceiver) {
2178 // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2179 // it's not really unused.
2180 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>())
2181 return;
2182
2183 // In C++, `_` variables behave as if they were maybe_unused
2184 if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(getLangOpts()))
2185 return;
2186
2187 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2188
2189 if (Ty->isReferenceType() || Ty->isDependentType())
2190 return;
2191
2192 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2193 if (Tag->hasAttr<UnusedAttr>())
2194 return;
2195 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2196 // mimic gcc's behavior.
2197 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag);
2198 RD && !RD->hasAttr<WarnUnusedAttr>())
2199 return;
2200 }
2201
2202 // Don't warn about __block Objective-C pointer variables, as they might
2203 // be assigned in the block but not used elsewhere for the purpose of lifetime
2204 // extension.
2205 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2206 return;
2207
2208 // Don't warn about Objective-C pointer variables with precise lifetime
2209 // semantics; they can be used to ensure ARC releases the object at a known
2210 // time, which may mean assignment but no other references.
2211 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2212 return;
2213
2214 auto iter = RefsMinusAssignments.find(VD);
2215 if (iter == RefsMinusAssignments.end())
2216 return;
2217
2218 assert(iter->getSecond() >= 0 &&
2219 "Found a negative number of references to a VarDecl");
2220 if (int RefCnt = iter->getSecond(); RefCnt > 0) {
2221 // Assume the given VarDecl is "used" if its ref count stored in
2222 // `RefMinusAssignments` is positive, with one exception.
2223 //
2224 // For a C++ variable whose decl (with initializer) entirely consist the
2225 // condition expression of a if/while/for construct,
2226 // Clang creates a DeclRefExpr for the condition expression rather than a
2227 // BinaryOperator of AssignmentOp. Thus, the C++ variable's ref
2228 // count stored in `RefMinusAssignment` equals 1 when the variable is never
2229 // used in the body of the if/while/for construct.
2230 bool UnusedCXXCondDecl = VD->isCXXCondDecl() && (RefCnt == 1);
2231 if (!UnusedCXXCondDecl)
2232 return;
2233 }
2234
2235 unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2236 : diag::warn_unused_but_set_variable;
2237 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2238}
2239
2241 Sema::DiagReceiverTy DiagReceiver) {
2242 // Verify that we have no forward references left. If so, there was a goto
2243 // or address of a label taken, but no definition of it. Label fwd
2244 // definitions are indicated with a null substmt which is also not a resolved
2245 // MS inline assembly label name.
2246 bool Diagnose = false;
2247 if (L->isMSAsmLabel())
2248 Diagnose = !L->isResolvedMSAsmLabel();
2249 else
2250 Diagnose = L->getStmt() == nullptr;
2251 if (Diagnose)
2252 DiagReceiver(L->getLocation(), S.PDiag(diag::err_undeclared_label_use)
2253 << L);
2254}
2255
2257 S->applyNRVO();
2258
2259 if (S->decl_empty()) return;
2261 "Scope shouldn't contain decls!");
2262
2263 /// We visit the decls in non-deterministic order, but we want diagnostics
2264 /// emitted in deterministic order. Collect any diagnostic that may be emitted
2265 /// and sort the diagnostics before emitting them, after we visited all decls.
2266 struct LocAndDiag {
2267 SourceLocation Loc;
2268 std::optional<SourceLocation> PreviousDeclLoc;
2270 };
2272 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2273 DeclDiags.push_back(LocAndDiag{Loc, std::nullopt, std::move(PD)});
2274 };
2275 auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2276 SourceLocation PreviousDeclLoc,
2277 PartialDiagnostic PD) {
2278 DeclDiags.push_back(LocAndDiag{Loc, PreviousDeclLoc, std::move(PD)});
2279 };
2280
2281 for (auto *TmpD : S->decls()) {
2282 assert(TmpD && "This decl didn't get pushed??");
2283
2284 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2285 NamedDecl *D = cast<NamedDecl>(TmpD);
2286
2287 // Diagnose unused variables in this scope.
2289 DiagnoseUnusedDecl(D, addDiag);
2290 if (const auto *RD = dyn_cast<RecordDecl>(D))
2291 DiagnoseUnusedNestedTypedefs(RD, addDiag);
2292 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2293 DiagnoseUnusedButSetDecl(VD, addDiag);
2294 RefsMinusAssignments.erase(VD);
2295 }
2296 }
2297
2298 if (!D->getDeclName()) continue;
2299
2300 // If this was a forward reference to a label, verify it was defined.
2301 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2302 CheckPoppedLabel(LD, *this, addDiag);
2303
2304 // Partial translation units that are created in incremental processing must
2305 // not clean up the IdResolver because PTUs should take into account the
2306 // declarations that came from previous PTUs.
2307 if (!PP.isIncrementalProcessingEnabled() || getLangOpts().ObjC ||
2309 IdResolver.RemoveDecl(D);
2310
2311 // Warn on it if we are shadowing a declaration.
2312 auto ShadowI = ShadowingDecls.find(D);
2313 if (ShadowI != ShadowingDecls.end()) {
2314 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2315 addDiagWithPrev(D->getLocation(), FD->getLocation(),
2316 PDiag(diag::warn_ctor_parm_shadows_field)
2317 << D << FD << FD->getParent());
2318 }
2319 ShadowingDecls.erase(ShadowI);
2320 }
2321 }
2322
2323 llvm::sort(DeclDiags,
2324 [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2325 // The particular order for diagnostics is not important, as long
2326 // as the order is deterministic. Using the raw location is going
2327 // to generally be in source order unless there are macro
2328 // expansions involved.
2329 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2330 });
2331 for (const LocAndDiag &D : DeclDiags) {
2332 Diag(D.Loc, D.PD);
2333 if (D.PreviousDeclLoc)
2334 Diag(*D.PreviousDeclLoc, diag::note_previous_declaration);
2335 }
2336}
2337
2339 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2340 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2341 (S->isClassScope() && !getLangOpts().CPlusPlus))
2342 S = S->getParent();
2343 return S;
2344}
2345
2346static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2348 switch (Error) {
2350 return "";
2352 return BuiltinInfo.getHeaderName(ID);
2354 return "stdio.h";
2356 return "setjmp.h";
2358 return "ucontext.h";
2359 }
2360 llvm_unreachable("unhandled error kind");
2361}
2362
2364 unsigned ID, SourceLocation Loc) {
2365 DeclContext *Parent = Context.getTranslationUnitDecl();
2366
2367 if (getLangOpts().CPlusPlus) {
2369 Context, Parent, Loc, Loc, LinkageSpecLanguageIDs::C, false);
2370 CLinkageDecl->setImplicit();
2371 Parent->addDecl(CLinkageDecl);
2372 Parent = CLinkageDecl;
2373 }
2374
2376 if (Context.BuiltinInfo.isImmediate(ID)) {
2377 assert(getLangOpts().CPlusPlus20 &&
2378 "consteval builtins should only be available in C++20 mode");
2379 ConstexprKind = ConstexprSpecKind::Consteval;
2380 }
2381
2383 Context, Parent, Loc, Loc, II, Type, /*TInfo=*/nullptr, SC_Extern,
2384 getCurFPFeatures().isFPConstrained(), /*isInlineSpecified=*/false,
2385 Type->isFunctionProtoType(), ConstexprKind);
2386 New->setImplicit();
2387 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2388
2389 // Create Decl objects for each parameter, adding them to the
2390 // FunctionDecl.
2391 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2393 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2395 Context, New, SourceLocation(), SourceLocation(), nullptr,
2396 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2397 parm->setScopeInfo(0, i);
2398 Params.push_back(parm);
2399 }
2400 New->setParams(Params);
2401 }
2402
2404 return New;
2405}
2406
2408 Scope *S, bool ForRedeclaration,
2409 SourceLocation Loc) {
2411
2413 QualType R = Context.GetBuiltinType(ID, Error);
2414 if (Error) {
2415 if (!ForRedeclaration)
2416 return nullptr;
2417
2418 // If we have a builtin without an associated type we should not emit a
2419 // warning when we were not able to find a type for it.
2421 Context.BuiltinInfo.allowTypeMismatch(ID))
2422 return nullptr;
2423
2424 // If we could not find a type for setjmp it is because the jmp_buf type was
2425 // not defined prior to the setjmp declaration.
2427 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2428 << Context.BuiltinInfo.getName(ID);
2429 return nullptr;
2430 }
2431
2432 // Generally, we emit a warning that the declaration requires the
2433 // appropriate header.
2434 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2435 << getHeaderName(Context.BuiltinInfo, ID, Error)
2436 << Context.BuiltinInfo.getName(ID);
2437 return nullptr;
2438 }
2439
2440 if (!ForRedeclaration &&
2441 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2442 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2443 Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2444 : diag::ext_implicit_lib_function_decl)
2445 << Context.BuiltinInfo.getName(ID) << R;
2446 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2447 Diag(Loc, diag::note_include_header_or_declare)
2448 << Header << Context.BuiltinInfo.getName(ID);
2449 }
2450
2451 if (R.isNull())
2452 return nullptr;
2453
2454 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2456
2457 // TUScope is the translation-unit scope to insert this function into.
2458 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2459 // relate Scopes to DeclContexts, and probably eliminate CurContext
2460 // entirely, but we're not there yet.
2461 DeclContext *SavedContext = CurContext;
2462 CurContext = New->getDeclContext();
2464 CurContext = SavedContext;
2465 return New;
2466}
2467
2468/// Typedef declarations don't have linkage, but they still denote the same
2469/// entity if their types are the same.
2470/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2471/// isSameEntity.
2472static void
2475 // This is only interesting when modules are enabled.
2476 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2477 return;
2478
2479 // Empty sets are uninteresting.
2480 if (Previous.empty())
2481 return;
2482
2483 LookupResult::Filter Filter = Previous.makeFilter();
2484 while (Filter.hasNext()) {
2485 NamedDecl *Old = Filter.next();
2486
2487 // Non-hidden declarations are never ignored.
2488 if (S.isVisible(Old))
2489 continue;
2490
2491 // Declarations of the same entity are not ignored, even if they have
2492 // different linkages.
2493 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2494 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2495 Decl->getUnderlyingType()))
2496 continue;
2497
2498 // If both declarations give a tag declaration a typedef name for linkage
2499 // purposes, then they declare the same entity.
2500 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2501 Decl->getAnonDeclWithTypedefName())
2502 continue;
2503 }
2504
2505 Filter.erase();
2506 }
2507
2508 Filter.done();
2509}
2510
2512 QualType OldType;
2513 if (const TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2514 OldType = OldTypedef->getUnderlyingType();
2515 else
2516 OldType = Context.getTypeDeclType(Old);
2517 QualType NewType = New->getUnderlyingType();
2518
2519 if (NewType->isVariablyModifiedType()) {
2520 // Must not redefine a typedef with a variably-modified type.
2521 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2522 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2523 << Kind << NewType;
2524 if (Old->getLocation().isValid())
2525 notePreviousDefinition(Old, New->getLocation());
2526 New->setInvalidDecl();
2527 return true;
2528 }
2529
2530 if (OldType != NewType &&
2531 !OldType->isDependentType() &&
2532 !NewType->isDependentType() &&
2533 !Context.hasSameType(OldType, NewType)) {
2534 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2535 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2536 << Kind << NewType << OldType;
2537 if (Old->getLocation().isValid())
2538 notePreviousDefinition(Old, New->getLocation());
2539 New->setInvalidDecl();
2540 return true;
2541 }
2542 return false;
2543}
2544
2546 LookupResult &OldDecls) {
2547 // If the new decl is known invalid already, don't bother doing any
2548 // merging checks.
2549 if (New->isInvalidDecl()) return;
2550
2551 // Allow multiple definitions for ObjC built-in typedefs.
2552 // FIXME: Verify the underlying types are equivalent!
2553 if (getLangOpts().ObjC) {
2554 const IdentifierInfo *TypeID = New->getIdentifier();
2555 switch (TypeID->getLength()) {
2556 default: break;
2557 case 2:
2558 {
2559 if (!TypeID->isStr("id"))
2560 break;
2561 QualType T = New->getUnderlyingType();
2562 if (!T->isPointerType())
2563 break;
2564 if (!T->isVoidPointerType()) {
2565 QualType PT = T->castAs<PointerType>()->getPointeeType();
2566 if (!PT->isStructureType())
2567 break;
2568 }
2569 Context.setObjCIdRedefinitionType(T);
2570 // Install the built-in type for 'id', ignoring the current definition.
2571 New->setModedTypeSourceInfo(New->getTypeSourceInfo(),
2572 Context.getObjCIdType());
2573 return;
2574 }
2575 case 5:
2576 if (!TypeID->isStr("Class"))
2577 break;
2578 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2579 // Install the built-in type for 'Class', ignoring the current definition.
2580 New->setModedTypeSourceInfo(New->getTypeSourceInfo(),
2581 Context.getObjCClassType());
2582 return;
2583 case 3:
2584 if (!TypeID->isStr("SEL"))
2585 break;
2586 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2587 // Install the built-in type for 'SEL', ignoring the current definition.
2588 New->setModedTypeSourceInfo(New->getTypeSourceInfo(),
2589 Context.getObjCSelType());
2590 return;
2591 }
2592 // Fall through - the typedef name was not a builtin type.
2593 }
2594
2595 // Verify the old decl was also a type.
2596 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2597 if (!Old) {
2598 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2599 << New->getDeclName();
2600
2601 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2602 if (OldD->getLocation().isValid())
2603 notePreviousDefinition(OldD, New->getLocation());
2604
2605 return New->setInvalidDecl();
2606 }
2607
2608 // If the old declaration is invalid, just give up here.
2609 if (Old->isInvalidDecl())
2610 return New->setInvalidDecl();
2611
2612 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2613 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2614 auto *NewTag = New->getAnonDeclWithTypedefName();
2615 NamedDecl *Hidden = nullptr;
2616 if (OldTag && NewTag &&
2617 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2618 !hasVisibleDefinition(OldTag, &Hidden)) {
2619 // There is a definition of this tag, but it is not visible. Use it
2620 // instead of our tag.
2621 if (OldTD->isModed())
2622 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2623 OldTD->getUnderlyingType());
2624 else
2625 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2626
2627 // Make the old tag definition visible.
2629
2631 }
2632 }
2633
2634 // If the typedef types are not identical, reject them in all languages and
2635 // with any extensions enabled.
2636 if (isIncompatibleTypedef(Old, New))
2637 return;
2638
2639 // The types match. Link up the redeclaration chain and merge attributes if
2640 // the old declaration was a typedef.
2641 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2642 New->setPreviousDecl(Typedef);
2644 }
2645
2646 if (getLangOpts().MicrosoftExt)
2647 return;
2648
2649 if (getLangOpts().CPlusPlus) {
2650 // C++ [dcl.typedef]p2:
2651 // In a given non-class scope, a typedef specifier can be used to
2652 // redefine the name of any type declared in that scope to refer
2653 // to the type to which it already refers.
2655 return;
2656
2657 // C++0x [dcl.typedef]p4:
2658 // In a given class scope, a typedef specifier can be used to redefine
2659 // any class-name declared in that scope that is not also a typedef-name
2660 // to refer to the type to which it already refers.
2661 //
2662 // This wording came in via DR424, which was a correction to the
2663 // wording in DR56, which accidentally banned code like:
2664 //
2665 // struct S {
2666 // typedef struct A { } A;
2667 // };
2668 //
2669 // in the C++03 standard. We implement the C++0x semantics, which
2670 // allow the above but disallow
2671 //
2672 // struct S {
2673 // typedef int I;
2674 // typedef int I;
2675 // };
2676 //
2677 // since that was the intent of DR56.
2678 if (!isa<TypedefNameDecl>(Old))
2679 return;
2680
2681 Diag(New->getLocation(), diag::err_redefinition)
2682 << New->getDeclName();
2683 notePreviousDefinition(Old, New->getLocation());
2684 return New->setInvalidDecl();
2685 }
2686
2687 // Modules always permit redefinition of typedefs, as does C11.
2688 if (getLangOpts().Modules || getLangOpts().C11)
2689 return;
2690
2691 // If we have a redefinition of a typedef in C, emit a warning. This warning
2692 // is normally mapped to an error, but can be controlled with
2693 // -Wtypedef-redefinition. If either the original or the redefinition is
2694 // in a system header, don't emit this for compatibility with GCC.
2695 if (getDiagnostics().getSuppressSystemWarnings() &&
2696 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2697 (Old->isImplicit() ||
2698 Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2699 Context.getSourceManager().isInSystemHeader(New->getLocation())))
2700 return;
2701
2702 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2703 << New->getDeclName();
2704 notePreviousDefinition(Old, New->getLocation());
2705}
2706
2708 // If this was an unscoped enumeration, yank all of its enumerators
2709 // out of the scope.
2710 if (auto *ED = dyn_cast<EnumDecl>(New); ED && !ED->isScoped()) {
2711 Scope *EnumScope = getNonFieldDeclScope(S);
2712 for (auto *ECD : ED->enumerators()) {
2713 assert(EnumScope->isDeclScope(ECD));
2714 EnumScope->RemoveDecl(ECD);
2715 IdResolver.RemoveDecl(ECD);
2716 }
2717 }
2718}
2719
2720/// DeclhasAttr - returns true if decl Declaration already has the target
2721/// attribute.
2722static bool DeclHasAttr(const Decl *D, const Attr *A) {
2723 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2724 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2725 for (const auto *i : D->attrs())
2726 if (i->getKind() == A->getKind()) {
2727 if (Ann) {
2728 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2729 return true;
2730 continue;
2731 }
2732 // FIXME: Don't hardcode this check
2733 if (OA && isa<OwnershipAttr>(i))
2734 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2735 return true;
2736 }
2737
2738 return false;
2739}
2740
2742 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2743 return VD->isThisDeclarationADefinition();
2744 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2745 return TD->isCompleteDefinition() || TD->isBeingDefined();
2746 return true;
2747}
2748
2749/// Merge alignment attributes from \p Old to \p New, taking into account the
2750/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2751///
2752/// \return \c true if any attributes were added to \p New.
2753static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2754 // Look for alignas attributes on Old, and pick out whichever attribute
2755 // specifies the strictest alignment requirement.
2756 AlignedAttr *OldAlignasAttr = nullptr;
2757 AlignedAttr *OldStrictestAlignAttr = nullptr;
2758 unsigned OldAlign = 0;
2759 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2760 // FIXME: We have no way of representing inherited dependent alignments
2761 // in a case like:
2762 // template<int A, int B> struct alignas(A) X;
2763 // template<int A, int B> struct alignas(B) X {};
2764 // For now, we just ignore any alignas attributes which are not on the
2765 // definition in such a case.
2766 if (I->isAlignmentDependent())
2767 return false;
2768
2769 if (I->isAlignas())
2770 OldAlignasAttr = I;
2771
2772 unsigned Align = I->getAlignment(S.Context);
2773 if (Align > OldAlign) {
2774 OldAlign = Align;
2775 OldStrictestAlignAttr = I;
2776 }
2777 }
2778
2779 // Look for alignas attributes on New.
2780 AlignedAttr *NewAlignasAttr = nullptr;
2781 unsigned NewAlign = 0;
2782 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2783 if (I->isAlignmentDependent())
2784 return false;
2785
2786 if (I->isAlignas())
2787 NewAlignasAttr = I;
2788
2789 unsigned Align = I->getAlignment(S.Context);
2790 if (Align > NewAlign)
2791 NewAlign = Align;
2792 }
2793
2794 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2795 // Both declarations have 'alignas' attributes. We require them to match.
2796 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2797 // fall short. (If two declarations both have alignas, they must both match
2798 // every definition, and so must match each other if there is a definition.)
2799
2800 // If either declaration only contains 'alignas(0)' specifiers, then it
2801 // specifies the natural alignment for the type.
2802 if (OldAlign == 0 || NewAlign == 0) {
2803 QualType Ty;
2804 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2805 Ty = VD->getType();
2806 else
2808
2809 if (OldAlign == 0)
2810 OldAlign = S.Context.getTypeAlign(Ty);
2811 if (NewAlign == 0)
2812 NewAlign = S.Context.getTypeAlign(Ty);
2813 }
2814
2815 if (OldAlign != NewAlign) {
2816 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2819 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2820 }
2821 }
2822
2823 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2824 // C++11 [dcl.align]p6:
2825 // if any declaration of an entity has an alignment-specifier,
2826 // every defining declaration of that entity shall specify an
2827 // equivalent alignment.
2828 // C11 6.7.5/7:
2829 // If the definition of an object does not have an alignment
2830 // specifier, any other declaration of that object shall also
2831 // have no alignment specifier.
2832 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2833 << OldAlignasAttr;
2834 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2835 << OldAlignasAttr;
2836 }
2837
2838 bool AnyAdded = false;
2839
2840 // Ensure we have an attribute representing the strictest alignment.
2841 if (OldAlign > NewAlign) {
2842 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2843 Clone->setInherited(true);
2844 New->addAttr(Clone);
2845 AnyAdded = true;
2846 }
2847
2848 // Ensure we have an alignas attribute if the old declaration had one.
2849 if (OldAlignasAttr && !NewAlignasAttr &&
2850 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2851 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2852 Clone->setInherited(true);
2853 New->addAttr(Clone);
2854 AnyAdded = true;
2855 }
2856
2857 return AnyAdded;
2858}
2859
2860#define WANT_DECL_MERGE_LOGIC
2861#include "clang/Sema/AttrParsedAttrImpl.inc"
2862#undef WANT_DECL_MERGE_LOGIC
2863
2865 const InheritableAttr *Attr,
2867 // Diagnose any mutual exclusions between the attribute that we want to add
2868 // and attributes that already exist on the declaration.
2869 if (!DiagnoseMutualExclusions(S, D, Attr))
2870 return false;
2871
2872 // This function copies an attribute Attr from a previous declaration to the
2873 // new declaration D if the new declaration doesn't itself have that attribute
2874 // yet or if that attribute allows duplicates.
2875 // If you're adding a new attribute that requires logic different from
2876 // "use explicit attribute on decl if present, else use attribute from
2877 // previous decl", for example if the attribute needs to be consistent
2878 // between redeclarations, you need to call a custom merge function here.
2879 InheritableAttr *NewAttr = nullptr;
2880 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2881 NewAttr = S.mergeAvailabilityAttr(
2882 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2883 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2884 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2885 AA->getPriority(), AA->getEnvironment());
2886 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2887 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2888 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2889 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2890 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2891 NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2892 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2893 NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2894 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2895 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2896 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2897 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2898 FA->getFirstArg());
2899 else if (const auto *FMA = dyn_cast<FormatMatchesAttr>(Attr))
2900 NewAttr = S.mergeFormatMatchesAttr(
2901 D, *FMA, FMA->getType(), FMA->getFormatIdx(), FMA->getFormatString());
2902 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2903 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2904 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2905 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2906 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2907 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2908 IA->getInheritanceModel());
2909 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2910 NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2911 &S.Context.Idents.get(AA->getSpelling()));
2912 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2915 // CUDA target attributes are part of function signature for
2916 // overloading purposes and must not be merged.
2917 return false;
2918 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2919 NewAttr = S.mergeMinSizeAttr(D, *MA);
2920 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2921 NewAttr = S.Swift().mergeNameAttr(D, *SNA, SNA->getName());
2922 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2923 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2924 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2925 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2926 else if (isa<AlignedAttr>(Attr))
2927 // AlignedAttrs are handled separately, because we need to handle all
2928 // such attributes on a declaration at the same time.
2929 NewAttr = nullptr;
2934 NewAttr = nullptr;
2935 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2936 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2937 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2938 NewAttr = S.Wasm().mergeImportModuleAttr(D, *IMA);
2939 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2940 NewAttr = S.Wasm().mergeImportNameAttr(D, *INA);
2941 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2942 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2943 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2944 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2945 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2946 NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2947 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
2948 NewAttr = S.HLSL().mergeNumThreadsAttr(D, *NT, NT->getX(), NT->getY(),
2949 NT->getZ());
2950 else if (const auto *WS = dyn_cast<HLSLWaveSizeAttr>(Attr))
2951 NewAttr = S.HLSL().mergeWaveSizeAttr(D, *WS, WS->getMin(), WS->getMax(),
2952 WS->getPreferred(),
2953 WS->getSpelledArgsCount());
2954 else if (const auto *CI = dyn_cast<HLSLVkConstantIdAttr>(Attr))
2955 NewAttr = S.HLSL().mergeVkConstantIdAttr(D, *CI, CI->getId());
2956 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
2957 NewAttr = S.HLSL().mergeShaderAttr(D, *SA, SA->getType());
2958 else if (isa<SuppressAttr>(Attr))
2959 // Do nothing. Each redeclaration should be suppressed separately.
2960 NewAttr = nullptr;
2961 else if (const auto *RD = dyn_cast<OpenACCRoutineDeclAttr>(Attr))
2962 NewAttr = S.OpenACC().mergeRoutineDeclAttr(*RD);
2963 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2964 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2965
2966 if (NewAttr) {
2967 NewAttr->setInherited(true);
2968 D->addAttr(NewAttr);
2969 if (isa<MSInheritanceAttr>(NewAttr))
2971 return true;
2972 }
2973
2974 return false;
2975}
2976
2977static const NamedDecl *getDefinition(const Decl *D) {
2978 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
2979 if (const auto *Def = TD->getDefinition(); Def && !Def->isBeingDefined())
2980 return Def;
2981 return nullptr;
2982 }
2983 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2984 const VarDecl *Def = VD->getDefinition();
2985 if (Def)
2986 return Def;
2987 return VD->getActingDefinition();
2988 }
2989 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2990 const FunctionDecl *Def = nullptr;
2991 if (FD->isDefined(Def, true))
2992 return Def;
2993 }
2994 return nullptr;
2995}
2996
2997static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2998 for (const auto *Attribute : D->attrs())
2999 if (Attribute->getKind() == Kind)
3000 return true;
3001 return false;
3002}
3003
3004/// checkNewAttributesAfterDef - If we already have a definition, check that
3005/// there are no new attributes in this declaration.
3006static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
3007 if (!New->hasAttrs())
3008 return;
3009
3010 const NamedDecl *Def = getDefinition(Old);
3011 if (!Def || Def == New)
3012 return;
3013
3014 AttrVec &NewAttributes = New->getAttrs();
3015 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
3016 Attr *NewAttribute = NewAttributes[I];
3017
3018 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
3019 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
3020 SkipBodyInfo SkipBody;
3021 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
3022
3023 // If we're skipping this definition, drop the "alias" attribute.
3024 if (SkipBody.ShouldSkip) {
3025 NewAttributes.erase(NewAttributes.begin() + I);
3026 --E;
3027 continue;
3028 }
3029 } else {
3030 VarDecl *VD = cast<VarDecl>(New);
3031 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
3033 ? diag::err_alias_after_tentative
3034 : diag::err_redefinition;
3035 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
3036 if (Diag == diag::err_redefinition)
3037 S.notePreviousDefinition(Def, VD->getLocation());
3038 else
3039 S.Diag(Def->getLocation(), diag::note_previous_definition);
3040 VD->setInvalidDecl();
3041 }
3042 ++I;
3043 continue;
3044 }
3045
3046 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
3047 // Tentative definitions are only interesting for the alias check above.
3048 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
3049 ++I;
3050 continue;
3051 }
3052 }
3053
3054 if (hasAttribute(Def, NewAttribute->getKind())) {
3055 ++I;
3056 continue; // regular attr merging will take care of validating this.
3057 }
3058
3059 if (isa<C11NoReturnAttr>(NewAttribute)) {
3060 // C's _Noreturn is allowed to be added to a function after it is defined.
3061 ++I;
3062 continue;
3063 } else if (isa<UuidAttr>(NewAttribute)) {
3064 // msvc will allow a subsequent definition to add an uuid to a class
3065 ++I;
3066 continue;
3068 NewAttribute) &&
3069 NewAttribute->isStandardAttributeSyntax()) {
3070 // C++14 [dcl.attr.deprecated]p3: A name or entity declared without the
3071 // deprecated attribute can later be re-declared with the attribute and
3072 // vice-versa.
3073 // C++17 [dcl.attr.unused]p4: A name or entity declared without the
3074 // maybe_unused attribute can later be redeclared with the attribute and
3075 // vice versa.
3076 // C++20 [dcl.attr.nodiscard]p2: A name or entity declared without the
3077 // nodiscard attribute can later be redeclared with the attribute and
3078 // vice-versa.
3079 // C23 6.7.13.3p3, 6.7.13.4p3. and 6.7.13.5p5 give the same allowances.
3080 ++I;
3081 continue;
3082 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
3083 if (AA->isAlignas()) {
3084 // C++11 [dcl.align]p6:
3085 // if any declaration of an entity has an alignment-specifier,
3086 // every defining declaration of that entity shall specify an
3087 // equivalent alignment.
3088 // C11 6.7.5/7:
3089 // If the definition of an object does not have an alignment
3090 // specifier, any other declaration of that object shall also
3091 // have no alignment specifier.
3092 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
3093 << AA;
3094 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
3095 << AA;
3096 NewAttributes.erase(NewAttributes.begin() + I);
3097 --E;
3098 continue;
3099 }
3100 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
3101 // If there is a C definition followed by a redeclaration with this
3102 // attribute then there are two different definitions. In C++, prefer the
3103 // standard diagnostics.
3104 if (!S.getLangOpts().CPlusPlus) {
3105 S.Diag(NewAttribute->getLocation(),
3106 diag::err_loader_uninitialized_redeclaration);
3107 S.Diag(Def->getLocation(), diag::note_previous_definition);
3108 NewAttributes.erase(NewAttributes.begin() + I);
3109 --E;
3110 continue;
3111 }
3112 } else if (isa<SelectAnyAttr>(NewAttribute) &&
3113 cast<VarDecl>(New)->isInline() &&
3114 !cast<VarDecl>(New)->isInlineSpecified()) {
3115 // Don't warn about applying selectany to implicitly inline variables.
3116 // Older compilers and language modes would require the use of selectany
3117 // to make such variables inline, and it would have no effect if we
3118 // honored it.
3119 ++I;
3120 continue;
3121 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
3122 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3123 // declarations after definitions.
3124 ++I;
3125 continue;
3126 } else if (isa<SYCLKernelEntryPointAttr>(NewAttribute)) {
3127 // Elevate latent uses of the sycl_kernel_entry_point attribute to an
3128 // error since the definition will have already been created without
3129 // the semantic effects of the attribute having been applied.
3130 S.Diag(NewAttribute->getLocation(),
3131 diag::err_sycl_entry_point_after_definition)
3132 << NewAttribute;
3133 S.Diag(Def->getLocation(), diag::note_previous_definition);
3134 cast<SYCLKernelEntryPointAttr>(NewAttribute)->setInvalidAttr();
3135 ++I;
3136 continue;
3137 } else if (isa<SYCLExternalAttr>(NewAttribute)) {
3138 // SYCLExternalAttr may be added after a definition.
3139 ++I;
3140 continue;
3141 }
3142
3143 S.Diag(NewAttribute->getLocation(),
3144 diag::warn_attribute_precede_definition);
3145 S.Diag(Def->getLocation(), diag::note_previous_definition);
3146 NewAttributes.erase(NewAttributes.begin() + I);
3147 --E;
3148 }
3149}
3150
3151static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3152 const ConstInitAttr *CIAttr,
3153 bool AttrBeforeInit) {
3154 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3155
3156 // Figure out a good way to write this specifier on the old declaration.
3157 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3158 // enough of the attribute list spelling information to extract that without
3159 // heroics.
3160 std::string SuitableSpelling;
3161 if (S.getLangOpts().CPlusPlus20)
3162 SuitableSpelling = std::string(
3163 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
3164 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3165 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3166 InsertLoc, {tok::l_square, tok::l_square,
3167 S.PP.getIdentifierInfo("clang"), tok::coloncolon,
3168 S.PP.getIdentifierInfo("require_constant_initialization"),
3169 tok::r_square, tok::r_square}));
3170 if (SuitableSpelling.empty())
3171 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3172 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
3173 S.PP.getIdentifierInfo("require_constant_initialization"),
3174 tok::r_paren, tok::r_paren}));
3175 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3176 SuitableSpelling = "constinit";
3177 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3178 SuitableSpelling = "[[clang::require_constant_initialization]]";
3179 if (SuitableSpelling.empty())
3180 SuitableSpelling = "__attribute__((require_constant_initialization))";
3181 SuitableSpelling += " ";
3182
3183 if (AttrBeforeInit) {
3184 // extern constinit int a;
3185 // int a = 0; // error (missing 'constinit'), accepted as extension
3186 assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3187 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3188 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3189 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3190 } else {
3191 // int a = 0;
3192 // constinit extern int a; // error (missing 'constinit')
3193 S.Diag(CIAttr->getLocation(),
3194 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3195 : diag::warn_require_const_init_added_too_late)
3196 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3197 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3198 << CIAttr->isConstinit()
3199 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3200 }
3201}
3202
3205 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3206 UsedAttr *NewAttr = OldAttr->clone(Context);
3207 NewAttr->setInherited(true);
3208 New->addAttr(NewAttr);
3209 }
3210 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3211 RetainAttr *NewAttr = OldAttr->clone(Context);
3212 NewAttr->setInherited(true);
3213 New->addAttr(NewAttr);
3214 }
3215
3216 if (!Old->hasAttrs() && !New->hasAttrs())
3217 return;
3218
3219 // [dcl.constinit]p1:
3220 // If the [constinit] specifier is applied to any declaration of a
3221 // variable, it shall be applied to the initializing declaration.
3222 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3223 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3224 if (bool(OldConstInit) != bool(NewConstInit)) {
3225 const auto *OldVD = cast<VarDecl>(Old);
3226 auto *NewVD = cast<VarDecl>(New);
3227
3228 // Find the initializing declaration. Note that we might not have linked
3229 // the new declaration into the redeclaration chain yet.
3230 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3231 if (!InitDecl &&
3232 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3233 InitDecl = NewVD;
3234
3235 if (InitDecl == NewVD) {
3236 // This is the initializing declaration. If it would inherit 'constinit',
3237 // that's ill-formed. (Note that we do not apply this to the attribute
3238 // form).
3239 if (OldConstInit && OldConstInit->isConstinit())
3240 diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3241 /*AttrBeforeInit=*/true);
3242 } else if (NewConstInit) {
3243 // This is the first time we've been told that this declaration should
3244 // have a constant initializer. If we already saw the initializing
3245 // declaration, this is too late.
3246 if (InitDecl && InitDecl != NewVD) {
3247 diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3248 /*AttrBeforeInit=*/false);
3249 NewVD->dropAttr<ConstInitAttr>();
3250 }
3251 }
3252 }
3253
3254 // Attributes declared post-definition are currently ignored.
3255 checkNewAttributesAfterDef(*this, New, Old);
3256
3257 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3258 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3259 if (!OldA->isEquivalent(NewA)) {
3260 // This redeclaration changes __asm__ label.
3261 Diag(New->getLocation(), diag::err_different_asm_label);
3262 Diag(OldA->getLocation(), diag::note_previous_declaration);
3263 }
3264 } else if (Old->isUsed()) {
3265 // This redeclaration adds an __asm__ label to a declaration that has
3266 // already been ODR-used.
3267 Diag(New->getLocation(), diag::err_late_asm_label_name)
3268 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3269 }
3270 }
3271
3272 // Re-declaration cannot add abi_tag's.
3273 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3274 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3275 for (const auto &NewTag : NewAbiTagAttr->tags()) {
3276 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3277 Diag(NewAbiTagAttr->getLocation(),
3278 diag::err_new_abi_tag_on_redeclaration)
3279 << NewTag;
3280 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3281 }
3282 }
3283 } else {
3284 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3285 Diag(Old->getLocation(), diag::note_previous_declaration);
3286 }
3287 }
3288
3289 // This redeclaration adds a section attribute.
3290 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3291 if (auto *VD = dyn_cast<VarDecl>(New)) {
3292 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3293 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3294 Diag(Old->getLocation(), diag::note_previous_declaration);
3295 }
3296 }
3297 }
3298
3299 // Redeclaration adds code-seg attribute.
3300 const auto *NewCSA = New->getAttr<CodeSegAttr>();
3301 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3302 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3303 Diag(New->getLocation(), diag::warn_mismatched_section)
3304 << 0 /*codeseg*/;
3305 Diag(Old->getLocation(), diag::note_previous_declaration);
3306 }
3307
3308 if (!Old->hasAttrs())
3309 return;
3310
3311 bool foundAny = New->hasAttrs();
3312
3313 // Ensure that any moving of objects within the allocated map is done before
3314 // we process them.
3315 if (!foundAny) New->setAttrs(AttrVec());
3316
3317 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3318 // Ignore deprecated/unavailable/availability attributes if requested.
3320 if (isa<DeprecatedAttr>(I) ||
3323 switch (AMK) {
3325 continue;
3326
3331 LocalAMK = AMK;
3332 break;
3333 }
3334 }
3335
3336 // Already handled.
3337 if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3338 continue;
3339
3341 if (auto *FD = dyn_cast<FunctionDecl>(New);
3342 FD &&
3343 FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
3344 continue; // Don't propagate inferred noreturn attributes to explicit
3345 }
3346
3347 if (mergeDeclAttribute(*this, New, I, LocalAMK))
3348 foundAny = true;
3349 }
3350
3351 if (mergeAlignedAttrs(*this, New, Old))
3352 foundAny = true;
3353
3354 if (!foundAny) New->dropAttrs();
3355}
3356
3357// Returns the number of added attributes.
3358template <class T>
3359static unsigned propagateAttribute(ParmVarDecl *To, const ParmVarDecl *From,
3360 Sema &S) {
3361 unsigned found = 0;
3362 for (const auto *I : From->specific_attrs<T>()) {
3363 if (!DeclHasAttr(To, I)) {
3364 T *newAttr = cast<T>(I->clone(S.Context));
3365 newAttr->setInherited(true);
3366 To->addAttr(newAttr);
3367 ++found;
3368 }
3369 }
3370 return found;
3371}
3372
3373template <class F>
3374static void propagateAttributes(ParmVarDecl *To, const ParmVarDecl *From,
3375 F &&propagator) {
3376 if (!From->hasAttrs()) {
3377 return;
3378 }
3379
3380 bool foundAny = To->hasAttrs();
3381
3382 // Ensure that any moving of objects within the allocated map is
3383 // done before we process them.
3384 if (!foundAny)
3385 To->setAttrs(AttrVec());
3386
3387 foundAny |= std::forward<F>(propagator)(To, From) != 0;
3388
3389 if (!foundAny)
3390 To->dropAttrs();
3391}
3392
3393/// mergeParamDeclAttributes - Copy attributes from the old parameter
3394/// to the new one.
3396 const ParmVarDecl *oldDecl,
3397 Sema &S) {
3398 // C++11 [dcl.attr.depend]p2:
3399 // The first declaration of a function shall specify the
3400 // carries_dependency attribute for its declarator-id if any declaration
3401 // of the function specifies the carries_dependency attribute.
3402 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3403 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3404 S.Diag(CDA->getLocation(),
3405 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3406 // Find the first declaration of the parameter.
3407 // FIXME: Should we build redeclaration chains for function parameters?
3408 const FunctionDecl *FirstFD =
3409 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3410 const ParmVarDecl *FirstVD =
3411 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3412 S.Diag(FirstVD->getLocation(),
3413 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3414 }
3415
3417 newDecl, oldDecl, [&S](ParmVarDecl *To, const ParmVarDecl *From) {
3418 unsigned found = 0;
3419 found += propagateAttribute<InheritableParamAttr>(To, From, S);
3420 // Propagate the lifetimebound attribute from parameters to the
3421 // most recent declaration. Note that this doesn't include the implicit
3422 // 'this' parameter, as the attribute is applied to the function type in
3423 // that case.
3424 found += propagateAttribute<LifetimeBoundAttr>(To, From, S);
3425 return found;
3426 });
3427}
3428
3430 const ASTContext &Ctx) {
3431
3432 auto NoSizeInfo = [&Ctx](QualType Ty) {
3433 if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3434 return true;
3435 if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))
3436 return VAT->getSizeModifier() == ArraySizeModifier::Star;
3437 return false;
3438 };
3439
3440 // `type[]` is equivalent to `type *` and `type[*]`.
3441 if (NoSizeInfo(Old) && NoSizeInfo(New))
3442 return true;
3443
3444 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3445 if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3446 const auto *OldVAT = Ctx.getAsVariableArrayType(Old);
3447 const auto *NewVAT = Ctx.getAsVariableArrayType(New);
3448 if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^
3449 (NewVAT->getSizeModifier() == ArraySizeModifier::Star))
3450 return false;
3451 return true;
3452 }
3453
3454 // Only compare size, ignore Size modifiers and CVR.
3455 if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3456 return Ctx.getAsConstantArrayType(Old)->getSize() ==
3458 }
3459
3460 // Don't try to compare dependent sized array
3461 if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) {
3462 return true;
3463 }
3464
3465 return Old == New;
3466}
3467
3468static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3469 const ParmVarDecl *OldParam,
3470 Sema &S) {
3471 if (auto Oldnullability = OldParam->getType()->getNullability()) {
3472 if (auto Newnullability = NewParam->getType()->getNullability()) {
3473 if (*Oldnullability != *Newnullability) {
3474 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3476 *Newnullability,
3478 != 0))
3480 *Oldnullability,
3482 != 0));
3483 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3484 }
3485 } else {
3486 QualType NewT = NewParam->getType();
3487 NewT = S.Context.getAttributedType(*Oldnullability, NewT, NewT);
3488 NewParam->setType(NewT);
3489 }
3490 }
3491 const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
3492 const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
3493 if (OldParamDT && NewParamDT &&
3494 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3495 QualType OldParamOT = OldParamDT->getOriginalType();
3496 QualType NewParamOT = NewParamDT->getOriginalType();
3497 if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) {
3498 S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
3499 << NewParam << NewParamOT;
3500 S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
3501 << OldParamOT;
3502 }
3503 }
3504}
3505
3506namespace {
3507
3508/// Used in MergeFunctionDecl to keep track of function parameters in
3509/// C.
3510struct GNUCompatibleParamWarning {
3511 ParmVarDecl *OldParm;
3512 ParmVarDecl *NewParm;
3513 QualType PromotedType;
3514};
3515
3516} // end anonymous namespace
3517
3518// Determine whether the previous declaration was a definition, implicit
3519// declaration, or a declaration.
3520template <typename T>
3521static std::pair<diag::kind, SourceLocation>
3523 diag::kind PrevDiag;
3524 SourceLocation OldLocation = Old->getLocation();
3525 if (Old->isThisDeclarationADefinition())
3526 PrevDiag = diag::note_previous_definition;
3527 else if (Old->isImplicit()) {
3528 PrevDiag = diag::note_previous_implicit_declaration;
3529 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3530 if (FD->getBuiltinID())
3531 PrevDiag = diag::note_previous_builtin_declaration;
3532 }
3533 if (OldLocation.isInvalid())
3534 OldLocation = New->getLocation();
3535 } else
3536 PrevDiag = diag::note_previous_declaration;
3537 return std::make_pair(PrevDiag, OldLocation);
3538}
3539
3540/// canRedefineFunction - checks if a function can be redefined. Currently,
3541/// only extern inline functions can be redefined, and even then only in
3542/// GNU89 mode.
3543static bool canRedefineFunction(const FunctionDecl *FD,
3544 const LangOptions& LangOpts) {
3545 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3546 !LangOpts.CPlusPlus &&
3547 FD->isInlineSpecified() &&
3548 FD->getStorageClass() == SC_Extern);
3549}
3550
3551const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3552 const AttributedType *AT = T->getAs<AttributedType>();
3553 while (AT && !AT->isCallingConv())
3554 AT = AT->getModifiedType()->getAs<AttributedType>();
3555 return AT;
3556}
3557
3558template <typename T>
3559static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3560 const DeclContext *DC = Old->getDeclContext();
3561 if (DC->isRecord())
3562 return false;
3563
3564 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3565 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3566 return true;
3567 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3568 return true;
3569 return false;
3570}
3571
3572template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3573static bool isExternC(VarTemplateDecl *) { return false; }
3574static bool isExternC(FunctionTemplateDecl *) { return false; }
3575
3576/// Check whether a redeclaration of an entity introduced by a
3577/// using-declaration is valid, given that we know it's not an overload
3578/// (nor a hidden tag declaration).
3579template<typename ExpectedDecl>
3581 ExpectedDecl *New) {
3582 // C++11 [basic.scope.declarative]p4:
3583 // Given a set of declarations in a single declarative region, each of
3584 // which specifies the same unqualified name,
3585 // -- they shall all refer to the same entity, or all refer to functions
3586 // and function templates; or
3587 // -- exactly one declaration shall declare a class name or enumeration
3588 // name that is not a typedef name and the other declarations shall all
3589 // refer to the same variable or enumerator, or all refer to functions
3590 // and function templates; in this case the class name or enumeration
3591 // name is hidden (3.3.10).
3592
3593 // C++11 [namespace.udecl]p14:
3594 // If a function declaration in namespace scope or block scope has the
3595 // same name and the same parameter-type-list as a function introduced
3596 // by a using-declaration, and the declarations do not declare the same
3597 // function, the program is ill-formed.
3598
3599 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3600 if (Old &&
3601 !Old->getDeclContext()->getRedeclContext()->Equals(
3602 New->getDeclContext()->getRedeclContext()) &&
3603 !(isExternC(Old) && isExternC(New)))
3604 Old = nullptr;
3605
3606 if (!Old) {
3607 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3608 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3609 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3610 return true;
3611 }
3612 return false;
3613}
3614
3616 const FunctionDecl *B) {
3617 assert(A->getNumParams() == B->getNumParams());
3618
3619 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3620 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3621 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3622 if (AttrA == AttrB)
3623 return true;
3624 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3625 AttrA->isDynamic() == AttrB->isDynamic();
3626 };
3627
3628 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3629}
3630
3631/// If necessary, adjust the semantic declaration context for a qualified
3632/// declaration to name the correct inline namespace within the qualifier.
3634 DeclaratorDecl *OldD) {
3635 // The only case where we need to update the DeclContext is when
3636 // redeclaration lookup for a qualified name finds a declaration
3637 // in an inline namespace within the context named by the qualifier:
3638 //
3639 // inline namespace N { int f(); }
3640 // int ::f(); // Sema DC needs adjusting from :: to N::.
3641 //
3642 // For unqualified declarations, the semantic context *can* change
3643 // along the redeclaration chain (for local extern declarations,
3644 // extern "C" declarations, and friend declarations in particular).
3645 if (!NewD->getQualifier())
3646 return;
3647
3648 // NewD is probably already in the right context.
3649 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3650 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3651 if (NamedDC->Equals(SemaDC))
3652 return;
3653
3654 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3655 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3656 "unexpected context for redeclaration");
3657
3658 auto *LexDC = NewD->getLexicalDeclContext();
3659 auto FixSemaDC = [=](NamedDecl *D) {
3660 if (!D)
3661 return;
3662 D->setDeclContext(SemaDC);
3663 D->setLexicalDeclContext(LexDC);
3664 };
3665
3666 FixSemaDC(NewD);
3667 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3668 FixSemaDC(FD->getDescribedFunctionTemplate());
3669 else if (auto *VD = dyn_cast<VarDecl>(NewD))
3670 FixSemaDC(VD->getDescribedVarTemplate());
3671}
3672
3674 bool MergeTypeWithOld, bool NewDeclIsDefn) {
3675 // Verify the old decl was also a function.
3676 FunctionDecl *Old = OldD->getAsFunction();
3677 if (!Old) {
3678 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3679 // We don't need to check the using friend pattern from other module unit
3680 // since we should have diagnosed such cases in its unit already.
3681 if (New->getFriendObjectKind() && !OldD->isInAnotherModuleUnit()) {
3682 Diag(New->getLocation(), diag::err_using_decl_friend);
3683 Diag(Shadow->getTargetDecl()->getLocation(),
3684 diag::note_using_decl_target);
3685 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3686 << 0;
3687 return true;
3688 }
3689
3690 // Check whether the two declarations might declare the same function or
3691 // function template.
3692 if (FunctionTemplateDecl *NewTemplate =
3693 New->getDescribedFunctionTemplate()) {
3695 NewTemplate))
3696 return true;
3697 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3698 ->getAsFunction();
3699 } else {
3700 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3701 return true;
3702 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3703 }
3704 } else {
3705 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3706 << New->getDeclName();
3707 notePreviousDefinition(OldD, New->getLocation());
3708 return true;
3709 }
3710 }
3711
3712 // If the old declaration was found in an inline namespace and the new
3713 // declaration was qualified, update the DeclContext to match.
3715
3716 // If the old declaration is invalid, just give up here.
3717 if (Old->isInvalidDecl())
3718 return true;
3719
3720 // Disallow redeclaration of some builtins.
3721 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3722 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3723 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3724 << Old << Old->getType();
3725 return true;
3726 }
3727
3728 diag::kind PrevDiag;
3729 SourceLocation OldLocation;
3730 std::tie(PrevDiag, OldLocation) =
3732
3733 // Don't complain about this if we're in GNU89 mode and the old function
3734 // is an extern inline function.
3735 // Don't complain about specializations. They are not supposed to have
3736 // storage classes.
3737 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3738 New->getStorageClass() == SC_Static &&
3739 Old->hasExternalFormalLinkage() &&
3740 !New->getTemplateSpecializationInfo() &&
3742 if (getLangOpts().MicrosoftExt) {
3743 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3744 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3745 } else {
3746 Diag(New->getLocation(), diag::err_static_non_static) << New;
3747 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3748 return true;
3749 }
3750 }
3751
3752 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3753 if (!Old->hasAttr<InternalLinkageAttr>()) {
3754 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3755 << ILA;
3756 Diag(Old->getLocation(), diag::note_previous_declaration);
3757 New->dropAttr<InternalLinkageAttr>();
3758 }
3759
3760 if (auto *EA = New->getAttr<ErrorAttr>()) {
3761 if (!Old->hasAttr<ErrorAttr>()) {
3762 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3763 Diag(Old->getLocation(), diag::note_previous_declaration);
3764 New->dropAttr<ErrorAttr>();
3765 }
3766 }
3767
3769 return true;
3770
3771 if (!getLangOpts().CPlusPlus) {
3772 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3773 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3774 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3775 << New << OldOvl;
3776
3777 // Try our best to find a decl that actually has the overloadable
3778 // attribute for the note. In most cases (e.g. programs with only one
3779 // broken declaration/definition), this won't matter.
3780 //
3781 // FIXME: We could do this if we juggled some extra state in
3782 // OverloadableAttr, rather than just removing it.
3783 const Decl *DiagOld = Old;
3784 if (OldOvl) {
3785 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3786 const auto *A = D->getAttr<OverloadableAttr>();
3787 return A && !A->isImplicit();
3788 });
3789 // If we've implicitly added *all* of the overloadable attrs to this
3790 // chain, emitting a "previous redecl" note is pointless.
3791 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3792 }
3793
3794 if (DiagOld)
3795 Diag(DiagOld->getLocation(),
3796 diag::note_attribute_overloadable_prev_overload)
3797 << OldOvl;
3798
3799 if (OldOvl)
3800 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3801 else
3802 New->dropAttr<OverloadableAttr>();
3803 }
3804 }
3805
3806 // It is not permitted to redeclare an SME function with different SME
3807 // attributes.
3808 if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
3809 Diag(New->getLocation(), diag::err_sme_attr_mismatch)
3810 << New->getType() << Old->getType();
3811 Diag(OldLocation, diag::note_previous_declaration);
3812 return true;
3813 }
3814
3815 // If a function is first declared with a calling convention, but is later
3816 // declared or defined without one, all following decls assume the calling
3817 // convention of the first.
3818 //
3819 // It's OK if a function is first declared without a calling convention,
3820 // but is later declared or defined with the default calling convention.
3821 //
3822 // To test if either decl has an explicit calling convention, we look for
3823 // AttributedType sugar nodes on the type as written. If they are missing or
3824 // were canonicalized away, we assume the calling convention was implicit.
3825 //
3826 // Note also that we DO NOT return at this point, because we still have
3827 // other tests to run.
3828 QualType OldQType = Context.getCanonicalType(Old->getType());
3829 QualType NewQType = Context.getCanonicalType(New->getType());
3830 const FunctionType *OldType = cast<FunctionType>(OldQType);
3831 const FunctionType *NewType = cast<FunctionType>(NewQType);
3832 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3833 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3834 bool RequiresAdjustment = false;
3835
3836 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3838 const FunctionType *FT =
3839 First->getType().getCanonicalType()->castAs<FunctionType>();
3841 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3842 if (!NewCCExplicit) {
3843 // Inherit the CC from the previous declaration if it was specified
3844 // there but not here.
3845 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3846 RequiresAdjustment = true;
3847 } else if (Old->getBuiltinID()) {
3848 // Builtin attribute isn't propagated to the new one yet at this point,
3849 // so we check if the old one is a builtin.
3850
3851 // Calling Conventions on a Builtin aren't really useful and setting a
3852 // default calling convention and cdecl'ing some builtin redeclarations is
3853 // common, so warn and ignore the calling convention on the redeclaration.
3854 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3855 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3857 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3858 RequiresAdjustment = true;
3859 } else {
3860 // Calling conventions aren't compatible, so complain.
3861 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3862 Diag(New->getLocation(), diag::err_cconv_change)
3863 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3864 << !FirstCCExplicit
3865 << (!FirstCCExplicit ? "" :
3867
3868 // Put the note on the first decl, since it is the one that matters.
3869 Diag(First->getLocation(), diag::note_previous_declaration);
3870 return true;
3871 }
3872 }
3873
3874 // FIXME: diagnose the other way around?
3875 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3876 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3877 RequiresAdjustment = true;
3878 }
3879
3880 // Merge regparm attribute.
3881 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3882 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3883 if (NewTypeInfo.getHasRegParm()) {
3884 Diag(New->getLocation(), diag::err_regparm_mismatch)
3885 << NewType->getRegParmType()
3886 << OldType->getRegParmType();
3887 Diag(OldLocation, diag::note_previous_declaration);
3888 return true;
3889 }
3890
3891 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3892 RequiresAdjustment = true;
3893 }
3894
3895 // Merge ns_returns_retained attribute.
3896 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3897 if (NewTypeInfo.getProducesResult()) {
3898 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3899 << "'ns_returns_retained'";
3900 Diag(OldLocation, diag::note_previous_declaration);
3901 return true;
3902 }
3903
3904 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3905 RequiresAdjustment = true;
3906 }
3907
3908 if (OldTypeInfo.getNoCallerSavedRegs() !=
3909 NewTypeInfo.getNoCallerSavedRegs()) {
3910 if (NewTypeInfo.getNoCallerSavedRegs()) {
3911 AnyX86NoCallerSavedRegistersAttr *Attr =
3912 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3913 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3914 Diag(OldLocation, diag::note_previous_declaration);
3915 return true;
3916 }
3917
3918 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3919 RequiresAdjustment = true;
3920 }
3921
3922 if (RequiresAdjustment) {
3923 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3924 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3925 New->setType(QualType(AdjustedType, 0));
3926 NewQType = Context.getCanonicalType(New->getType());
3927 }
3928
3929 // If this redeclaration makes the function inline, we may need to add it to
3930 // UndefinedButUsed.
3931 if (!Old->isInlined() && New->isInlined() && !New->hasAttr<GNUInlineAttr>() &&
3932 !getLangOpts().GNUInline && Old->isUsed(false) && !Old->isDefined() &&
3933 !New->isThisDeclarationADefinition() && !Old->isInAnotherModuleUnit())
3934 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3935 SourceLocation()));
3936
3937 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3938 // about it.
3939 if (New->hasAttr<GNUInlineAttr>() &&
3940 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3941 UndefinedButUsed.erase(Old->getCanonicalDecl());
3942 }
3943
3944 // If pass_object_size params don't match up perfectly, this isn't a valid
3945 // redeclaration.
3946 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3948 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3949 << New->getDeclName();
3950 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3951 return true;
3952 }
3953
3954 QualType OldQTypeForComparison = OldQType;
3955 if (Context.hasAnyFunctionEffects()) {
3956 const auto OldFX = Old->getFunctionEffects();
3957 const auto NewFX = New->getFunctionEffects();
3958 if (OldFX != NewFX) {
3959 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
3960 for (const auto &Diff : Diffs) {
3961 if (Diff.shouldDiagnoseRedeclaration(*Old, OldFX, *New, NewFX)) {
3962 Diag(New->getLocation(),
3963 diag::warn_mismatched_func_effect_redeclaration)
3964 << Diff.effectName();
3965 Diag(Old->getLocation(), diag::note_previous_declaration);
3966 }
3967 }
3968 // Following a warning, we could skip merging effects from the previous
3969 // declaration, but that would trigger an additional "conflicting types"
3970 // error.
3971 if (const auto *NewFPT = NewQType->getAs<FunctionProtoType>()) {
3973 FunctionEffectSet MergedFX =
3974 FunctionEffectSet::getUnion(OldFX, NewFX, MergeErrs);
3975 if (!MergeErrs.empty())
3976 diagnoseFunctionEffectMergeConflicts(MergeErrs, New->getLocation(),
3977 Old->getLocation());
3978
3979 FunctionProtoType::ExtProtoInfo EPI = NewFPT->getExtProtoInfo();
3980 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
3981 QualType ModQT = Context.getFunctionType(NewFPT->getReturnType(),
3982 NewFPT->getParamTypes(), EPI);
3983
3984 New->setType(ModQT);
3985 NewQType = New->getType();
3986
3987 // Revise OldQTForComparison to include the merged effects,
3988 // so as not to fail due to differences later.
3989 if (const auto *OldFPT = OldQType->getAs<FunctionProtoType>()) {
3990 EPI = OldFPT->getExtProtoInfo();
3991 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
3992 OldQTypeForComparison = Context.getFunctionType(
3993 OldFPT->getReturnType(), OldFPT->getParamTypes(), EPI);
3994 }
3995 if (OldFX.empty()) {
3996 // A redeclaration may add the attribute to a previously seen function
3997 // body which needs to be verified.
3998 maybeAddDeclWithEffects(Old, MergedFX);
3999 }
4000 }
4001 }
4002 }
4003
4004 if (getLangOpts().CPlusPlus) {
4005 OldQType = Context.getCanonicalType(Old->getType());
4006 NewQType = Context.getCanonicalType(New->getType());
4007
4008 // Go back to the type source info to compare the declared return types,
4009 // per C++1y [dcl.type.auto]p13:
4010 // Redeclarations or specializations of a function or function template
4011 // with a declared return type that uses a placeholder type shall also
4012 // use that placeholder, not a deduced type.
4013 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
4014 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
4015 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
4016 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
4017 OldDeclaredReturnType)) {
4018 QualType ResQT;
4019 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
4020 OldDeclaredReturnType->isObjCObjectPointerType())
4021 // FIXME: This does the wrong thing for a deduced return type.
4022 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
4023 if (ResQT.isNull()) {
4024 if (New->isCXXClassMember() && New->isOutOfLine())
4025 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
4026 << New << New->getReturnTypeSourceRange();
4027 else if (Old->isExternC() && New->isExternC() &&
4028 !Old->hasAttr<OverloadableAttr>() &&
4029 !New->hasAttr<OverloadableAttr>())
4030 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4031 else
4032 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
4033 << New->getReturnTypeSourceRange();
4034 Diag(OldLocation, PrevDiag) << Old << Old->getType()
4035 << Old->getReturnTypeSourceRange();
4036 return true;
4037 }
4038 else
4039 NewQType = ResQT;
4040 }
4041
4042 QualType OldReturnType = OldType->getReturnType();
4043 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
4044 if (OldReturnType != NewReturnType) {
4045 // If this function has a deduced return type and has already been
4046 // defined, copy the deduced value from the old declaration.
4047 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
4048 if (OldAT && OldAT->isDeduced()) {
4049 QualType DT = OldAT->getDeducedType();
4050 if (DT.isNull()) {
4051 New->setType(SubstAutoTypeDependent(New->getType()));
4052 NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
4053 } else {
4054 New->setType(SubstAutoType(New->getType(), DT));
4055 NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
4056 }
4057 }
4058 }
4059
4060 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
4061 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
4062 if (OldMethod && NewMethod) {
4063 // Preserve triviality.
4064 NewMethod->setTrivial(OldMethod->isTrivial());
4065
4066 // MSVC allows explicit template specialization at class scope:
4067 // 2 CXXMethodDecls referring to the same function will be injected.
4068 // We don't want a redeclaration error.
4069 bool IsClassScopeExplicitSpecialization =
4070 OldMethod->isFunctionTemplateSpecialization() &&
4072 bool isFriend = NewMethod->getFriendObjectKind();
4073
4074 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
4075 !IsClassScopeExplicitSpecialization) {
4076 // -- Member function declarations with the same name and the
4077 // same parameter types cannot be overloaded if any of them
4078 // is a static member function declaration.
4079 if (OldMethod->isStatic() != NewMethod->isStatic()) {
4080 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
4081 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4082 return true;
4083 }
4084
4085 // C++ [class.mem]p1:
4086 // [...] A member shall not be declared twice in the
4087 // member-specification, except that a nested class or member
4088 // class template can be declared and then later defined.
4089 if (!inTemplateInstantiation()) {
4090 unsigned NewDiag;
4091 if (isa<CXXConstructorDecl>(OldMethod))
4092 NewDiag = diag::err_constructor_redeclared;
4093 else if (isa<CXXDestructorDecl>(NewMethod))
4094 NewDiag = diag::err_destructor_redeclared;
4095 else if (isa<CXXConversionDecl>(NewMethod))
4096 NewDiag = diag::err_conv_function_redeclared;
4097 else
4098 NewDiag = diag::err_member_redeclared;
4099
4100 Diag(New->getLocation(), NewDiag);
4101 } else {
4102 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
4103 << New << New->getType();
4104 }
4105 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4106 return true;
4107
4108 // Complain if this is an explicit declaration of a special
4109 // member that was initially declared implicitly.
4110 //
4111 // As an exception, it's okay to befriend such methods in order
4112 // to permit the implicit constructor/destructor/operator calls.
4113 } else if (OldMethod->isImplicit()) {
4114 if (isFriend) {
4115 NewMethod->setImplicit();
4116 } else {
4117 Diag(NewMethod->getLocation(),
4118 diag::err_definition_of_implicitly_declared_member)
4119 << New << getSpecialMember(OldMethod);
4120 return true;
4121 }
4122 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
4123 Diag(NewMethod->getLocation(),
4124 diag::err_definition_of_explicitly_defaulted_member)
4125 << getSpecialMember(OldMethod);
4126 return true;
4127 }
4128 }
4129
4130 // C++1z [over.load]p2
4131 // Certain function declarations cannot be overloaded:
4132 // -- Function declarations that differ only in the return type,
4133 // the exception specification, or both cannot be overloaded.
4134
4135 // Check the exception specifications match. This may recompute the type of
4136 // both Old and New if it resolved exception specifications, so grab the
4137 // types again after this. Because this updates the type, we do this before
4138 // any of the other checks below, which may update the "de facto" NewQType
4139 // but do not necessarily update the type of New.
4141 return true;
4142
4143 // C++11 [dcl.attr.noreturn]p1:
4144 // The first declaration of a function shall specify the noreturn
4145 // attribute if any declaration of that function specifies the noreturn
4146 // attribute.
4147 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4148 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4149 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
4150 << NRA;
4151 Diag(Old->getLocation(), diag::note_previous_declaration);
4152 }
4153
4154 // C++11 [dcl.attr.depend]p2:
4155 // The first declaration of a function shall specify the
4156 // carries_dependency attribute for its declarator-id if any declaration
4157 // of the function specifies the carries_dependency attribute.
4158 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
4159 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
4160 Diag(CDA->getLocation(),
4161 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
4162 Diag(Old->getFirstDecl()->getLocation(),
4163 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
4164 }
4165
4166 // SYCL 2020 section 5.10.1, "SYCL functions and member functions linkage":
4167 // When a function is declared with SYCL_EXTERNAL, that macro must be
4168 // used on the first declaration of that function in the translation unit.
4169 // Redeclarations of the function in the same translation unit may
4170 // optionally use SYCL_EXTERNAL, but this is not required.
4171 const SYCLExternalAttr *SEA = New->getAttr<SYCLExternalAttr>();
4172 if (SEA && !Old->hasAttr<SYCLExternalAttr>()) {
4173 Diag(SEA->getLocation(), diag::warn_sycl_external_missing_on_first_decl)
4174 << SEA;
4175 Diag(Old->getLocation(), diag::note_previous_declaration);
4176 }
4177
4178 // (C++98 8.3.5p3):
4179 // All declarations for a function shall agree exactly in both the
4180 // return type and the parameter-type-list.
4181 // We also want to respect all the extended bits except noreturn.
4182
4183 // noreturn should now match unless the old type info didn't have it.
4184 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4185 auto *OldType = OldQTypeForComparison->castAs<FunctionProtoType>();
4186 const FunctionType *OldTypeForComparison
4187 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
4188 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4189 assert(OldQTypeForComparison.isCanonical());
4190 }
4191
4193 // As a special case, retain the language linkage from previous
4194 // declarations of a friend function as an extension.
4195 //
4196 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4197 // and is useful because there's otherwise no way to specify language
4198 // linkage within class scope.
4199 //
4200 // Check cautiously as the friend object kind isn't yet complete.
4201 if (New->getFriendObjectKind() != Decl::FOK_None) {
4202 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
4203 Diag(OldLocation, PrevDiag);
4204 } else {
4205 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4206 Diag(OldLocation, PrevDiag);
4207 return true;
4208 }
4209 }
4210
4211 // HLSL check parameters for matching ABI specifications.
4212 if (getLangOpts().HLSL) {
4213 if (HLSL().CheckCompatibleParameterABI(New, Old))
4214 return true;
4215
4216 // If no errors are generated when checking parameter ABIs we can check if
4217 // the two declarations have the same type ignoring the ABIs and if so,
4218 // the declarations can be merged. This case for merging is only valid in
4219 // HLSL because there are no valid cases of merging mismatched parameter
4220 // ABIs except the HLSL implicit in and explicit in.
4221 if (Context.hasSameFunctionTypeIgnoringParamABI(OldQTypeForComparison,
4222 NewQType))
4223 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4224 // Fall through for conflicting redeclarations and redefinitions.
4225 }
4226
4227 // If the function types are compatible, merge the declarations. Ignore the
4228 // exception specifier because it was already checked above in
4229 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4230 // about incompatible types under -fms-compatibility.
4231 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
4232 NewQType))
4233 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4234
4235 // If the types are imprecise (due to dependent constructs in friends or
4236 // local extern declarations), it's OK if they differ. We'll check again
4237 // during instantiation.
4238 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
4239 return false;
4240
4241 // Fall through for conflicting redeclarations and redefinitions.
4242 }
4243
4244 // C: Function types need to be compatible, not identical. This handles
4245 // duplicate function decls like "void f(int); void f(enum X);" properly.
4246 if (!getLangOpts().CPlusPlus) {
4247 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4248 // type is specified by a function definition that contains a (possibly
4249 // empty) identifier list, both shall agree in the number of parameters
4250 // and the type of each parameter shall be compatible with the type that
4251 // results from the application of default argument promotions to the
4252 // type of the corresponding identifier. ...
4253 // This cannot be handled by ASTContext::typesAreCompatible() because that
4254 // doesn't know whether the function type is for a definition or not when
4255 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4256 // we need to cover here is that the number of arguments agree as the
4257 // default argument promotion rules were already checked by
4258 // ASTContext::typesAreCompatible().
4259 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4260 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4261 if (Old->hasInheritedPrototype())
4262 Old = Old->getCanonicalDecl();
4263 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4264 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
4265 return true;
4266 }
4267
4268 // If we are merging two functions where only one of them has a prototype,
4269 // we may have enough information to decide to issue a diagnostic that the
4270 // function without a prototype will change behavior in C23. This handles
4271 // cases like:
4272 // void i(); void i(int j);
4273 // void i(int j); void i();
4274 // void i(); void i(int j) {}
4275 // See ActOnFinishFunctionBody() for other cases of the behavior change
4276 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4277 // type without a prototype.
4278 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4279 !New->isImplicit() && !Old->isImplicit()) {
4280 const FunctionDecl *WithProto, *WithoutProto;
4281 if (New->hasWrittenPrototype()) {
4282 WithProto = New;
4283 WithoutProto = Old;
4284 } else {
4285 WithProto = Old;
4286 WithoutProto = New;
4287 }
4288
4289 if (WithProto->getNumParams() != 0) {
4290 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4291 // The one without the prototype will be changing behavior in C23, so
4292 // warn about that one so long as it's a user-visible declaration.
4293 bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4294 if (WithoutProto == New)
4295 IsWithoutProtoADef = NewDeclIsDefn;
4296 else
4297 IsWithProtoADef = NewDeclIsDefn;
4298 Diag(WithoutProto->getLocation(),
4299 diag::warn_non_prototype_changes_behavior)
4300 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4301 << (WithoutProto == Old) << IsWithProtoADef;
4302
4303 // The reason the one without the prototype will be changing behavior
4304 // is because of the one with the prototype, so note that so long as
4305 // it's a user-visible declaration. There is one exception to this:
4306 // when the new declaration is a definition without a prototype, the
4307 // old declaration with a prototype is not the cause of the issue,
4308 // and that does not need to be noted because the one with a
4309 // prototype will not change behavior in C23.
4310 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4311 !IsWithoutProtoADef)
4312 Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
4313 }
4314 }
4315 }
4316
4317 if (Context.typesAreCompatible(OldQType, NewQType)) {
4318 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4319 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4320 const FunctionProtoType *OldProto = nullptr;
4321 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
4322 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
4323 // The old declaration provided a function prototype, but the
4324 // new declaration does not. Merge in the prototype.
4325 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4326 NewQType = Context.getFunctionType(NewFuncType->getReturnType(),
4327 OldProto->getParamTypes(),
4328 OldProto->getExtProtoInfo());
4329 New->setType(NewQType);
4330 New->setHasInheritedPrototype();
4331
4332 // Synthesize parameters with the same types.
4334 for (const auto &ParamType : OldProto->param_types()) {
4336 Context, New, SourceLocation(), SourceLocation(), nullptr,
4337 ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4338 Param->setScopeInfo(0, Params.size());
4339 Param->setImplicit();
4340 Params.push_back(Param);
4341 }
4342
4343 New->setParams(Params);
4344 }
4345
4346 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4347 }
4348 }
4349
4350 // Check if the function types are compatible when pointer size address
4351 // spaces are ignored.
4352 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4353 return false;
4354
4355 // GNU C permits a K&R definition to follow a prototype declaration
4356 // if the declared types of the parameters in the K&R definition
4357 // match the types in the prototype declaration, even when the
4358 // promoted types of the parameters from the K&R definition differ
4359 // from the types in the prototype. GCC then keeps the types from
4360 // the prototype.
4361 //
4362 // If a variadic prototype is followed by a non-variadic K&R definition,
4363 // the K&R definition becomes variadic. This is sort of an edge case, but
4364 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4365 // C99 6.9.1p8.
4366 if (!getLangOpts().CPlusPlus &&
4367 Old->hasPrototype() && !New->hasPrototype() &&
4368 New->getType()->getAs<FunctionProtoType>() &&
4369 Old->getNumParams() == New->getNumParams()) {
4372 const FunctionProtoType *OldProto
4373 = Old->getType()->getAs<FunctionProtoType>();
4374 const FunctionProtoType *NewProto
4375 = New->getType()->getAs<FunctionProtoType>();
4376
4377 // Determine whether this is the GNU C extension.
4378 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4379 NewProto->getReturnType());
4380 bool LooseCompatible = !MergedReturn.isNull();
4381 for (unsigned Idx = 0, End = Old->getNumParams();
4382 LooseCompatible && Idx != End; ++Idx) {
4383 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4384 ParmVarDecl *NewParm = New->getParamDecl(Idx);
4385 if (Context.typesAreCompatible(OldParm->getType(),
4386 NewProto->getParamType(Idx))) {
4387 ArgTypes.push_back(NewParm->getType());
4388 } else if (Context.typesAreCompatible(OldParm->getType(),
4389 NewParm->getType(),
4390 /*CompareUnqualified=*/true)) {
4391 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4392 NewProto->getParamType(Idx) };
4393 Warnings.push_back(Warn);
4394 ArgTypes.push_back(NewParm->getType());
4395 } else
4396 LooseCompatible = false;
4397 }
4398
4399 if (LooseCompatible) {
4400 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4401 Diag(Warnings[Warn].NewParm->getLocation(),
4402 diag::ext_param_promoted_not_compatible_with_prototype)
4403 << Warnings[Warn].PromotedType
4404 << Warnings[Warn].OldParm->getType();
4405 if (Warnings[Warn].OldParm->getLocation().isValid())
4406 Diag(Warnings[Warn].OldParm->getLocation(),
4407 diag::note_previous_declaration);
4408 }
4409
4410 if (MergeTypeWithOld)
4411 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4412 OldProto->getExtProtoInfo()));
4413 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4414 }
4415
4416 // Fall through to diagnose conflicting types.
4417 }
4418
4419 // A function that has already been declared has been redeclared or
4420 // defined with a different type; show an appropriate diagnostic.
4421
4422 // If the previous declaration was an implicitly-generated builtin
4423 // declaration, then at the very least we should use a specialized note.
4424 unsigned BuiltinID;
4425 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4426 // If it's actually a library-defined builtin function like 'malloc'
4427 // or 'printf', just warn about the incompatible redeclaration.
4428 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4429 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4430 Diag(OldLocation, diag::note_previous_builtin_declaration)
4431 << Old << Old->getType();
4432 return false;
4433 }
4434
4435 PrevDiag = diag::note_previous_builtin_declaration;
4436 }
4437
4438 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4439 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4440 return true;
4441}
4442
4444 Scope *S, bool MergeTypeWithOld) {
4445 // Merge the attributes
4447
4448 // Merge "pure" flag.
4449 if (Old->isPureVirtual())
4450 New->setIsPureVirtual();
4451
4452 // Merge "used" flag.
4453 if (Old->getMostRecentDecl()->isUsed(false))
4454 New->setIsUsed();
4455
4456 // Merge attributes from the parameters. These can mismatch with K&R
4457 // declarations.
4458 if (New->getNumParams() == Old->getNumParams())
4459 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4460 ParmVarDecl *NewParam = New->getParamDecl(i);
4461 ParmVarDecl *OldParam = Old->getParamDecl(i);
4462 mergeParamDeclAttributes(NewParam, OldParam, *this);
4463 mergeParamDeclTypes(NewParam, OldParam, *this);
4464 }
4465
4466 if (getLangOpts().CPlusPlus)
4467 return MergeCXXFunctionDecl(New, Old, S);
4468
4469 // Merge the function types so the we get the composite types for the return
4470 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4471 // was visible.
4472 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4473 if (!Merged.isNull() && MergeTypeWithOld)
4474 New->setType(Merged);
4475
4476 return false;
4477}
4478
4480 ObjCMethodDecl *oldMethod) {
4481 // Merge the attributes, including deprecated/unavailable
4482 AvailabilityMergeKind MergeKind =
4484 ? (oldMethod->isOptional()
4487 : isa<ObjCImplDecl>(newMethod->getDeclContext())
4490
4491 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4492
4493 // Merge attributes from the parameters.
4495 oe = oldMethod->param_end();
4497 ni = newMethod->param_begin(), ne = newMethod->param_end();
4498 ni != ne && oi != oe; ++ni, ++oi)
4499 mergeParamDeclAttributes(*ni, *oi, *this);
4500
4501 ObjC().CheckObjCMethodOverride(newMethod, oldMethod);
4502}
4503
4505 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4506
4507 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
4508 ? diag::err_redefinition_different_type
4509 : diag::err_redeclaration_different_type)
4510 << New->getDeclName() << New->getType() << Old->getType();
4511
4512 diag::kind PrevDiag;
4513 SourceLocation OldLocation;
4514 std::tie(PrevDiag, OldLocation)
4516 S.Diag(OldLocation, PrevDiag) << Old << Old->getType();
4517 New->setInvalidDecl();
4518}
4519
4521 bool MergeTypeWithOld) {
4522 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4523 return;
4524
4525 QualType MergedT;
4526 if (getLangOpts().CPlusPlus) {
4527 if (New->getType()->isUndeducedType()) {
4528 // We don't know what the new type is until the initializer is attached.
4529 return;
4530 } else if (Context.hasSameType(New->getType(), Old->getType())) {
4531 // These could still be something that needs exception specs checked.
4532 return MergeVarDeclExceptionSpecs(New, Old);
4533 }
4534 // C++ [basic.link]p10:
4535 // [...] the types specified by all declarations referring to a given
4536 // object or function shall be identical, except that declarations for an
4537 // array object can specify array types that differ by the presence or
4538 // absence of a major array bound (8.3.4).
4539 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4540 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4541 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4542
4543 // We are merging a variable declaration New into Old. If it has an array
4544 // bound, and that bound differs from Old's bound, we should diagnose the
4545 // mismatch.
4546 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4547 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4548 PrevVD = PrevVD->getPreviousDecl()) {
4549 QualType PrevVDTy = PrevVD->getType();
4550 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4551 continue;
4552
4553 if (!Context.hasSameType(New->getType(), PrevVDTy))
4554 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4555 }
4556 }
4557
4558 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4559 if (Context.hasSameType(OldArray->getElementType(),
4560 NewArray->getElementType()))
4561 MergedT = New->getType();
4562 }
4563 // FIXME: Check visibility. New is hidden but has a complete type. If New
4564 // has no array bound, it should not inherit one from Old, if Old is not
4565 // visible.
4566 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4567 if (Context.hasSameType(OldArray->getElementType(),
4568 NewArray->getElementType()))
4569 MergedT = Old->getType();
4570 }
4571 }
4572 else if (New->getType()->isObjCObjectPointerType() &&
4573 Old->getType()->isObjCObjectPointerType()) {
4574 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4575 Old->getType());
4576 }
4577 } else {
4578 // C 6.2.7p2:
4579 // All declarations that refer to the same object or function shall have
4580 // compatible type.
4581 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4582 }
4583 if (MergedT.isNull()) {
4584 // It's OK if we couldn't merge types if either type is dependent, for a
4585 // block-scope variable. In other cases (static data members of class
4586 // templates, variable templates, ...), we require the types to be
4587 // equivalent.
4588 // FIXME: The C++ standard doesn't say anything about this.
4589 if ((New->getType()->isDependentType() ||
4590 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4591 // If the old type was dependent, we can't merge with it, so the new type
4592 // becomes dependent for now. We'll reproduce the original type when we
4593 // instantiate the TypeSourceInfo for the variable.
4594 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4595 New->setType(Context.DependentTy);
4596 return;
4597 }
4598 return diagnoseVarDeclTypeMismatch(*this, New, Old);
4599 }
4600
4601 // Don't actually update the type on the new declaration if the old
4602 // declaration was an extern declaration in a different scope.
4603 if (MergeTypeWithOld)
4604 New->setType(MergedT);
4605}
4606
4607static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4609 // C11 6.2.7p4:
4610 // For an identifier with internal or external linkage declared
4611 // in a scope in which a prior declaration of that identifier is
4612 // visible, if the prior declaration specifies internal or
4613 // external linkage, the type of the identifier at the later
4614 // declaration becomes the composite type.
4615 //
4616 // If the variable isn't visible, we do not merge with its type.
4617 if (Previous.isShadowed())
4618 return false;
4619
4620 if (S.getLangOpts().CPlusPlus) {
4621 // C++11 [dcl.array]p3:
4622 // If there is a preceding declaration of the entity in the same
4623 // scope in which the bound was specified, an omitted array bound
4624 // is taken to be the same as in that earlier declaration.
4625 return NewVD->isPreviousDeclInSameBlockScope() ||
4626 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4628 } else {
4629 // If the old declaration was function-local, don't merge with its
4630 // type unless we're in the same function.
4631 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4632 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4633 }
4634}
4635
4637 // If the new decl is already invalid, don't do any other checking.
4638 if (New->isInvalidDecl())
4639 return;
4640
4641 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4642 return;
4643
4644 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4645
4646 // Verify the old decl was also a variable or variable template.
4647 VarDecl *Old = nullptr;
4648 VarTemplateDecl *OldTemplate = nullptr;
4649 if (Previous.isSingleResult()) {
4650 if (NewTemplate) {
4651 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4652 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4653
4654 if (auto *Shadow =
4655 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4656 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4657 return New->setInvalidDecl();
4658 } else {
4659 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4660
4661 if (auto *Shadow =
4662 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4663 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4664 return New->setInvalidDecl();
4665 }
4666 }
4667 if (!Old) {
4668 Diag(New->getLocation(), diag::err_redefinition_different_kind)
4669 << New->getDeclName();
4670 notePreviousDefinition(Previous.getRepresentativeDecl(),
4671 New->getLocation());
4672 return New->setInvalidDecl();
4673 }
4674
4675 // If the old declaration was found in an inline namespace and the new
4676 // declaration was qualified, update the DeclContext to match.
4678
4679 // Ensure the template parameters are compatible.
4680 if (NewTemplate &&
4682 OldTemplate->getTemplateParameters(),
4683 /*Complain=*/true, TPL_TemplateMatch))
4684 return New->setInvalidDecl();
4685
4686 // C++ [class.mem]p1:
4687 // A member shall not be declared twice in the member-specification [...]
4688 //
4689 // Here, we need only consider static data members.
4690 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4691 Diag(New->getLocation(), diag::err_duplicate_member)
4692 << New->getIdentifier();
4693 Diag(Old->getLocation(), diag::note_previous_declaration);
4694 New->setInvalidDecl();
4695 }
4696
4698 // Warn if an already-defined variable is made a weak_import in a subsequent
4699 // declaration
4700 if (New->hasAttr<WeakImportAttr>())
4701 for (auto *D = Old; D; D = D->getPreviousDecl()) {
4702 if (D->isThisDeclarationADefinition() != VarDecl::DeclarationOnly) {
4703 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4704 Diag(D->getLocation(), diag::note_previous_definition);
4705 // Remove weak_import attribute on new declaration.
4706 New->dropAttr<WeakImportAttr>();
4707 break;
4708 }
4709 }
4710
4711 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4712 if (!Old->hasAttr<InternalLinkageAttr>()) {
4713 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4714 << ILA;
4715 Diag(Old->getLocation(), diag::note_previous_declaration);
4716 New->dropAttr<InternalLinkageAttr>();
4717 }
4718
4719 // Merge the types.
4720 VarDecl *MostRecent = Old->getMostRecentDecl();
4721 if (MostRecent != Old) {
4722 MergeVarDeclTypes(New, MostRecent,
4723 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4724 if (New->isInvalidDecl())
4725 return;
4726 }
4727
4729 if (New->isInvalidDecl())
4730 return;
4731
4732 diag::kind PrevDiag;
4733 SourceLocation OldLocation;
4734 std::tie(PrevDiag, OldLocation) =
4736
4737 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4738 if (New->getStorageClass() == SC_Static &&
4739 !New->isStaticDataMember() &&
4740 Old->hasExternalFormalLinkage()) {
4741 if (getLangOpts().MicrosoftExt) {
4742 Diag(New->getLocation(), diag::ext_static_non_static)
4743 << New->getDeclName();
4744 Diag(OldLocation, PrevDiag);
4745 } else {
4746 Diag(New->getLocation(), diag::err_static_non_static)
4747 << New->getDeclName();
4748 Diag(OldLocation, PrevDiag);
4749 return New->setInvalidDecl();
4750 }
4751 }
4752 // C99 6.2.2p4:
4753 // For an identifier declared with the storage-class specifier
4754 // extern in a scope in which a prior declaration of that
4755 // identifier is visible,23) if the prior declaration specifies
4756 // internal or external linkage, the linkage of the identifier at
4757 // the later declaration is the same as the linkage specified at
4758 // the prior declaration. If no prior declaration is visible, or
4759 // if the prior declaration specifies no linkage, then the
4760 // identifier has external linkage.
4761 if (New->hasExternalStorage() && Old->hasLinkage())
4762 /* Okay */;
4763 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4764 !New->isStaticDataMember() &&
4766 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4767 Diag(OldLocation, PrevDiag);
4768 return New->setInvalidDecl();
4769 }
4770
4771 // Check if extern is followed by non-extern and vice-versa.
4772 if (New->hasExternalStorage() &&
4773 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4774 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4775 Diag(OldLocation, PrevDiag);
4776 return New->setInvalidDecl();
4777 }
4778 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4779 !New->hasExternalStorage()) {
4780 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4781 Diag(OldLocation, PrevDiag);
4782 return New->setInvalidDecl();
4783 }
4784
4786 return;
4787
4788 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4789
4790 // FIXME: The test for external storage here seems wrong? We still
4791 // need to check for mismatches.
4792 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4793 // Don't complain about out-of-line definitions of static members.
4794 !(Old->getLexicalDeclContext()->isRecord() &&
4795 !New->getLexicalDeclContext()->isRecord())) {
4796 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4797 Diag(OldLocation, PrevDiag);
4798 return New->setInvalidDecl();
4799 }
4800
4801 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4802 if (VarDecl *Def = Old->getDefinition()) {
4803 // C++1z [dcl.fcn.spec]p4:
4804 // If the definition of a variable appears in a translation unit before
4805 // its first declaration as inline, the program is ill-formed.
4806 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4807 Diag(Def->getLocation(), diag::note_previous_definition);
4808 }
4809 }
4810
4811 // If this redeclaration makes the variable inline, we may need to add it to
4812 // UndefinedButUsed.
4813 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4814 !Old->getDefinition() && !New->isThisDeclarationADefinition() &&
4815 !Old->isInAnotherModuleUnit())
4816 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4817 SourceLocation()));
4818
4819 if (New->getTLSKind() != Old->getTLSKind()) {
4820 if (!Old->getTLSKind()) {
4821 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4822 Diag(OldLocation, PrevDiag);
4823 } else if (!New->getTLSKind()) {
4824 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4825 Diag(OldLocation, PrevDiag);
4826 } else {
4827 // Do not allow redeclaration to change the variable between requiring
4828 // static and dynamic initialization.
4829 // FIXME: GCC allows this, but uses the TLS keyword on the first
4830 // declaration to determine the kind. Do we need to be compatible here?
4831 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4832 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4833 Diag(OldLocation, PrevDiag);
4834 }
4835 }
4836
4837 // C++ doesn't have tentative definitions, so go right ahead and check here.
4838 if (getLangOpts().CPlusPlus) {
4839 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4840 Old->getCanonicalDecl()->isConstexpr()) {
4841 // This definition won't be a definition any more once it's been merged.
4842 Diag(New->getLocation(),
4843 diag::warn_deprecated_redundant_constexpr_static_def);
4844 } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4845 VarDecl *Def = Old->getDefinition();
4846 if (Def && checkVarDeclRedefinition(Def, New))
4847 return;
4848 }
4849 } else {
4850 // C++ may not have a tentative definition rule, but it has a different
4851 // rule about what constitutes a definition in the first place. See
4852 // [basic.def]p2 for details, but the basic idea is: if the old declaration
4853 // contains the extern specifier and doesn't have an initializer, it's fine
4854 // in C++.
4855 if (Old->getStorageClass() != SC_Extern || Old->hasInit()) {
4856 Diag(New->getLocation(), diag::warn_cxx_compat_tentative_definition)
4857 << New;
4858 Diag(Old->getLocation(), diag::note_previous_declaration);
4859 }
4860 }
4861
4863 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4864 Diag(OldLocation, PrevDiag);
4865 New->setInvalidDecl();
4866 return;
4867 }
4868
4869 // Merge "used" flag.
4870 if (Old->getMostRecentDecl()->isUsed(false))
4871 New->setIsUsed();
4872
4873 // Keep a chain of previous declarations.
4874 New->setPreviousDecl(Old);
4875 if (NewTemplate)
4876 NewTemplate->setPreviousDecl(OldTemplate);
4877
4878 // Inherit access appropriately.
4879 New->setAccess(Old->getAccess());
4880 if (NewTemplate)
4881 NewTemplate->setAccess(New->getAccess());
4882
4883 if (Old->isInline())
4884 New->setImplicitlyInline();
4885}
4886
4889 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4890 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4891 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4892 auto FOld = SrcMgr.getFileEntryRefForID(FOldDecLoc.first);
4893 auto &HSI = PP.getHeaderSearchInfo();
4894 StringRef HdrFilename =
4895 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4896
4897 auto noteFromModuleOrInclude = [&](Module *Mod,
4898 SourceLocation IncLoc) -> bool {
4899 // Redefinition errors with modules are common with non modular mapped
4900 // headers, example: a non-modular header H in module A that also gets
4901 // included directly in a TU. Pointing twice to the same header/definition
4902 // is confusing, try to get better diagnostics when modules is on.
4903 if (IncLoc.isValid()) {
4904 if (Mod) {
4905 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4906 << HdrFilename.str() << Mod->getFullModuleName();
4907 if (!Mod->DefinitionLoc.isInvalid())
4908 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4909 << Mod->getFullModuleName();
4910 } else {
4911 Diag(IncLoc, diag::note_redefinition_include_same_file)
4912 << HdrFilename.str();
4913 }
4914 return true;
4915 }
4916
4917 return false;
4918 };
4919
4920 // Is it the same file and same offset? Provide more information on why
4921 // this leads to a redefinition error.
4922 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4923 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4924 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4925 bool EmittedDiag =
4926 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4927 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4928
4929 // If the header has no guards, emit a note suggesting one.
4930 if (FOld && !HSI.isFileMultipleIncludeGuarded(*FOld))
4931 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4932
4933 if (EmittedDiag)
4934 return;
4935 }
4936
4937 // Redefinition coming from different files or couldn't do better above.
4938 if (Old->getLocation().isValid())
4939 Diag(Old->getLocation(), diag::note_previous_definition);
4940}
4941
4943 if (!hasVisibleDefinition(Old) &&
4944 (New->getFormalLinkage() == Linkage::Internal || New->isInline() ||
4946 New->getDescribedVarTemplate() || New->getNumTemplateParameterLists() ||
4947 New->getDeclContext()->isDependentContext() ||
4948 New->hasAttr<SelectAnyAttr>())) {
4949 // The previous definition is hidden, and multiple definitions are
4950 // permitted (in separate TUs). Demote this to a declaration.
4951 New->demoteThisDefinitionToDeclaration();
4952
4953 // Make the canonical definition visible.
4954 if (auto *OldTD = Old->getDescribedVarTemplate())
4957 return false;
4958 } else {
4959 Diag(New->getLocation(), diag::err_redefinition) << New;
4960 notePreviousDefinition(Old, New->getLocation());
4961 New->setInvalidDecl();
4962 return true;
4963 }
4964}
4965
4967 DeclSpec &DS,
4968 const ParsedAttributesView &DeclAttrs,
4969 RecordDecl *&AnonRecord) {
4971 S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);
4972}
4973
4974// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4975// disambiguate entities defined in different scopes.
4976// While the VS2015 ABI fixes potential miscompiles, it is also breaks
4977// compatibility.
4978// We will pick our mangling number depending on which version of MSVC is being
4979// targeted.
4980static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4984}
4985
4986void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4987 if (!Context.getLangOpts().CPlusPlus)
4988 return;
4989
4990 if (isa<CXXRecordDecl>(Tag->getParent())) {
4991 // If this tag is the direct child of a class, number it if
4992 // it is anonymous.
4993 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4994 return;
4996 Context.getManglingNumberContext(Tag->getParent());
4997 Context.setManglingNumber(
4998 Tag, MCtx.getManglingNumber(
4999 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
5000 return;
5001 }
5002
5003 // If this tag isn't a direct child of a class, number it if it is local.
5005 Decl *ManglingContextDecl;
5006 std::tie(MCtx, ManglingContextDecl) =
5007 getCurrentMangleNumberContext(Tag->getDeclContext());
5008 if (MCtx) {
5009 Context.setManglingNumber(
5010 Tag, MCtx->getManglingNumber(
5011 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
5012 }
5013}
5014
5015namespace {
5016struct NonCLikeKind {
5017 enum {
5018 None,
5019 BaseClass,
5020 DefaultMemberInit,
5021 Lambda,
5022 Friend,
5023 OtherMember,
5024 Invalid,
5025 } Kind = None;
5026 SourceRange Range;
5027
5028 explicit operator bool() { return Kind != None; }
5029};
5030}
5031
5032/// Determine whether a class is C-like, according to the rules of C++
5033/// [dcl.typedef] for anonymous classes with typedef names for linkage.
5034static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
5035 if (RD->isInvalidDecl())
5036 return {NonCLikeKind::Invalid, {}};
5037
5038 // C++ [dcl.typedef]p9: [P1766R1]
5039 // An unnamed class with a typedef name for linkage purposes shall not
5040 //
5041 // -- have any base classes
5042 if (RD->getNumBases())
5043 return {NonCLikeKind::BaseClass,
5045 RD->bases_end()[-1].getEndLoc())};
5046 bool Invalid = false;
5047 for (Decl *D : RD->decls()) {
5048 // Don't complain about things we already diagnosed.
5049 if (D->isInvalidDecl()) {
5050 Invalid = true;
5051 continue;
5052 }
5053
5054 // -- have any [...] default member initializers
5055 if (auto *FD = dyn_cast<FieldDecl>(D)) {
5056 if (FD->hasInClassInitializer()) {
5057 auto *Init = FD->getInClassInitializer();
5058 return {NonCLikeKind::DefaultMemberInit,
5059 Init ? Init->getSourceRange() : D->getSourceRange()};
5060 }
5061 continue;
5062 }
5063
5064 // FIXME: We don't allow friend declarations. This violates the wording of
5065 // P1766, but not the intent.
5066 if (isa<FriendDecl>(D))
5067 return {NonCLikeKind::Friend, D->getSourceRange()};
5068
5069 // -- declare any members other than non-static data members, member
5070 // enumerations, or member classes,
5072 isa<EnumDecl>(D))
5073 continue;
5074 auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
5075 if (!MemberRD) {
5076 if (D->isImplicit())
5077 continue;
5078 return {NonCLikeKind::OtherMember, D->getSourceRange()};
5079 }
5080
5081 // -- contain a lambda-expression,
5082 if (MemberRD->isLambda())
5083 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
5084
5085 // and all member classes shall also satisfy these requirements
5086 // (recursively).
5087 if (MemberRD->isThisDeclarationADefinition()) {
5088 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
5089 return Kind;
5090 }
5091 }
5092
5093 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
5094}
5095
5097 TypedefNameDecl *NewTD) {
5098 if (TagFromDeclSpec->isInvalidDecl())
5099 return;
5100
5101 // Do nothing if the tag already has a name for linkage purposes.
5102 if (TagFromDeclSpec->hasNameForLinkage())
5103 return;
5104
5105 // A well-formed anonymous tag must always be a TagUseKind::Definition.
5106 assert(TagFromDeclSpec->isThisDeclarationADefinition());
5107
5108 // The type must match the tag exactly; no qualifiers allowed.
5109 if (!Context.hasSameType(NewTD->getUnderlyingType(),
5110 Context.getCanonicalTagType(TagFromDeclSpec))) {
5111 if (getLangOpts().CPlusPlus)
5112 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
5113 return;
5114 }
5115
5116 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
5117 // An unnamed class with a typedef name for linkage purposes shall [be
5118 // C-like].
5119 //
5120 // FIXME: Also diagnose if we've already computed the linkage. That ideally
5121 // shouldn't happen, but there are constructs that the language rule doesn't
5122 // disallow for which we can't reasonably avoid computing linkage early.
5123 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
5124 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
5125 : NonCLikeKind();
5126 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
5127 if (NonCLike || ChangesLinkage) {
5128 if (NonCLike.Kind == NonCLikeKind::Invalid)
5129 return;
5130
5131 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
5132 if (ChangesLinkage) {
5133 // If the linkage changes, we can't accept this as an extension.
5134 if (NonCLike.Kind == NonCLikeKind::None)
5135 DiagID = diag::err_typedef_changes_linkage;
5136 else
5137 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
5138 }
5139
5140 SourceLocation FixitLoc =
5141 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
5142 llvm::SmallString<40> TextToInsert;
5143 TextToInsert += ' ';
5144 TextToInsert += NewTD->getIdentifier()->getName();
5145
5146 Diag(FixitLoc, DiagID)
5147 << isa<TypeAliasDecl>(NewTD)
5148 << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
5149 if (NonCLike.Kind != NonCLikeKind::None) {
5150 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
5151 << NonCLike.Kind - 1 << NonCLike.Range;
5152 }
5153 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
5154 << NewTD << isa<TypeAliasDecl>(NewTD);
5155
5156 if (ChangesLinkage)
5157 return;
5158 }
5159
5160 // Otherwise, set this as the anon-decl typedef for the tag.
5161 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
5162
5163 // Now that we have a name for the tag, process API notes again.
5164 ProcessAPINotes(TagFromDeclSpec);
5165}
5166
5167static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {
5169 switch (T) {
5171 return 0;
5173 return 1;
5175 return 2;
5177 return 3;
5178 case DeclSpec::TST_enum:
5179 if (const auto *ED = dyn_cast<EnumDecl>(DS.getRepAsDecl())) {
5180 if (ED->isScopedUsingClassTag())
5181 return 5;
5182 if (ED->isScoped())
5183 return 6;
5184 }
5185 return 4;
5186 default:
5187 llvm_unreachable("unexpected type specifier");
5188 }
5189}
5190
5192 DeclSpec &DS,
5193 const ParsedAttributesView &DeclAttrs,
5194 MultiTemplateParamsArg TemplateParams,
5195 bool IsExplicitInstantiation,
5196 RecordDecl *&AnonRecord,
5197 SourceLocation EllipsisLoc) {
5198 Decl *TagD = nullptr;
5199 TagDecl *Tag = nullptr;
5205 TagD = DS.getRepAsDecl();
5206
5207 if (!TagD) // We probably had an error
5208 return nullptr;
5209
5210 // Note that the above type specs guarantee that the
5211 // type rep is a Decl, whereas in many of the others
5212 // it's a Type.
5213 if (isa<TagDecl>(TagD))
5214 Tag = cast<TagDecl>(TagD);
5215 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
5216 Tag = CTD->getTemplatedDecl();
5217 }
5218
5219 if (Tag) {
5220 handleTagNumbering(Tag, S);
5221 Tag->setFreeStanding();
5222 if (Tag->isInvalidDecl())
5223 return Tag;
5224 }
5225
5226 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5227 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5228 // or incomplete types shall not be restrict-qualified."
5229 if (TypeQuals & DeclSpec::TQ_restrict)
5231 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5232 << DS.getSourceRange();
5233 }
5234
5235 if (DS.isInlineSpecified())
5236 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
5237 << getLangOpts().CPlusPlus17;
5238
5239 if (DS.hasConstexprSpecifier()) {
5240 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5241 // and definitions of functions and variables.
5242 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5243 // the declaration of a function or function template
5244 if (Tag)
5245 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
5247 << static_cast<int>(DS.getConstexprSpecifier());
5248 else if (getLangOpts().C23)
5249 Diag(DS.getConstexprSpecLoc(), diag::err_c23_constexpr_not_variable);
5250 else
5251 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
5252 << static_cast<int>(DS.getConstexprSpecifier());
5253 // Don't emit warnings after this error.
5254 return TagD;
5255 }
5256
5258
5259 if (DS.isFriendSpecified()) {
5260 // If we're dealing with a decl but not a TagDecl, assume that
5261 // whatever routines created it handled the friendship aspect.
5262 if (TagD && !Tag)
5263 return nullptr;
5264 return ActOnFriendTypeDecl(S, DS, TemplateParams, EllipsisLoc);
5265 }
5266
5267 assert(EllipsisLoc.isInvalid() &&
5268 "Friend ellipsis but not friend-specified?");
5269
5270 // Track whether this decl-specifier declares anything.
5271 bool DeclaresAnything = true;
5272
5273 // Handle anonymous struct definitions.
5274 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
5275 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5277 if (getLangOpts().CPlusPlus ||
5278 Record->getDeclContext()->isRecord()) {
5279 // If CurContext is a DeclContext that can contain statements,
5280 // RecursiveASTVisitor won't visit the decls that
5281 // BuildAnonymousStructOrUnion() will put into CurContext.
5282 // Also store them here so that they can be part of the
5283 // DeclStmt that gets created in this case.
5284 // FIXME: Also return the IndirectFieldDecls created by
5285 // BuildAnonymousStructOr union, for the same reason?
5286 if (CurContext->isFunctionOrMethod())
5287 AnonRecord = Record;
5288 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5289 Context.getPrintingPolicy());
5290 }
5291
5292 DeclaresAnything = false;
5293 }
5294 }
5295
5296 // C11 6.7.2.1p2:
5297 // A struct-declaration that does not declare an anonymous structure or
5298 // anonymous union shall contain a struct-declarator-list.
5299 //
5300 // This rule also existed in C89 and C99; the grammar for struct-declaration
5301 // did not permit a struct-declaration without a struct-declarator-list.
5302 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5304 // Check for Microsoft C extension: anonymous struct/union member.
5305 // Handle 2 kinds of anonymous struct/union:
5306 // struct STRUCT;
5307 // union UNION;
5308 // and
5309 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5310 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5311 if ((Tag && Tag->getDeclName()) ||
5313 RecordDecl *Record = Tag ? dyn_cast<RecordDecl>(Tag)
5314 : DS.getRepAsType().get()->getAsRecordDecl();
5315 if (Record && getLangOpts().MicrosoftExt) {
5316 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5317 << Record->isUnion() << DS.getSourceRange();
5319 }
5320
5321 DeclaresAnything = false;
5322 }
5323 }
5324
5325 // Skip all the checks below if we have a type error.
5327 (TagD && TagD->isInvalidDecl()))
5328 return TagD;
5329
5330 if (getLangOpts().CPlusPlus &&
5332 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5333 if (Enum->enumerators().empty() && !Enum->getIdentifier() &&
5334 !Enum->isInvalidDecl())
5335 DeclaresAnything = false;
5336
5337 if (!DS.isMissingDeclaratorOk()) {
5338 // Customize diagnostic for a typedef missing a name.
5340 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5341 << DS.getSourceRange();
5342 else
5343 DeclaresAnything = false;
5344 }
5345
5346 if (DS.isModulePrivateSpecified() &&
5347 Tag && Tag->getDeclContext()->isFunctionOrMethod())
5348 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5349 << Tag->getTagKind()
5351
5353
5354 // C 6.7/2:
5355 // A declaration [...] shall declare at least a declarator [...], a tag,
5356 // or the members of an enumeration.
5357 // C++ [dcl.dcl]p3:
5358 // [If there are no declarators], and except for the declaration of an
5359 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5360 // names into the program, or shall redeclare a name introduced by a
5361 // previous declaration.
5362 if (!DeclaresAnything) {
5363 // In C, we allow this as a (popular) extension / bug. Don't bother
5364 // producing further diagnostics for redundant qualifiers after this.
5365 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5366 ? diag::err_no_declarators
5367 : diag::ext_no_declarators)
5368 << DS.getSourceRange();
5369 return TagD;
5370 }
5371
5372 // C++ [dcl.stc]p1:
5373 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5374 // init-declarator-list of the declaration shall not be empty.
5375 // C++ [dcl.fct.spec]p1:
5376 // If a cv-qualifier appears in a decl-specifier-seq, the
5377 // init-declarator-list of the declaration shall not be empty.
5378 //
5379 // Spurious qualifiers here appear to be valid in C.
5380 unsigned DiagID = diag::warn_standalone_specifier;
5381 if (getLangOpts().CPlusPlus)
5382 DiagID = diag::ext_standalone_specifier;
5383
5384 // Note that a linkage-specification sets a storage class, but
5385 // 'extern "C" struct foo;' is actually valid and not theoretically
5386 // useless.
5387 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5388 if (SCS == DeclSpec::SCS_mutable)
5389 // Since mutable is not a viable storage class specifier in C, there is
5390 // no reason to treat it as an extension. Instead, diagnose as an error.
5391 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5392 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5393 Diag(DS.getStorageClassSpecLoc(), DiagID)
5395 }
5396
5400 if (DS.getTypeQualifiers()) {
5402 Diag(DS.getConstSpecLoc(), DiagID) << "const";
5404 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5405 // Restrict is covered above.
5407 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5409 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5410 }
5411
5412 // Warn about ignored type attributes, for example:
5413 // __attribute__((aligned)) struct A;
5414 // Attributes should be placed after tag to apply to type declaration.
5415 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5416 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5417 if (TypeSpecType == DeclSpec::TST_class ||
5418 TypeSpecType == DeclSpec::TST_struct ||
5419 TypeSpecType == DeclSpec::TST_interface ||
5420 TypeSpecType == DeclSpec::TST_union ||
5421 TypeSpecType == DeclSpec::TST_enum) {
5422
5423 auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) {
5424 unsigned DiagnosticId = diag::warn_declspec_attribute_ignored;
5425 if (AL.isAlignas() && !getLangOpts().CPlusPlus)
5426 DiagnosticId = diag::warn_attribute_ignored;
5427 else if (AL.isRegularKeywordAttribute())
5428 DiagnosticId = diag::err_declspec_keyword_has_no_effect;
5429 else
5430 DiagnosticId = diag::warn_declspec_attribute_ignored;
5431 Diag(AL.getLoc(), DiagnosticId)
5432 << AL << GetDiagnosticTypeSpecifierID(DS);
5433 };
5434
5435 llvm::for_each(DS.getAttributes(), EmitAttributeDiagnostic);
5436 llvm::for_each(DeclAttrs, EmitAttributeDiagnostic);
5437 }
5438 }
5439
5440 return TagD;
5441}
5442
5443/// We are trying to inject an anonymous member into the given scope;
5444/// check if there's an existing declaration that can't be overloaded.
5445///
5446/// \return true if this is a forbidden redeclaration
5447static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S,
5448 DeclContext *Owner,
5449 DeclarationName Name,
5450 SourceLocation NameLoc, bool IsUnion,
5451 StorageClass SC) {
5452 LookupResult R(SemaRef, Name, NameLoc,
5456 if (!SemaRef.LookupName(R, S)) return false;
5457
5458 // Pick a representative declaration.
5460 assert(PrevDecl && "Expected a non-null Decl");
5461
5462 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5463 return false;
5464
5465 if (SC == StorageClass::SC_None &&
5466 PrevDecl->isPlaceholderVar(SemaRef.getLangOpts()) &&
5467 (Owner->isFunctionOrMethod() || Owner->isRecord())) {
5468 if (!Owner->isRecord())
5469 SemaRef.DiagPlaceholderVariableDefinition(NameLoc);
5470 return false;
5471 }
5472
5473 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5474 << IsUnion << Name;
5475 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5476
5477 return true;
5478}
5479
5481 if (auto *RD = dyn_cast_if_present<RecordDecl>(D))
5483}
5484
5486 if (!getLangOpts().CPlusPlus)
5487 return;
5488
5489 // This function can be parsed before we have validated the
5490 // structure as an anonymous struct
5491 if (Record->isAnonymousStructOrUnion())
5492 return;
5493
5494 const NamedDecl *First = 0;
5495 for (const Decl *D : Record->decls()) {
5496 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
5497 if (!ND || !ND->isPlaceholderVar(getLangOpts()))
5498 continue;
5499 if (!First)
5500 First = ND;
5501 else
5503 }
5504}
5505
5506/// InjectAnonymousStructOrUnionMembers - Inject the members of the
5507/// anonymous struct or union AnonRecord into the owning context Owner
5508/// and scope S. This routine will be invoked just after we realize
5509/// that an unnamed union or struct is actually an anonymous union or
5510/// struct, e.g.,
5511///
5512/// @code
5513/// union {
5514/// int i;
5515/// float f;
5516/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5517/// // f into the surrounding scope.x
5518/// @endcode
5519///
5520/// This routine is recursive, injecting the names of nested anonymous
5521/// structs/unions into the owning context and scope as well.
5522static bool
5524 RecordDecl *AnonRecord, AccessSpecifier AS,
5525 StorageClass SC,
5526 SmallVectorImpl<NamedDecl *> &Chaining) {
5527 bool Invalid = false;
5528
5529 // Look every FieldDecl and IndirectFieldDecl with a name.
5530 for (auto *D : AnonRecord->decls()) {
5531 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5532 cast<NamedDecl>(D)->getDeclName()) {
5533 ValueDecl *VD = cast<ValueDecl>(D);
5534 // C++ [class.union]p2:
5535 // The names of the members of an anonymous union shall be
5536 // distinct from the names of any other entity in the
5537 // scope in which the anonymous union is declared.
5538
5539 bool FieldInvalid = CheckAnonMemberRedeclaration(
5540 SemaRef, S, Owner, VD->getDeclName(), VD->getLocation(),
5541 AnonRecord->isUnion(), SC);
5542 if (FieldInvalid)
5543 Invalid = true;
5544
5545 // Inject the IndirectFieldDecl even if invalid, because later
5546 // diagnostics may depend on it being present, see findDefaultInitializer.
5547
5548 // C++ [class.union]p2:
5549 // For the purpose of name lookup, after the anonymous union
5550 // definition, the members of the anonymous union are
5551 // considered to have been defined in the scope in which the
5552 // anonymous union is declared.
5553 unsigned OldChainingSize = Chaining.size();
5554 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5555 Chaining.append(IF->chain_begin(), IF->chain_end());
5556 else
5557 Chaining.push_back(VD);
5558
5559 assert(Chaining.size() >= 2);
5560 NamedDecl **NamedChain =
5561 new (SemaRef.Context) NamedDecl *[Chaining.size()];
5562 for (unsigned i = 0; i < Chaining.size(); i++)
5563 NamedChain[i] = Chaining[i];
5564
5566 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5567 VD->getType(), {NamedChain, Chaining.size()});
5568
5569 for (const auto *Attr : VD->attrs())
5570 IndirectField->addAttr(Attr->clone(SemaRef.Context));
5571
5572 IndirectField->setAccess(AS);
5573 IndirectField->setImplicit();
5574 IndirectField->setInvalidDecl(FieldInvalid);
5575 SemaRef.PushOnScopeChains(IndirectField, S);
5576
5577 // That includes picking up the appropriate access specifier.
5578 if (AS != AS_none)
5579 IndirectField->setAccess(AS);
5580
5581 Chaining.resize(OldChainingSize);
5582 }
5583 }
5584
5585 return Invalid;
5586}
5587
5588/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5589/// a VarDecl::StorageClass. Any error reporting is up to the caller:
5590/// illegal input values are mapped to SC_None.
5591static StorageClass
5593 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5594 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5595 "Parser allowed 'typedef' as storage class VarDecl.");
5596 switch (StorageClassSpec) {
5599 if (DS.isExternInLinkageSpec())
5600 return SC_None;
5601 return SC_Extern;
5602 case DeclSpec::SCS_static: return SC_Static;
5603 case DeclSpec::SCS_auto: return SC_Auto;
5606 // Illegal SCSs map to None: error reporting is up to the caller.
5607 case DeclSpec::SCS_mutable: // Fall through.
5608 case DeclSpec::SCS_typedef: return SC_None;
5609 }
5610 llvm_unreachable("unknown storage class specifier");
5611}
5612
5614 assert(Record->hasInClassInitializer());
5615
5616 for (const auto *I : Record->decls()) {
5617 const auto *FD = dyn_cast<FieldDecl>(I);
5618 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5619 FD = IFD->getAnonField();
5620 if (FD && FD->hasInClassInitializer())
5621 return FD->getLocation();
5622 }
5623
5624 llvm_unreachable("couldn't find in-class initializer");
5625}
5626
5628 SourceLocation DefaultInitLoc) {
5629 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5630 return;
5631
5632 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5633 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5634}
5635
5637 CXXRecordDecl *AnonUnion) {
5638 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5639 return;
5640
5642}
5643
5645 AccessSpecifier AS,
5647 const PrintingPolicy &Policy) {
5648 DeclContext *Owner = Record->getDeclContext();
5649
5650 // Diagnose whether this anonymous struct/union is an extension.
5651 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5652 Diag(Record->getLocation(), diag::ext_anonymous_union);
5653 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5654 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5655 else if (!Record->isUnion() && !getLangOpts().C11)
5656 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5657
5658 // C and C++ require different kinds of checks for anonymous
5659 // structs/unions.
5660 bool Invalid = false;
5661 if (getLangOpts().CPlusPlus) {
5662 const char *PrevSpec = nullptr;
5663 if (Record->isUnion()) {
5664 // C++ [class.union]p6:
5665 // C++17 [class.union.anon]p2:
5666 // Anonymous unions declared in a named namespace or in the
5667 // global namespace shall be declared static.
5668 unsigned DiagID;
5669 DeclContext *OwnerScope = Owner->getRedeclContext();
5671 (OwnerScope->isTranslationUnit() ||
5672 (OwnerScope->isNamespace() &&
5673 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5674 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5675 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5676
5677 // Recover by adding 'static'.
5679 PrevSpec, DiagID, Policy);
5680 }
5681 // C++ [class.union]p6:
5682 // A storage class is not allowed in a declaration of an
5683 // anonymous union in a class scope.
5685 isa<RecordDecl>(Owner)) {
5687 diag::err_anonymous_union_with_storage_spec)
5689
5690 // Recover by removing the storage specifier.
5693 PrevSpec, DiagID, Context.getPrintingPolicy());
5694 }
5695 }
5696
5697 // Ignore const/volatile/restrict qualifiers.
5698 if (DS.getTypeQualifiers()) {
5700 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5701 << Record->isUnion() << "const"
5705 diag::ext_anonymous_struct_union_qualified)
5706 << Record->isUnion() << "volatile"
5710 diag::ext_anonymous_struct_union_qualified)
5711 << Record->isUnion() << "restrict"
5715 diag::ext_anonymous_struct_union_qualified)
5716 << Record->isUnion() << "_Atomic"
5720 diag::ext_anonymous_struct_union_qualified)
5721 << Record->isUnion() << "__unaligned"
5723
5725 }
5726
5727 // C++ [class.union]p2:
5728 // The member-specification of an anonymous union shall only
5729 // define non-static data members. [Note: nested types and
5730 // functions cannot be declared within an anonymous union. ]
5731 for (auto *Mem : Record->decls()) {
5732 // Ignore invalid declarations; we already diagnosed them.
5733 if (Mem->isInvalidDecl())
5734 continue;
5735
5736 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5737 // C++ [class.union]p3:
5738 // An anonymous union shall not have private or protected
5739 // members (clause 11).
5740 assert(FD->getAccess() != AS_none);
5741 if (FD->getAccess() != AS_public) {
5742 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5743 << Record->isUnion() << (FD->getAccess() == AS_protected);
5744 Invalid = true;
5745 }
5746
5747 // C++ [class.union]p1
5748 // An object of a class with a non-trivial constructor, a non-trivial
5749 // copy constructor, a non-trivial destructor, or a non-trivial copy
5750 // assignment operator cannot be a member of a union, nor can an
5751 // array of such objects.
5752 if (CheckNontrivialField(FD))
5753 Invalid = true;
5754 } else if (Mem->isImplicit()) {
5755 // Any implicit members are fine.
5756 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5757 // This is a type that showed up in an
5758 // elaborated-type-specifier inside the anonymous struct or
5759 // union, but which actually declares a type outside of the
5760 // anonymous struct or union. It's okay.
5761 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5762 if (!MemRecord->isAnonymousStructOrUnion() &&
5763 MemRecord->getDeclName()) {
5764 // Visual C++ allows type definition in anonymous struct or union.
5765 if (getLangOpts().MicrosoftExt)
5766 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5767 << Record->isUnion();
5768 else {
5769 // This is a nested type declaration.
5770 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5771 << Record->isUnion();
5772 Invalid = true;
5773 }
5774 } else {
5775 // This is an anonymous type definition within another anonymous type.
5776 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5777 // not part of standard C++.
5778 Diag(MemRecord->getLocation(),
5779 diag::ext_anonymous_record_with_anonymous_type)
5780 << Record->isUnion();
5781 }
5782 } else if (isa<AccessSpecDecl>(Mem)) {
5783 // Any access specifier is fine.
5784 } else if (isa<StaticAssertDecl>(Mem)) {
5785 // In C++1z, static_assert declarations are also fine.
5786 } else {
5787 // We have something that isn't a non-static data
5788 // member. Complain about it.
5789 unsigned DK = diag::err_anonymous_record_bad_member;
5790 if (isa<TypeDecl>(Mem))
5791 DK = diag::err_anonymous_record_with_type;
5792 else if (isa<FunctionDecl>(Mem))
5793 DK = diag::err_anonymous_record_with_function;
5794 else if (isa<VarDecl>(Mem))
5795 DK = diag::err_anonymous_record_with_static;
5796
5797 // Visual C++ allows type definition in anonymous struct or union.
5798 if (getLangOpts().MicrosoftExt &&
5799 DK == diag::err_anonymous_record_with_type)
5800 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5801 << Record->isUnion();
5802 else {
5803 Diag(Mem->getLocation(), DK) << Record->isUnion();
5804 Invalid = true;
5805 }
5806 }
5807 }
5808
5809 // C++11 [class.union]p8 (DR1460):
5810 // At most one variant member of a union may have a
5811 // brace-or-equal-initializer.
5812 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5813 Owner->isRecord())
5816 }
5817
5818 if (!Record->isUnion() && !Owner->isRecord()) {
5819 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5820 << getLangOpts().CPlusPlus;
5821 Invalid = true;
5822 }
5823
5824 // C++ [dcl.dcl]p3:
5825 // [If there are no declarators], and except for the declaration of an
5826 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5827 // names into the program
5828 // C++ [class.mem]p2:
5829 // each such member-declaration shall either declare at least one member
5830 // name of the class or declare at least one unnamed bit-field
5831 //
5832 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5833 if (getLangOpts().CPlusPlus && Record->field_empty())
5834 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5835
5836 // Mock up a declarator.
5840 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5841
5842 // Create a declaration for this anonymous struct/union.
5843 NamedDecl *Anon = nullptr;
5844 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5845 Anon = FieldDecl::Create(
5846 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5847 /*IdentifierInfo=*/nullptr, Context.getCanonicalTagType(Record), TInfo,
5848 /*BitWidth=*/nullptr, /*Mutable=*/false,
5849 /*InitStyle=*/ICIS_NoInit);
5850 Anon->setAccess(AS);
5851 ProcessDeclAttributes(S, Anon, Dc);
5852
5853 if (getLangOpts().CPlusPlus)
5854 FieldCollector->Add(cast<FieldDecl>(Anon));
5855 } else {
5856 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5857 if (SCSpec == DeclSpec::SCS_mutable) {
5858 // mutable can only appear on non-static class members, so it's always
5859 // an error here
5860 Diag(Record->getLocation(), diag::err_mutable_nonmember);
5861 Invalid = true;
5862 SC = SC_None;
5863 }
5864
5865 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5866 Record->getLocation(), /*IdentifierInfo=*/nullptr,
5867 Context.getCanonicalTagType(Record), TInfo, SC);
5868 if (Invalid)
5869 Anon->setInvalidDecl();
5870
5871 ProcessDeclAttributes(S, Anon, Dc);
5872
5873 // Default-initialize the implicit variable. This initialization will be
5874 // trivial in almost all cases, except if a union member has an in-class
5875 // initializer:
5876 // union { int n = 0; };
5878 }
5879 Anon->setImplicit();
5880
5881 // Mark this as an anonymous struct/union type.
5882 Record->setAnonymousStructOrUnion(true);
5883
5884 // Add the anonymous struct/union object to the current
5885 // context. We'll be referencing this object when we refer to one of
5886 // its members.
5887 Owner->addDecl(Anon);
5888
5889 // Inject the members of the anonymous struct/union into the owning
5890 // context and into the identifier resolver chain for name lookup
5891 // purposes.
5893 Chain.push_back(Anon);
5894
5895 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, SC,
5896 Chain))
5897 Invalid = true;
5898
5899 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5900 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5902 Decl *ManglingContextDecl;
5903 std::tie(MCtx, ManglingContextDecl) =
5904 getCurrentMangleNumberContext(NewVD->getDeclContext());
5905 if (MCtx) {
5906 Context.setManglingNumber(
5907 NewVD, MCtx->getManglingNumber(
5908 NewVD, getMSManglingNumber(getLangOpts(), S)));
5909 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5910 }
5911 }
5912 }
5913
5914 if (Invalid)
5915 Anon->setInvalidDecl();
5916
5917 return Anon;
5918}
5919
5921 RecordDecl *Record) {
5922 assert(Record && "expected a record!");
5923
5924 // Mock up a declarator.
5927 assert(TInfo && "couldn't build declarator info for anonymous struct");
5928
5929 auto *ParentDecl = cast<RecordDecl>(CurContext);
5930 CanQualType RecTy = Context.getCanonicalTagType(Record);
5931
5932 // Create a declaration for this anonymous struct.
5933 NamedDecl *Anon =
5934 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5935 /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5936 /*BitWidth=*/nullptr, /*Mutable=*/false,
5937 /*InitStyle=*/ICIS_NoInit);
5938 Anon->setImplicit();
5939
5940 // Add the anonymous struct object to the current context.
5941 CurContext->addDecl(Anon);
5942
5943 // Inject the members of the anonymous struct into the current
5944 // context and into the identifier resolver chain for name lookup
5945 // purposes.
5947 Chain.push_back(Anon);
5948
5949 RecordDecl *RecordDef = Record->getDefinition();
5950 if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5951 diag::err_field_incomplete_or_sizeless) ||
5953 *this, S, CurContext, RecordDef, AS_none,
5955 Anon->setInvalidDecl();
5956 ParentDecl->setInvalidDecl();
5957 }
5958
5959 return Anon;
5960}
5961
5965
5968 DeclarationNameInfo NameInfo;
5969 NameInfo.setLoc(Name.StartLocation);
5970
5971 switch (Name.getKind()) {
5972
5975 NameInfo.setName(Name.Identifier);
5976 return NameInfo;
5977
5979 // C++ [temp.deduct.guide]p3:
5980 // The simple-template-id shall name a class template specialization.
5981 // The template-name shall be the same identifier as the template-name
5982 // of the simple-template-id.
5983 // These together intend to imply that the template-name shall name a
5984 // class template.
5985 // FIXME: template<typename T> struct X {};
5986 // template<typename T> using Y = X<T>;
5987 // Y(int) -> Y<int>;
5988 // satisfies these rules but does not name a class template.
5989 TemplateName TN = Name.TemplateName.get().get();
5990 auto *Template = TN.getAsTemplateDecl();
5992 Diag(Name.StartLocation,
5993 diag::err_deduction_guide_name_not_class_template)
5994 << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5995 if (Template)
5997 return DeclarationNameInfo();
5998 }
5999
6000 NameInfo.setName(
6001 Context.DeclarationNames.getCXXDeductionGuideName(Template));
6002 return NameInfo;
6003 }
6004
6006 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
6010 return NameInfo;
6011
6013 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
6014 Name.Identifier));
6016 return NameInfo;
6017
6019 TypeSourceInfo *TInfo;
6021 if (Ty.isNull())
6022 return DeclarationNameInfo();
6023 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
6024 Context.getCanonicalType(Ty)));
6025 NameInfo.setNamedTypeInfo(TInfo);
6026 return NameInfo;
6027 }
6028
6030 TypeSourceInfo *TInfo;
6031 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
6032 if (Ty.isNull())
6033 return DeclarationNameInfo();
6034 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
6035 Context.getCanonicalType(Ty)));
6036 NameInfo.setNamedTypeInfo(TInfo);
6037 return NameInfo;
6038 }
6039
6041 // In well-formed code, we can only have a constructor
6042 // template-id that refers to the current context, so go there
6043 // to find the actual type being constructed.
6044 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
6045 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
6046 return DeclarationNameInfo();
6047
6048 // Determine the type of the class being constructed.
6049 CanQualType CurClassType = Context.getCanonicalTagType(CurClass);
6050
6051 // FIXME: Check two things: that the template-id names the same type as
6052 // CurClassType, and that the template-id does not occur when the name
6053 // was qualified.
6054
6055 NameInfo.setName(
6056 Context.DeclarationNames.getCXXConstructorName(CurClassType));
6057 // FIXME: should we retrieve TypeSourceInfo?
6058 NameInfo.setNamedTypeInfo(nullptr);
6059 return NameInfo;
6060 }
6061
6063 TypeSourceInfo *TInfo;
6064 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
6065 if (Ty.isNull())
6066 return DeclarationNameInfo();
6067 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
6068 Context.getCanonicalType(Ty)));
6069 NameInfo.setNamedTypeInfo(TInfo);
6070 return NameInfo;
6071 }
6072
6074 TemplateName TName = Name.TemplateId->Template.get();
6075 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
6076 return Context.getNameForTemplate(TName, TNameLoc);
6077 }
6078
6079 } // switch (Name.getKind())
6080
6081 llvm_unreachable("Unknown name kind");
6082}
6083
6085 do {
6086 if (Ty->isPointerOrReferenceType())
6087 Ty = Ty->getPointeeType();
6088 else if (Ty->isArrayType())
6090 else
6091 return Ty.withoutLocalFastQualifiers();
6092 } while (true);
6093}
6094
6095/// hasSimilarParameters - Determine whether the C++ functions Declaration
6096/// and Definition have "nearly" matching parameters. This heuristic is
6097/// used to improve diagnostics in the case where an out-of-line function
6098/// definition doesn't match any declaration within the class or namespace.
6099/// Also sets Params to the list of indices to the parameters that differ
6100/// between the declaration and the definition. If hasSimilarParameters
6101/// returns true and Params is empty, then all of the parameters match.
6105 SmallVectorImpl<unsigned> &Params) {
6106 Params.clear();
6107 if (Declaration->param_size() != Definition->param_size())
6108 return false;
6109 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
6110 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
6111 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
6112
6113 // The parameter types are identical
6114 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
6115 continue;
6116
6117 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
6118 QualType DefParamBaseTy = getCoreType(DefParamTy);
6119 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
6120 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
6121
6122 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
6123 (DeclTyName && DeclTyName == DefTyName))
6124 Params.push_back(Idx);
6125 else // The two parameters aren't even close
6126 return false;
6127 }
6128
6129 return true;
6130}
6131
6132/// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
6133/// declarator needs to be rebuilt in the current instantiation.
6134/// Any bits of declarator which appear before the name are valid for
6135/// consideration here. That's specifically the type in the decl spec
6136/// and the base type in any member-pointer chunks.
6138 DeclarationName Name) {
6139 // The types we specifically need to rebuild are:
6140 // - typenames, typeofs, and decltypes
6141 // - types which will become injected class names
6142 // Of course, we also need to rebuild any type referencing such a
6143 // type. It's safest to just say "dependent", but we call out a
6144 // few cases here.
6145
6146 DeclSpec &DS = D.getMutableDeclSpec();
6147 switch (DS.getTypeSpecType()) {
6151#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
6152#include "clang/Basic/TransformTypeTraits.def"
6153 case DeclSpec::TST_atomic: {
6154 // Grab the type from the parser.
6155 TypeSourceInfo *TSI = nullptr;
6156 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
6157 if (T.isNull() || !T->isInstantiationDependentType()) break;
6158
6159 // Make sure there's a type source info. This isn't really much
6160 // of a waste; most dependent types should have type source info
6161 // attached already.
6162 if (!TSI)
6164
6165 // Rebuild the type in the current instantiation.
6167 if (!TSI) return true;
6168
6169 // Store the new type back in the decl spec.
6170 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
6171 DS.UpdateTypeRep(LocType);
6172 break;
6173 }
6174
6178 Expr *E = DS.getRepAsExpr();
6180 if (Result.isInvalid()) return true;
6181 DS.UpdateExprRep(Result.get());
6182 break;
6183 }
6184
6185 default:
6186 // Nothing to do for these decl specs.
6187 break;
6188 }
6189
6190 // It doesn't matter what order we do this in.
6191 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
6192 DeclaratorChunk &Chunk = D.getTypeObject(I);
6193
6194 // The only type information in the declarator which can come
6195 // before the declaration name is the base type of a member
6196 // pointer.
6198 continue;
6199
6200 // Rebuild the scope specifier in-place.
6201 CXXScopeSpec &SS = Chunk.Mem.Scope();
6203 return true;
6204 }
6205
6206 return false;
6207}
6208
6209/// Returns true if the declaration is declared in a system header or from a
6210/// system macro.
6211static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
6212 return SM.isInSystemHeader(D->getLocation()) ||
6213 SM.isInSystemMacro(D->getLocation());
6214}
6215
6217 // Avoid warning twice on the same identifier, and don't warn on redeclaration
6218 // of system decl.
6219 if (D->getPreviousDecl() || D->isImplicit())
6220 return;
6223 !isFromSystemHeader(Context.getSourceManager(), D)) {
6224 Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
6225 << D << static_cast<int>(Status);
6226 }
6227}
6228
6231
6232 // Check if we are in an `omp begin/end declare variant` scope. Handle this
6233 // declaration only if the `bind_to_declaration` extension is set.
6235 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
6236 if (OpenMP().getOMPTraitInfoForSurroundingScope()->isExtensionActive(
6237 llvm::omp::TraitProperty::
6238 implementation_extension_bind_to_declaration))
6240 S, D, MultiTemplateParamsArg(), Bases);
6241
6243
6244 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
6245 Dcl && Dcl->getDeclContext()->isFileContext())
6247
6248 if (!Bases.empty())
6250 Bases);
6251
6252 return Dcl;
6253}
6254
6256 DeclarationNameInfo NameInfo) {
6257 DeclarationName Name = NameInfo.getName();
6258
6259 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
6260 while (Record && Record->isAnonymousStructOrUnion())
6261 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
6262 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6263 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
6264 return true;
6265 }
6266
6267 return false;
6268}
6269
6271 DeclarationName Name,
6272 SourceLocation Loc,
6273 TemplateIdAnnotation *TemplateId,
6274 bool IsMemberSpecialization) {
6275 assert(SS.isValid() && "diagnoseQualifiedDeclaration called for declaration "
6276 "without nested-name-specifier");
6277 DeclContext *Cur = CurContext;
6278 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
6279 Cur = Cur->getParent();
6280
6281 // If the user provided a superfluous scope specifier that refers back to the
6282 // class in which the entity is already declared, diagnose and ignore it.
6283 //
6284 // class X {
6285 // void X::f();
6286 // };
6287 //
6288 // Note, it was once ill-formed to give redundant qualification in all
6289 // contexts, but that rule was removed by DR482.
6290 if (Cur->Equals(DC)) {
6291 if (Cur->isRecord()) {
6292 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6293 : diag::err_member_extra_qualification)
6294 << Name << FixItHint::CreateRemoval(SS.getRange());
6295 SS.clear();
6296 } else {
6297 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
6298 }
6299 return false;
6300 }
6301
6302 // Check whether the qualifying scope encloses the scope of the original
6303 // declaration. For a template-id, we perform the checks in
6304 // CheckTemplateSpecializationScope.
6305 if (!Cur->Encloses(DC) && !(TemplateId || IsMemberSpecialization)) {
6306 if (Cur->isRecord())
6307 Diag(Loc, diag::err_member_qualification)
6308 << Name << SS.getRange();
6309 else if (isa<TranslationUnitDecl>(DC))
6310 Diag(Loc, diag::err_invalid_declarator_global_scope)
6311 << Name << SS.getRange();
6312 else if (isa<FunctionDecl>(Cur))
6313 Diag(Loc, diag::err_invalid_declarator_in_function)
6314 << Name << SS.getRange();
6315 else if (isa<BlockDecl>(Cur))
6316 Diag(Loc, diag::err_invalid_declarator_in_block)
6317 << Name << SS.getRange();
6318 else if (isa<ExportDecl>(Cur)) {
6319 if (!isa<NamespaceDecl>(DC))
6320 Diag(Loc, diag::err_export_non_namespace_scope_name)
6321 << Name << SS.getRange();
6322 else
6323 // The cases that DC is not NamespaceDecl should be handled in
6324 // CheckRedeclarationExported.
6325 return false;
6326 } else
6327 Diag(Loc, diag::err_invalid_declarator_scope)
6328 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
6329
6330 return true;
6331 }
6332
6333 if (Cur->isRecord()) {
6334 // Cannot qualify members within a class.
6335 Diag(Loc, diag::err_member_qualification)
6336 << Name << SS.getRange();
6337 SS.clear();
6338
6339 // C++ constructors and destructors with incorrect scopes can break
6340 // our AST invariants by having the wrong underlying types. If
6341 // that's the case, then drop this declaration entirely.
6344 !Context.hasSameType(
6345 Name.getCXXNameType(),
6346 Context.getCanonicalTagType(cast<CXXRecordDecl>(Cur))))
6347 return true;
6348
6349 return false;
6350 }
6351
6352 // C++23 [temp.names]p5:
6353 // The keyword template shall not appear immediately after a declarative
6354 // nested-name-specifier.
6355 //
6356 // First check the template-id (if any), and then check each component of the
6357 // nested-name-specifier in reverse order.
6358 //
6359 // FIXME: nested-name-specifiers in friend declarations are declarative,
6360 // but we don't call diagnoseQualifiedDeclaration for them. We should.
6361 if (TemplateId && TemplateId->TemplateKWLoc.isValid())
6362 Diag(Loc, diag::ext_template_after_declarative_nns)
6364
6366 for (TypeLoc TL = SpecLoc.getAsTypeLoc(), NextTL; TL;
6367 TL = std::exchange(NextTL, TypeLoc())) {
6368 SourceLocation TemplateKeywordLoc;
6369 switch (TL.getTypeLocClass()) {
6370 case TypeLoc::TemplateSpecialization: {
6371 auto TST = TL.castAs<TemplateSpecializationTypeLoc>();
6372 TemplateKeywordLoc = TST.getTemplateKeywordLoc();
6373 if (auto *T = TST.getTypePtr(); T->isDependentType() && T->isTypeAlias())
6374 Diag(Loc, diag::ext_alias_template_in_declarative_nns)
6375 << TST.getLocalSourceRange();
6376 break;
6377 }
6378 case TypeLoc::Decltype:
6379 case TypeLoc::PackIndexing: {
6380 const Type *T = TL.getTypePtr();
6381 // C++23 [expr.prim.id.qual]p2:
6382 // [...] A declarative nested-name-specifier shall not have a
6383 // computed-type-specifier.
6384 //
6385 // CWG2858 changed this from 'decltype-specifier' to
6386 // 'computed-type-specifier'.
6387 Diag(Loc, diag::err_computed_type_in_declarative_nns)
6388 << T->isDecltypeType() << TL.getSourceRange();
6389 break;
6390 }
6391 case TypeLoc::DependentName:
6392 NextTL =
6393 TL.castAs<DependentNameTypeLoc>().getQualifierLoc().getAsTypeLoc();
6394 break;
6395 case TypeLoc::DependentTemplateSpecialization: {
6396 auto TST = TL.castAs<DependentTemplateSpecializationTypeLoc>();
6397 TemplateKeywordLoc = TST.getTemplateKeywordLoc();
6398 NextTL = TST.getQualifierLoc().getAsTypeLoc();
6399 break;
6400 }
6401 default:
6402 break;
6403 }
6404 if (TemplateKeywordLoc.isValid())
6405 Diag(Loc, diag::ext_template_after_declarative_nns)
6406 << FixItHint::CreateRemoval(TemplateKeywordLoc);
6407 }
6408
6409 return false;
6410}
6411
6413 MultiTemplateParamsArg TemplateParamLists) {
6414 // TODO: consider using NameInfo for diagnostic.
6416 DeclarationName Name = NameInfo.getName();
6417
6418 // All of these full declarators require an identifier. If it doesn't have
6419 // one, the ParsedFreeStandingDeclSpec action should be used.
6420 if (D.isDecompositionDeclarator()) {
6421 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6422 } else if (!Name) {
6423 if (!D.isInvalidType()) // Reject this if we think it is valid.
6424 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6426 return nullptr;
6428 return nullptr;
6429
6430 DeclContext *DC = CurContext;
6431 if (D.getCXXScopeSpec().isInvalid())
6432 D.setInvalidType();
6433 else if (D.getCXXScopeSpec().isSet()) {
6436 return nullptr;
6437
6438 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6439 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
6440 if (!DC || isa<EnumDecl>(DC)) {
6441 // If we could not compute the declaration context, it's because the
6442 // declaration context is dependent but does not refer to a class,
6443 // class template, or class template partial specialization. Complain
6444 // and return early, to avoid the coming semantic disaster.
6446 diag::err_template_qualified_declarator_no_match)
6448 << D.getCXXScopeSpec().getRange();
6449 return nullptr;
6450 }
6451 bool IsDependentContext = DC->isDependentContext();
6452
6453 if (!IsDependentContext &&
6455 return nullptr;
6456
6457 // If a class is incomplete, do not parse entities inside it.
6460 diag::err_member_def_undefined_record)
6461 << Name << DC << D.getCXXScopeSpec().getRange();
6462 return nullptr;
6463 }
6464 if (!D.getDeclSpec().isFriendSpecified()) {
6465 TemplateIdAnnotation *TemplateId =
6467 ? D.getName().TemplateId
6468 : nullptr;
6470 D.getIdentifierLoc(), TemplateId,
6471 /*IsMemberSpecialization=*/false)) {
6472 if (DC->isRecord())
6473 return nullptr;
6474
6475 D.setInvalidType();
6476 }
6477 }
6478
6479 // Check whether we need to rebuild the type of the given
6480 // declaration in the current instantiation.
6481 if (EnteringContext && IsDependentContext &&
6482 TemplateParamLists.size() != 0) {
6483 ContextRAII SavedContext(*this, DC);
6484 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
6485 D.setInvalidType();
6486 }
6487 }
6488
6490 QualType R = TInfo->getType();
6491
6494 D.setInvalidType();
6495
6496 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6498
6499 // See if this is a redefinition of a variable in the same scope.
6500 if (!D.getCXXScopeSpec().isSet()) {
6501 bool IsLinkageLookup = false;
6502 bool CreateBuiltins = false;
6503
6504 // If the declaration we're planning to build will be a function
6505 // or object with linkage, then look for another declaration with
6506 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6507 //
6508 // If the declaration we're planning to build will be declared with
6509 // external linkage in the translation unit, create any builtin with
6510 // the same name.
6512 /* Do nothing*/;
6513 else if (CurContext->isFunctionOrMethod() &&
6515 R->isFunctionType())) {
6516 IsLinkageLookup = true;
6517 CreateBuiltins =
6518 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6519 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6521 CreateBuiltins = true;
6522
6523 if (IsLinkageLookup) {
6525 Previous.setRedeclarationKind(
6527 }
6528
6529 LookupName(Previous, S, CreateBuiltins);
6530 } else { // Something like "int foo::x;"
6532
6533 // C++ [dcl.meaning]p1:
6534 // When the declarator-id is qualified, the declaration shall refer to a
6535 // previously declared member of the class or namespace to which the
6536 // qualifier refers (or, in the case of a namespace, of an element of the
6537 // inline namespace set of that namespace (7.3.1)) or to a specialization
6538 // thereof; [...]
6539 //
6540 // Note that we already checked the context above, and that we do not have
6541 // enough information to make sure that Previous contains the declaration
6542 // we want to match. For example, given:
6543 //
6544 // class X {
6545 // void f();
6546 // void f(float);
6547 // };
6548 //
6549 // void X::f(int) { } // ill-formed
6550 //
6551 // In this case, Previous will point to the overload set
6552 // containing the two f's declared in X, but neither of them
6553 // matches.
6554
6556 }
6557
6558 if (auto *TPD = Previous.getAsSingle<NamedDecl>();
6559 TPD && TPD->isTemplateParameter()) {
6560 // Older versions of clang allowed the names of function/variable templates
6561 // to shadow the names of their template parameters. For the compatibility
6562 // purposes we detect such cases and issue a default-to-error warning that
6563 // can be disabled with -Wno-strict-primary-template-shadow.
6564 if (!D.isInvalidType()) {
6565 bool AllowForCompatibility = false;
6566 if (Scope *DeclParent = S->getDeclParent();
6567 Scope *TemplateParamParent = S->getTemplateParamParent()) {
6568 AllowForCompatibility = DeclParent->Contains(*TemplateParamParent) &&
6569 TemplateParamParent->isDeclScope(TPD);
6570 }
6572 AllowForCompatibility);
6573 }
6574
6575 // Just pretend that we didn't see the previous declaration.
6576 Previous.clear();
6577 }
6578
6579 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6580 // Forget that the previous declaration is the injected-class-name.
6581 Previous.clear();
6582
6583 // In C++, the previous declaration we find might be a tag type
6584 // (class or enum). In this case, the new declaration will hide the
6585 // tag type. Note that this applies to functions, function templates, and
6586 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6587 if (Previous.isSingleTagDecl() &&
6589 (TemplateParamLists.size() == 0 || R->isFunctionType()))
6590 Previous.clear();
6591
6592 // Check that there are no default arguments other than in the parameters
6593 // of a function declaration (C++ only).
6594 if (getLangOpts().CPlusPlus)
6596
6597 /// Get the innermost enclosing declaration scope.
6598 S = S->getDeclParent();
6599
6600 NamedDecl *New;
6601
6602 bool AddToScope = true;
6604 if (TemplateParamLists.size()) {
6605 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6606 return nullptr;
6607 }
6608
6609 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6610 } else if (R->isFunctionType()) {
6611 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6612 TemplateParamLists,
6613 AddToScope);
6614 } else {
6615 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6616 AddToScope);
6617 }
6618
6619 if (!New)
6620 return nullptr;
6621
6623
6624 // If this has an identifier and is not a function template specialization,
6625 // add it to the scope stack.
6626 if (New->getDeclName() && AddToScope)
6628
6629 if (OpenMP().isInOpenMPDeclareTargetContext())
6631
6632 return New;
6633}
6634
6635/// Helper method to turn variable array types into constant array
6636/// types in certain situations which would otherwise be errors (for
6637/// GCC compatibility).
6639 ASTContext &Context,
6640 bool &SizeIsNegative,
6641 llvm::APSInt &Oversized) {
6642 // This method tries to turn a variable array into a constant
6643 // array even when the size isn't an ICE. This is necessary
6644 // for compatibility with code that depends on gcc's buggy
6645 // constant expression folding, like struct {char x[(int)(char*)2];}
6646 SizeIsNegative = false;
6647 Oversized = 0;
6648
6649 if (T->isDependentType())
6650 return QualType();
6651
6653 const Type *Ty = Qs.strip(T);
6654
6655 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6656 QualType Pointee = PTy->getPointeeType();
6657 QualType FixedType =
6658 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6659 Oversized);
6660 if (FixedType.isNull()) return FixedType;
6661 FixedType = Context.getPointerType(FixedType);
6662 return Qs.apply(Context, FixedType);
6663 }
6664 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6665 QualType Inner = PTy->getInnerType();
6666 QualType FixedType =
6667 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6668 Oversized);
6669 if (FixedType.isNull()) return FixedType;
6670 FixedType = Context.getParenType(FixedType);
6671 return Qs.apply(Context, FixedType);
6672 }
6673
6674 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6675 if (!VLATy)
6676 return QualType();
6677
6678 QualType ElemTy = VLATy->getElementType();
6679 if (ElemTy->isVariablyModifiedType()) {
6680 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6681 SizeIsNegative, Oversized);
6682 if (ElemTy.isNull())
6683 return QualType();
6684 }
6685
6686 Expr::EvalResult Result;
6687 if (!VLATy->getSizeExpr() ||
6688 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6689 return QualType();
6690
6691 llvm::APSInt Res = Result.Val.getInt();
6692
6693 // Check whether the array size is negative.
6694 if (Res.isSigned() && Res.isNegative()) {
6695 SizeIsNegative = true;
6696 return QualType();
6697 }
6698
6699 // Check whether the array is too large to be addressed.
6700 unsigned ActiveSizeBits =
6701 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6702 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6703 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6704 : Res.getActiveBits();
6705 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6706 Oversized = Res;
6707 return QualType();
6708 }
6709
6710 QualType FoldedArrayType = Context.getConstantArrayType(
6711 ElemTy, Res, VLATy->getSizeExpr(), ArraySizeModifier::Normal, 0);
6712 return Qs.apply(Context, FoldedArrayType);
6713}
6714
6715static void
6717 SrcTL = SrcTL.getUnqualifiedLoc();
6718 DstTL = DstTL.getUnqualifiedLoc();
6719 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6720 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6721 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6722 DstPTL.getPointeeLoc());
6723 DstPTL.setStarLoc(SrcPTL.getStarLoc());
6724 return;
6725 }
6726 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6727 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6728 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6729 DstPTL.getInnerLoc());
6730 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6731 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6732 return;
6733 }
6734 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6735 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6736 TypeLoc SrcElemTL = SrcATL.getElementLoc();
6737 TypeLoc DstElemTL = DstATL.getElementLoc();
6738 if (VariableArrayTypeLoc SrcElemATL =
6739 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6740 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6741 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6742 } else {
6743 DstElemTL.initializeFullCopy(SrcElemTL);
6744 }
6745 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6746 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6747 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6748}
6749
6750/// Helper method to turn variable array types into constant array
6751/// types in certain situations which would otherwise be errors (for
6752/// GCC compatibility).
6753static TypeSourceInfo*
6755 ASTContext &Context,
6756 bool &SizeIsNegative,
6757 llvm::APSInt &Oversized) {
6758 QualType FixedTy
6759 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6760 SizeIsNegative, Oversized);
6761 if (FixedTy.isNull())
6762 return nullptr;
6763 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6765 FixedTInfo->getTypeLoc());
6766 return FixedTInfo;
6767}
6768
6771 unsigned FailedFoldDiagID) {
6772 bool SizeIsNegative;
6773 llvm::APSInt Oversized;
6775 TInfo, Context, SizeIsNegative, Oversized);
6776 if (FixedTInfo) {
6777 Diag(Loc, diag::ext_vla_folded_to_constant);
6778 TInfo = FixedTInfo;
6779 T = FixedTInfo->getType();
6780 return true;
6781 }
6782
6783 if (SizeIsNegative)
6784 Diag(Loc, diag::err_typecheck_negative_array_size);
6785 else if (Oversized.getBoolValue())
6786 Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6787 else if (FailedFoldDiagID)
6788 Diag(Loc, FailedFoldDiagID);
6789 return false;
6790}
6791
6792void
6794 if (!getLangOpts().CPlusPlus &&
6796 // Don't need to track declarations in the TU in C.
6797 return;
6798
6799 // Note that we have a locally-scoped external with this name.
6800 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6801}
6802
6804 // FIXME: We can have multiple results via __attribute__((overloadable)).
6805 auto Result = Context.getExternCContextDecl()->lookup(Name);
6806 return Result.empty() ? nullptr : *Result.begin();
6807}
6808
6810 // FIXME: We should probably indicate the identifier in question to avoid
6811 // confusion for constructs like "virtual int a(), b;"
6812 if (DS.isVirtualSpecified())
6814 diag::err_virtual_non_function);
6815
6816 if (DS.hasExplicitSpecifier())
6818 diag::err_explicit_non_function);
6819
6820 if (DS.isNoreturnSpecified())
6822 diag::err_noreturn_non_function);
6823}
6824
6825NamedDecl*
6828 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6829 if (D.getCXXScopeSpec().isSet()) {
6830 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6831 << D.getCXXScopeSpec().getRange();
6832 D.setInvalidType();
6833 // Pretend we didn't see the scope specifier.
6834 DC = CurContext;
6835 Previous.clear();
6836 }
6837
6839
6842 (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus)
6843 ? diag::warn_ms_inline_non_function
6844 : diag::err_inline_non_function)
6845 << getLangOpts().CPlusPlus17;
6847 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6848 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6849
6853 diag::err_deduction_guide_invalid_specifier)
6854 << "typedef";
6855 else
6856 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6857 << D.getName().getSourceRange();
6858 return nullptr;
6859 }
6860
6861 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6862 if (!NewTD) return nullptr;
6863
6864 // Handle attributes prior to checking for duplicates in MergeVarDecl
6865 ProcessDeclAttributes(S, NewTD, D);
6866
6868
6869 bool Redeclaration = D.isRedeclaration();
6872 return ND;
6873}
6874
6875void
6877 // C99 6.7.7p2: If a typedef name specifies a variably modified type
6878 // then it shall have block scope.
6879 // Note that variably modified types must be fixed before merging the decl so
6880 // that redeclarations will match.
6881 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6882 QualType T = TInfo->getType();
6883 if (T->isVariablyModifiedType()) {
6885
6886 if (S->getFnParent() == nullptr) {
6887 bool SizeIsNegative;
6888 llvm::APSInt Oversized;
6889 TypeSourceInfo *FixedTInfo =
6891 SizeIsNegative,
6892 Oversized);
6893 if (FixedTInfo) {
6894 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6895 NewTD->setTypeSourceInfo(FixedTInfo);
6896 } else {
6897 if (SizeIsNegative)
6898 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6899 else if (T->isVariableArrayType())
6900 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6901 else if (Oversized.getBoolValue())
6902 Diag(NewTD->getLocation(), diag::err_array_too_large)
6903 << toString(Oversized, 10);
6904 else
6905 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6906 NewTD->setInvalidDecl();
6907 }
6908 }
6909 }
6910}
6911
6912NamedDecl*
6915
6916 // Find the shadowed declaration before filtering for scope.
6917 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6918
6919 // Merge the decl with the existing one if appropriate. If the decl is
6920 // in an outer scope, it isn't the same thing.
6921 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6922 /*AllowInlineNamespace*/false);
6924 if (!Previous.empty()) {
6925 Redeclaration = true;
6926 MergeTypedefNameDecl(S, NewTD, Previous);
6927 } else {
6929 }
6930
6931 if (ShadowedDecl && !Redeclaration)
6932 CheckShadow(NewTD, ShadowedDecl, Previous);
6933
6934 // If this is the C FILE type, notify the AST context.
6935 if (IdentifierInfo *II = NewTD->getIdentifier())
6936 if (!NewTD->isInvalidDecl() &&
6938 switch (II->getNotableIdentifierID()) {
6939 case tok::NotableIdentifierKind::FILE:
6940 Context.setFILEDecl(NewTD);
6941 break;
6942 case tok::NotableIdentifierKind::jmp_buf:
6943 Context.setjmp_bufDecl(NewTD);
6944 break;
6945 case tok::NotableIdentifierKind::sigjmp_buf:
6946 Context.setsigjmp_bufDecl(NewTD);
6947 break;
6948 case tok::NotableIdentifierKind::ucontext_t:
6949 Context.setucontext_tDecl(NewTD);
6950 break;
6951 case tok::NotableIdentifierKind::float_t:
6952 case tok::NotableIdentifierKind::double_t:
6953 NewTD->addAttr(AvailableOnlyInDefaultEvalMethodAttr::Create(Context));
6954 break;
6955 default:
6956 break;
6957 }
6958 }
6959
6960 return NewTD;
6961}
6962
6963/// Determines whether the given declaration is an out-of-scope
6964/// previous declaration.
6965///
6966/// This routine should be invoked when name lookup has found a
6967/// previous declaration (PrevDecl) that is not in the scope where a
6968/// new declaration by the same name is being introduced. If the new
6969/// declaration occurs in a local scope, previous declarations with
6970/// linkage may still be considered previous declarations (C99
6971/// 6.2.2p4-5, C++ [basic.link]p6).
6972///
6973/// \param PrevDecl the previous declaration found by name
6974/// lookup
6975///
6976/// \param DC the context in which the new declaration is being
6977/// declared.
6978///
6979/// \returns true if PrevDecl is an out-of-scope previous declaration
6980/// for a new delcaration with the same name.
6981static bool
6983 ASTContext &Context) {
6984 if (!PrevDecl)
6985 return false;
6986
6987 if (!PrevDecl->hasLinkage())
6988 return false;
6989
6990 if (Context.getLangOpts().CPlusPlus) {
6991 // C++ [basic.link]p6:
6992 // If there is a visible declaration of an entity with linkage
6993 // having the same name and type, ignoring entities declared
6994 // outside the innermost enclosing namespace scope, the block
6995 // scope declaration declares that same entity and receives the
6996 // linkage of the previous declaration.
6997 DeclContext *OuterContext = DC->getRedeclContext();
6998 if (!OuterContext->isFunctionOrMethod())
6999 // This rule only applies to block-scope declarations.
7000 return false;
7001
7002 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
7003 if (PrevOuterContext->isRecord())
7004 // We found a member function: ignore it.
7005 return false;
7006
7007 // Find the innermost enclosing namespace for the new and
7008 // previous declarations.
7009 OuterContext = OuterContext->getEnclosingNamespaceContext();
7010 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
7011
7012 // The previous declaration is in a different namespace, so it
7013 // isn't the same function.
7014 if (!OuterContext->Equals(PrevOuterContext))
7015 return false;
7016 }
7017
7018 return true;
7019}
7020
7022 CXXScopeSpec &SS = D.getCXXScopeSpec();
7023 if (!SS.isSet()) return;
7025}
7026
7028 if (Decl->getType().hasAddressSpace())
7029 return;
7030 if (Decl->getType()->isDependentType())
7031 return;
7032 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
7033 QualType Type = Var->getType();
7034 if (Type->isSamplerT() || Type->isVoidType())
7035 return;
7037 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
7038 // __opencl_c_program_scope_global_variables feature, the address space
7039 // for a variable at program scope or a static or extern variable inside
7040 // a function are inferred to be __global.
7041 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
7042 Var->hasGlobalStorage())
7043 ImplAS = LangAS::opencl_global;
7044 // If the original type from a decayed type is an array type and that array
7045 // type has no address space yet, deduce it now.
7046 if (auto DT = dyn_cast<DecayedType>(Type)) {
7047 auto OrigTy = DT->getOriginalType();
7048 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
7049 // Add the address space to the original array type and then propagate
7050 // that to the element type through `getAsArrayType`.
7051 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
7052 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
7053 // Re-generate the decayed type.
7054 Type = Context.getDecayedType(OrigTy);
7055 }
7056 }
7057 Type = Context.getAddrSpaceQualType(Type, ImplAS);
7058 // Apply any qualifiers (including address space) from the array type to
7059 // the element type. This implements C99 6.7.3p8: "If the specification of
7060 // an array type includes any type qualifiers, the element type is so
7061 // qualified, not the array type."
7062 if (Type->isArrayType())
7063 Type = QualType(Context.getAsArrayType(Type), 0);
7064 Decl->setType(Type);
7065 }
7066}
7067
7068static void checkWeakAttr(Sema &S, NamedDecl &ND) {
7069 // 'weak' only applies to declarations with external linkage.
7070 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
7071 if (!ND.isExternallyVisible()) {
7072 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
7073 ND.dropAttr<WeakAttr>();
7074 }
7075 }
7076}
7077
7078static void checkWeakRefAttr(Sema &S, NamedDecl &ND) {
7079 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
7080 if (ND.isExternallyVisible()) {
7081 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
7082 ND.dropAttrs<WeakRefAttr, AliasAttr>();
7083 }
7084 }
7085}
7086
7087static void checkAliasAttr(Sema &S, NamedDecl &ND) {
7088 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
7089 if (VD->hasInit()) {
7090 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
7091 assert(VD->isThisDeclarationADefinition() &&
7092 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
7093 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
7094 VD->dropAttr<AliasAttr>();
7095 }
7096 }
7097 }
7098}
7099
7100static void checkSelectAnyAttr(Sema &S, NamedDecl &ND) {
7101 // 'selectany' only applies to externally visible variable declarations.
7102 // It does not apply to functions.
7103 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
7104 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
7105 S.Diag(Attr->getLocation(),
7106 diag::err_attribute_selectany_non_extern_data);
7107 ND.dropAttr<SelectAnyAttr>();
7108 }
7109 }
7110}
7111
7113 if (HybridPatchableAttr *Attr = ND.getAttr<HybridPatchableAttr>()) {
7114 if (!ND.isExternallyVisible())
7115 S.Diag(Attr->getLocation(),
7116 diag::warn_attribute_hybrid_patchable_non_extern);
7117 }
7118}
7119
7121 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
7122 auto *VD = dyn_cast<VarDecl>(&ND);
7123 bool IsAnonymousNS = false;
7124 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
7125 if (VD) {
7126 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
7127 while (NS && !IsAnonymousNS) {
7128 IsAnonymousNS = NS->isAnonymousNamespace();
7129 NS = dyn_cast<NamespaceDecl>(NS->getParent());
7130 }
7131 }
7132 // dll attributes require external linkage. Static locals may have external
7133 // linkage but still cannot be explicitly imported or exported.
7134 // In Microsoft mode, a variable defined in anonymous namespace must have
7135 // external linkage in order to be exported.
7136 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
7137 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
7138 (!AnonNSInMicrosoftMode &&
7139 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
7140 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
7141 << &ND << Attr;
7142 ND.setInvalidDecl();
7143 }
7144 }
7145}
7146
7148 // Check the attributes on the function type and function params, if any.
7149 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
7150 FD = FD->getMostRecentDecl();
7151 // Don't declare this variable in the second operand of the for-statement;
7152 // GCC miscompiles that by ending its lifetime before evaluating the
7153 // third operand. See gcc.gnu.org/PR86769.
7155 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
7156 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7157 TL = ATL.getModifiedLoc()) {
7158 // The [[lifetimebound]] attribute can be applied to the implicit object
7159 // parameter of a non-static member function (other than a ctor or dtor)
7160 // by applying it to the function type.
7161 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
7162 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
7163 int NoImplicitObjectError = -1;
7164 if (!MD)
7165 NoImplicitObjectError = 0;
7166 else if (MD->isStatic())
7167 NoImplicitObjectError = 1;
7168 else if (MD->isExplicitObjectMemberFunction())
7169 NoImplicitObjectError = 2;
7170 if (NoImplicitObjectError != -1) {
7171 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
7172 << NoImplicitObjectError << A->getRange();
7173 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
7174 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
7175 << isa<CXXDestructorDecl>(MD) << A->getRange();
7176 } else if (MD->getReturnType()->isVoidType()) {
7177 S.Diag(
7178 MD->getLocation(),
7179 diag::
7180 err_lifetimebound_implicit_object_parameter_void_return_type);
7181 }
7182 }
7183 }
7184
7185 for (unsigned int I = 0; I < FD->getNumParams(); ++I) {
7186 const ParmVarDecl *P = FD->getParamDecl(I);
7187
7188 // The [[lifetimebound]] attribute can be applied to a function parameter
7189 // only if the function returns a value.
7190 if (auto *A = P->getAttr<LifetimeBoundAttr>()) {
7191 if (!isa<CXXConstructorDecl>(FD) && FD->getReturnType()->isVoidType()) {
7192 S.Diag(A->getLocation(),
7193 diag::err_lifetimebound_parameter_void_return_type);
7194 }
7195 }
7196 }
7197 }
7198}
7199
7201 // Ensure that an auto decl is deduced otherwise the checks below might cache
7202 // the wrong linkage.
7203 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
7204
7205 checkWeakAttr(S, ND);
7206 checkWeakRefAttr(S, ND);
7207 checkAliasAttr(S, ND);
7208 checkSelectAnyAttr(S, ND);
7210 checkInheritableAttr(S, ND);
7212}
7213
7215 NamedDecl *NewDecl,
7216 bool IsSpecialization,
7217 bool IsDefinition) {
7218 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
7219 return;
7220
7221 bool IsTemplate = false;
7222 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
7223 OldDecl = OldTD->getTemplatedDecl();
7224 IsTemplate = true;
7225 if (!IsSpecialization)
7226 IsDefinition = false;
7227 }
7228 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
7229 NewDecl = NewTD->getTemplatedDecl();
7230 IsTemplate = true;
7231 }
7232
7233 if (!OldDecl || !NewDecl)
7234 return;
7235
7236 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
7237 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
7238 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
7239 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
7240
7241 // dllimport and dllexport are inheritable attributes so we have to exclude
7242 // inherited attribute instances.
7243 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
7244 (NewExportAttr && !NewExportAttr->isInherited());
7245
7246 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
7247 // the only exception being explicit specializations.
7248 // Implicitly generated declarations are also excluded for now because there
7249 // is no other way to switch these to use dllimport or dllexport.
7250 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
7251
7252 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
7253 // Allow with a warning for free functions and global variables.
7254 bool JustWarn = false;
7255 if (!OldDecl->isCXXClassMember()) {
7256 auto *VD = dyn_cast<VarDecl>(OldDecl);
7257 if (VD && !VD->getDescribedVarTemplate())
7258 JustWarn = true;
7259 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
7260 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
7261 JustWarn = true;
7262 }
7263
7264 // We cannot change a declaration that's been used because IR has already
7265 // been emitted. Dllimported functions will still work though (modulo
7266 // address equality) as they can use the thunk.
7267 if (OldDecl->isUsed())
7268 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
7269 JustWarn = false;
7270
7271 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7272 : diag::err_attribute_dll_redeclaration;
7273 S.Diag(NewDecl->getLocation(), DiagID)
7274 << NewDecl
7275 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7276 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7277 if (!JustWarn) {
7278 NewDecl->setInvalidDecl();
7279 return;
7280 }
7281 }
7282
7283 // A redeclaration is not allowed to drop a dllimport attribute, the only
7284 // exceptions being inline function definitions (except for function
7285 // templates), local extern declarations, qualified friend declarations or
7286 // special MSVC extension: in the last case, the declaration is treated as if
7287 // it were marked dllexport.
7288 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7289 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7290 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
7291 // Ignore static data because out-of-line definitions are diagnosed
7292 // separately.
7293 IsStaticDataMember = VD->isStaticDataMember();
7294 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7296 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
7297 IsInline = FD->isInlined();
7298 IsQualifiedFriend = FD->getQualifier() &&
7299 FD->getFriendObjectKind() == Decl::FOK_Declared;
7300 }
7301
7302 if (OldImportAttr && !HasNewAttr &&
7303 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7304 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7305 if (IsMicrosoftABI && IsDefinition) {
7306 if (IsSpecialization) {
7307 S.Diag(
7308 NewDecl->getLocation(),
7309 diag::err_attribute_dllimport_function_specialization_definition);
7310 S.Diag(OldImportAttr->getLocation(), diag::note_attribute);
7311 NewDecl->dropAttr<DLLImportAttr>();
7312 } else {
7313 S.Diag(NewDecl->getLocation(),
7314 diag::warn_redeclaration_without_import_attribute)
7315 << NewDecl;
7316 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7317 NewDecl->dropAttr<DLLImportAttr>();
7318 NewDecl->addAttr(DLLExportAttr::CreateImplicit(
7319 S.Context, NewImportAttr->getRange()));
7320 }
7321 } else if (IsMicrosoftABI && IsSpecialization) {
7322 assert(!IsDefinition);
7323 // MSVC allows this. Keep the inherited attribute.
7324 } else {
7325 S.Diag(NewDecl->getLocation(),
7326 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7327 << NewDecl << OldImportAttr;
7328 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7329 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
7330 OldDecl->dropAttr<DLLImportAttr>();
7331 NewDecl->dropAttr<DLLImportAttr>();
7332 }
7333 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7334 // In MinGW, seeing a function declared inline drops the dllimport
7335 // attribute.
7336 OldDecl->dropAttr<DLLImportAttr>();
7337 NewDecl->dropAttr<DLLImportAttr>();
7338 S.Diag(NewDecl->getLocation(),
7339 diag::warn_dllimport_dropped_from_inline_function)
7340 << NewDecl << OldImportAttr;
7341 }
7342
7343 // A specialization of a class template member function is processed here
7344 // since it's a redeclaration. If the parent class is dllexport, the
7345 // specialization inherits that attribute. This doesn't happen automatically
7346 // since the parent class isn't instantiated until later.
7347 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
7348 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7349 !NewImportAttr && !NewExportAttr) {
7350 if (const DLLExportAttr *ParentExportAttr =
7351 MD->getParent()->getAttr<DLLExportAttr>()) {
7352 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
7353 NewAttr->setInherited(true);
7354 NewDecl->addAttr(NewAttr);
7355 }
7356 }
7357 }
7358}
7359
7360/// Given that we are within the definition of the given function,
7361/// will that definition behave like C99's 'inline', where the
7362/// definition is discarded except for optimization purposes?
7364 // Try to avoid calling GetGVALinkageForFunction.
7365
7366 // All cases of this require the 'inline' keyword.
7367 if (!FD->isInlined()) return false;
7368
7369 // This is only possible in C++ with the gnu_inline attribute.
7370 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7371 return false;
7372
7373 // Okay, go ahead and call the relatively-more-expensive function.
7375}
7376
7377/// Determine whether a variable is extern "C" prior to attaching
7378/// an initializer. We can't just call isExternC() here, because that
7379/// will also compute and cache whether the declaration is externally
7380/// visible, which might change when we attach the initializer.
7381///
7382/// This can only be used if the declaration is known to not be a
7383/// redeclaration of an internal linkage declaration.
7384///
7385/// For instance:
7386///
7387/// auto x = []{};
7388///
7389/// Attaching the initializer here makes this declaration not externally
7390/// visible, because its type has internal linkage.
7391///
7392/// FIXME: This is a hack.
7393template<typename T>
7394static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7395 if (S.getLangOpts().CPlusPlus) {
7396 // In C++, the overloadable attribute negates the effects of extern "C".
7397 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7398 return false;
7399
7400 // So do CUDA's host/device attributes.
7401 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7402 D->template hasAttr<CUDAHostAttr>()))
7403 return false;
7404 }
7405 return D->isExternC();
7406}
7407
7408static bool shouldConsiderLinkage(const VarDecl *VD) {
7409 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7412 return VD->hasExternalStorage();
7413 if (DC->isFileContext())
7414 return true;
7415 if (DC->isRecord())
7416 return false;
7417 if (DC->getDeclKind() == Decl::HLSLBuffer)
7418 return false;
7419
7421 return false;
7422 llvm_unreachable("Unexpected context");
7423}
7424
7425static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7426 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7427 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7429 return true;
7430 if (DC->isRecord())
7431 return false;
7432 llvm_unreachable("Unexpected context");
7433}
7434
7435static bool hasParsedAttr(Scope *S, const Declarator &PD,
7436 ParsedAttr::Kind Kind) {
7437 // Check decl attributes on the DeclSpec.
7438 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
7439 return true;
7440
7441 // Walk the declarator structure, checking decl attributes that were in a type
7442 // position to the decl itself.
7443 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7444 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
7445 return true;
7446 }
7447
7448 // Finally, check attributes on the decl itself.
7449 return PD.getAttributes().hasAttribute(Kind) ||
7451}
7452
7454 if (!DC->isFunctionOrMethod())
7455 return false;
7456
7457 // If this is a local extern function or variable declared within a function
7458 // template, don't add it into the enclosing namespace scope until it is
7459 // instantiated; it might have a dependent type right now.
7460 if (DC->isDependentContext())
7461 return true;
7462
7463 // C++11 [basic.link]p7:
7464 // When a block scope declaration of an entity with linkage is not found to
7465 // refer to some other declaration, then that entity is a member of the
7466 // innermost enclosing namespace.
7467 //
7468 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7469 // semantically-enclosing namespace, not a lexically-enclosing one.
7470 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
7471 DC = DC->getParent();
7472 return true;
7473}
7474
7475/// Returns true if given declaration has external C language linkage.
7476static bool isDeclExternC(const Decl *D) {
7477 if (const auto *FD = dyn_cast<FunctionDecl>(D))
7478 return FD->isExternC();
7479 if (const auto *VD = dyn_cast<VarDecl>(D))
7480 return VD->isExternC();
7481
7482 llvm_unreachable("Unknown type of decl!");
7483}
7484
7485/// Returns true if there hasn't been any invalid type diagnosed.
7486static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7487 DeclContext *DC = NewVD->getDeclContext();
7488 QualType R = NewVD->getType();
7489
7490 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7491 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7492 // argument.
7493 if (R->isImageType() || R->isPipeType()) {
7494 Se.Diag(NewVD->getLocation(),
7495 diag::err_opencl_type_can_only_be_used_as_function_parameter)
7496 << R;
7497 NewVD->setInvalidDecl();
7498 return false;
7499 }
7500
7501 // OpenCL v1.2 s6.9.r:
7502 // The event type cannot be used to declare a program scope variable.
7503 // OpenCL v2.0 s6.9.q:
7504 // The clk_event_t and reserve_id_t types cannot be declared in program
7505 // scope.
7506 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7507 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7508 Se.Diag(NewVD->getLocation(),
7509 diag::err_invalid_type_for_program_scope_var)
7510 << R;
7511 NewVD->setInvalidDecl();
7512 return false;
7513 }
7514 }
7515
7516 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7517 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7518 Se.getLangOpts())) {
7519 QualType NR = R.getCanonicalType();
7520 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7521 NR->isReferenceType()) {
7524 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7525 << NR->isReferenceType();
7526 NewVD->setInvalidDecl();
7527 return false;
7528 }
7529 NR = NR->getPointeeType();
7530 }
7531 }
7532
7533 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7534 Se.getLangOpts())) {
7535 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7536 // half array type (unless the cl_khr_fp16 extension is enabled).
7537 if (Se.Context.getBaseElementType(R)->isHalfType()) {
7538 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7539 NewVD->setInvalidDecl();
7540 return false;
7541 }
7542 }
7543
7544 // OpenCL v1.2 s6.9.r:
7545 // The event type cannot be used with the __local, __constant and __global
7546 // address space qualifiers.
7547 if (R->isEventT()) {
7549 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7550 NewVD->setInvalidDecl();
7551 return false;
7552 }
7553 }
7554
7555 if (R->isSamplerT()) {
7556 // OpenCL v1.2 s6.9.b p4:
7557 // The sampler type cannot be used with the __local and __global address
7558 // space qualifiers.
7561 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7562 NewVD->setInvalidDecl();
7563 }
7564
7565 // OpenCL v1.2 s6.12.14.1:
7566 // A global sampler must be declared with either the constant address
7567 // space qualifier or with the const qualifier.
7568 if (DC->isTranslationUnit() &&
7570 R.isConstQualified())) {
7571 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7572 NewVD->setInvalidDecl();
7573 }
7574 if (NewVD->isInvalidDecl())
7575 return false;
7576 }
7577
7578 return true;
7579}
7580
7581template <typename AttrTy>
7582static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7583 const TypedefNameDecl *TND = TT->getDecl();
7584 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7585 AttrTy *Clone = Attribute->clone(S.Context);
7586 Clone->setInherited(true);
7587 D->addAttr(Clone);
7588 }
7589}
7590
7591// This function emits warning and a corresponding note based on the
7592// ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7593// declarations of an annotated type must be const qualified.
7595 QualType VarType = VD->getType().getCanonicalType();
7596
7597 // Ignore local declarations (for now) and those with const qualification.
7598 // TODO: Local variables should not be allowed if their type declaration has
7599 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7600 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7601 return;
7602
7603 if (VarType->isArrayType()) {
7604 // Retrieve element type for array declarations.
7605 VarType = S.getASTContext().getBaseElementType(VarType);
7606 }
7607
7608 const RecordDecl *RD = VarType->getAsRecordDecl();
7609
7610 // Check if the record declaration is present and if it has any attributes.
7611 if (RD == nullptr)
7612 return;
7613
7614 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7615 S.Diag(VD->getLocation(), diag::warn_var_decl_not_read_only) << RD;
7616 S.Diag(ConstDecl->getLocation(), diag::note_enforce_read_only_placement);
7617 return;
7618 }
7619}
7620
7621// Checks if VD is declared at global scope or with C language linkage.
7622static bool isMainVar(DeclarationName Name, VarDecl *VD) {
7623 return Name.getAsIdentifierInfo() &&
7624 Name.getAsIdentifierInfo()->isStr("main") &&
7625 !VD->getDescribedVarTemplate() &&
7626 (VD->getDeclContext()->getRedeclContext()->isTranslationUnit() ||
7627 VD->isExternC());
7628}
7629
7631 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7632 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7633 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7634 QualType R = TInfo->getType();
7636
7638 bool IsPlaceholderVariable = false;
7639
7640 if (D.isDecompositionDeclarator()) {
7641 // Take the name of the first declarator as our name for diagnostic
7642 // purposes.
7643 auto &Decomp = D.getDecompositionDeclarator();
7644 if (!Decomp.bindings().empty()) {
7645 II = Decomp.bindings()[0].Name;
7646 Name = II;
7647 }
7648 } else if (!II) {
7649 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7650 return nullptr;
7651 }
7652
7653
7656 if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) &&
7657 SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) {
7658
7659 IsPlaceholderVariable = true;
7660
7661 if (!Previous.empty()) {
7662 NamedDecl *PrevDecl = *Previous.begin();
7663 bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals(
7664 DC->getRedeclContext());
7665 if (SameDC && isDeclInScope(PrevDecl, CurContext, S, false)) {
7666 IsPlaceholderVariable = !isa<ParmVarDecl>(PrevDecl);
7667 if (IsPlaceholderVariable)
7669 }
7670 }
7671 }
7672
7673 // dllimport globals without explicit storage class are treated as extern. We
7674 // have to change the storage class this early to get the right DeclContext.
7675 if (SC == SC_None && !DC->isRecord() &&
7676 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7677 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7678 SC = SC_Extern;
7679
7680 DeclContext *OriginalDC = DC;
7681 bool IsLocalExternDecl = SC == SC_Extern &&
7683
7684 if (SCSpec == DeclSpec::SCS_mutable) {
7685 // mutable can only appear on non-static class members, so it's always
7686 // an error here
7687 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7688 D.setInvalidType();
7689 SC = SC_None;
7690 }
7691
7692 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7693 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7695 // In C++11, the 'register' storage class specifier is deprecated.
7696 // Suppress the warning in system macros, it's used in macros in some
7697 // popular C system headers, such as in glibc's htonl() macro.
7699 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7700 : diag::warn_deprecated_register)
7702 }
7703
7705
7706 if (!DC->isRecord() && S->getFnParent() == nullptr) {
7707 // C99 6.9p2: The storage-class specifiers auto and register shall not
7708 // appear in the declaration specifiers in an external declaration.
7709 // Global Register+Asm is a GNU extension we support.
7710 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7711 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7712 D.setInvalidType();
7713 }
7714 }
7715
7716 // If this variable has a VLA type and an initializer, try to
7717 // fold to a constant-sized type. This is otherwise invalid.
7718 if (D.hasInitializer() && R->isVariableArrayType())
7720 /*DiagID=*/0);
7721
7722 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) {
7723 const AutoType *AT = TL.getTypePtr();
7724 CheckConstrainedAuto(AT, TL.getConceptNameLoc());
7725 }
7726
7727 bool IsMemberSpecialization = false;
7728 bool IsVariableTemplateSpecialization = false;
7729 bool IsPartialSpecialization = false;
7730 bool IsVariableTemplate = false;
7731 VarDecl *NewVD = nullptr;
7732 VarTemplateDecl *NewTemplate = nullptr;
7733 TemplateParameterList *TemplateParams = nullptr;
7734 if (!getLangOpts().CPlusPlus) {
7736 II, R, TInfo, SC);
7737
7738 if (R->getContainedDeducedType())
7739 ParsingInitForAutoVars.insert(NewVD);
7740
7741 if (D.isInvalidType())
7742 NewVD->setInvalidDecl();
7743
7745 NewVD->hasLocalStorage())
7746 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7748 } else {
7749 bool Invalid = false;
7750 // Match up the template parameter lists with the scope specifier, then
7751 // determine whether we have a template or a template specialization.
7754 D.getCXXScopeSpec(),
7756 ? D.getName().TemplateId
7757 : nullptr,
7758 TemplateParamLists,
7759 /*never a friend*/ false, IsMemberSpecialization, Invalid);
7760
7761 if (TemplateParams) {
7762 if (DC->isDependentContext()) {
7763 ContextRAII SavedContext(*this, DC);
7765 Invalid = true;
7766 }
7767
7768 if (!TemplateParams->size() &&
7770 // There is an extraneous 'template<>' for this variable. Complain
7771 // about it, but allow the declaration of the variable.
7772 Diag(TemplateParams->getTemplateLoc(),
7773 diag::err_template_variable_noparams)
7774 << II
7775 << SourceRange(TemplateParams->getTemplateLoc(),
7776 TemplateParams->getRAngleLoc());
7777 TemplateParams = nullptr;
7778 } else {
7779 // Check that we can declare a template here.
7780 if (CheckTemplateDeclScope(S, TemplateParams))
7781 return nullptr;
7782
7784 // This is an explicit specialization or a partial specialization.
7785 IsVariableTemplateSpecialization = true;
7786 IsPartialSpecialization = TemplateParams->size() > 0;
7787 } else { // if (TemplateParams->size() > 0)
7788 // This is a template declaration.
7789 IsVariableTemplate = true;
7790
7791 // Only C++1y supports variable templates (N3651).
7792 DiagCompat(D.getIdentifierLoc(), diag_compat::variable_template);
7793 }
7794 }
7795 } else {
7796 // Check that we can declare a member specialization here.
7797 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7798 CheckTemplateDeclScope(S, TemplateParamLists.back()))
7799 return nullptr;
7800 assert((Invalid ||
7802 "should have a 'template<>' for this decl");
7803 }
7804
7805 bool IsExplicitSpecialization =
7806 IsVariableTemplateSpecialization && !IsPartialSpecialization;
7807
7808 // C++ [temp.expl.spec]p2:
7809 // The declaration in an explicit-specialization shall not be an
7810 // export-declaration. An explicit specialization shall not use a
7811 // storage-class-specifier other than thread_local.
7812 //
7813 // We use the storage-class-specifier from DeclSpec because we may have
7814 // added implicit 'extern' for declarations with __declspec(dllimport)!
7815 if (SCSpec != DeclSpec::SCS_unspecified &&
7816 (IsExplicitSpecialization || IsMemberSpecialization)) {
7818 diag::ext_explicit_specialization_storage_class)
7820 }
7821
7822 if (CurContext->isRecord()) {
7823 if (SC == SC_Static) {
7824 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7825 // Walk up the enclosing DeclContexts to check for any that are
7826 // incompatible with static data members.
7827 const DeclContext *FunctionOrMethod = nullptr;
7828 const CXXRecordDecl *AnonStruct = nullptr;
7829 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7830 if (Ctxt->isFunctionOrMethod()) {
7831 FunctionOrMethod = Ctxt;
7832 break;
7833 }
7834 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7835 if (ParentDecl && !ParentDecl->getDeclName()) {
7836 AnonStruct = ParentDecl;
7837 break;
7838 }
7839 }
7840 if (FunctionOrMethod) {
7841 // C++ [class.static.data]p5: A local class shall not have static
7842 // data members.
7844 diag::err_static_data_member_not_allowed_in_local_class)
7845 << Name << RD->getDeclName() << RD->getTagKind();
7846 } else if (AnonStruct) {
7847 // C++ [class.static.data]p4: Unnamed classes and classes contained
7848 // directly or indirectly within unnamed classes shall not contain
7849 // static data members.
7851 diag::err_static_data_member_not_allowed_in_anon_struct)
7852 << Name << AnonStruct->getTagKind();
7853 Invalid = true;
7854 } else if (RD->isUnion()) {
7855 // C++98 [class.union]p1: If a union contains a static data member,
7856 // the program is ill-formed. C++11 drops this restriction.
7858 diag_compat::static_data_member_in_union)
7859 << Name;
7860 }
7861 }
7862 } else if (IsVariableTemplate || IsPartialSpecialization) {
7863 // There is no such thing as a member field template.
7864 Diag(D.getIdentifierLoc(), diag::err_template_member)
7865 << II << TemplateParams->getSourceRange();
7866 // Recover by pretending this is a static data member template.
7867 SC = SC_Static;
7868 }
7869 } else if (DC->isRecord()) {
7870 // This is an out-of-line definition of a static data member.
7871 switch (SC) {
7872 case SC_None:
7873 break;
7874 case SC_Static:
7876 diag::err_static_out_of_line)
7879 break;
7880 case SC_Auto:
7881 case SC_Register:
7882 case SC_Extern:
7883 // [dcl.stc] p2: The auto or register specifiers shall be applied only
7884 // to names of variables declared in a block or to function parameters.
7885 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7886 // of class members
7887
7889 diag::err_storage_class_for_static_member)
7892 break;
7893 case SC_PrivateExtern:
7894 llvm_unreachable("C storage class in c++!");
7895 }
7896 }
7897
7898 if (IsVariableTemplateSpecialization) {
7899 SourceLocation TemplateKWLoc =
7900 TemplateParamLists.size() > 0
7901 ? TemplateParamLists[0]->getTemplateLoc()
7902 : SourceLocation();
7904 S, D, TInfo, Previous, TemplateKWLoc, TemplateParams, SC,
7906 if (Res.isInvalid())
7907 return nullptr;
7908 NewVD = cast<VarDecl>(Res.get());
7909 AddToScope = false;
7910 } else if (D.isDecompositionDeclarator()) {
7912 D.getIdentifierLoc(), R, TInfo, SC,
7913 Bindings);
7914 } else
7915 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7916 D.getIdentifierLoc(), II, R, TInfo, SC);
7917
7918 // If this is supposed to be a variable template, create it as such.
7919 if (IsVariableTemplate) {
7920 NewTemplate =
7922 TemplateParams, NewVD);
7923 NewVD->setDescribedVarTemplate(NewTemplate);
7924 }
7925
7926 // If this decl has an auto type in need of deduction, make a note of the
7927 // Decl so we can diagnose uses of it in its own initializer.
7928 if (R->getContainedDeducedType())
7929 ParsingInitForAutoVars.insert(NewVD);
7930
7931 if (D.isInvalidType() || Invalid) {
7932 NewVD->setInvalidDecl();
7933 if (NewTemplate)
7934 NewTemplate->setInvalidDecl();
7935 }
7936
7937 SetNestedNameSpecifier(*this, NewVD, D);
7938
7939 // If we have any template parameter lists that don't directly belong to
7940 // the variable (matching the scope specifier), store them.
7941 // An explicit variable template specialization does not own any template
7942 // parameter lists.
7943 unsigned VDTemplateParamLists =
7944 (TemplateParams && !IsExplicitSpecialization) ? 1 : 0;
7945 if (TemplateParamLists.size() > VDTemplateParamLists)
7947 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7948 }
7949
7950 if (D.getDeclSpec().isInlineSpecified()) {
7951 if (!getLangOpts().CPlusPlus) {
7952 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7953 << 0;
7954 } else if (CurContext->isFunctionOrMethod()) {
7955 // 'inline' is not allowed on block scope variable declaration.
7957 diag::err_inline_declaration_block_scope) << Name
7959 } else {
7961 getLangOpts().CPlusPlus17 ? diag::compat_cxx17_inline_variable
7962 : diag::compat_pre_cxx17_inline_variable);
7963 NewVD->setInlineSpecified();
7964 }
7965 }
7966
7967 // Set the lexical context. If the declarator has a C++ scope specifier, the
7968 // lexical context will be different from the semantic context.
7970 if (NewTemplate)
7971 NewTemplate->setLexicalDeclContext(CurContext);
7972
7973 if (IsLocalExternDecl) {
7975 for (auto *B : Bindings)
7976 B->setLocalExternDecl();
7977 else
7978 NewVD->setLocalExternDecl();
7979 }
7980
7981 bool EmitTLSUnsupportedError = false;
7983 // C++11 [dcl.stc]p4:
7984 // When thread_local is applied to a variable of block scope the
7985 // storage-class-specifier static is implied if it does not appear
7986 // explicitly.
7987 // Core issue: 'static' is not implied if the variable is declared
7988 // 'extern'.
7989 if (NewVD->hasLocalStorage() &&
7990 (SCSpec != DeclSpec::SCS_unspecified ||
7992 !DC->isFunctionOrMethod()))
7994 diag::err_thread_non_global)
7996 else if (!Context.getTargetInfo().isTLSSupported()) {
7997 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
7998 // Postpone error emission until we've collected attributes required to
7999 // figure out whether it's a host or device variable and whether the
8000 // error should be ignored.
8001 EmitTLSUnsupportedError = true;
8002 // We still need to mark the variable as TLS so it shows up in AST with
8003 // proper storage class for other tools to use even if we're not going
8004 // to emit any code for it.
8005 NewVD->setTSCSpec(TSCS);
8006 } else
8008 diag::err_thread_unsupported);
8009 } else
8010 NewVD->setTSCSpec(TSCS);
8011 }
8012
8013 switch (D.getDeclSpec().getConstexprSpecifier()) {
8015 break;
8016
8019 diag::err_constexpr_wrong_decl_kind)
8020 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
8021 [[fallthrough]];
8022
8024 NewVD->setConstexpr(true);
8025 // C++1z [dcl.spec.constexpr]p1:
8026 // A static data member declared with the constexpr specifier is
8027 // implicitly an inline variable.
8028 if (NewVD->isStaticDataMember() &&
8030 Context.getTargetInfo().getCXXABI().isMicrosoft()))
8031 NewVD->setImplicitlyInline();
8032 break;
8033
8035 if (!NewVD->hasGlobalStorage())
8037 diag::err_constinit_local_variable);
8038 else
8039 NewVD->addAttr(
8040 ConstInitAttr::Create(Context, D.getDeclSpec().getConstexprSpecLoc(),
8041 ConstInitAttr::Keyword_constinit));
8042 break;
8043 }
8044
8045 // C99 6.7.4p3
8046 // An inline definition of a function with external linkage shall
8047 // not contain a definition of a modifiable object with static or
8048 // thread storage duration...
8049 // We only apply this when the function is required to be defined
8050 // elsewhere, i.e. when the function is not 'extern inline'. Note
8051 // that a local variable with thread storage duration still has to
8052 // be marked 'static'. Also note that it's possible to get these
8053 // semantics in C++ using __attribute__((gnu_inline)).
8054 if (SC == SC_Static && S->getFnParent() != nullptr &&
8055 !NewVD->getType().isConstQualified()) {
8057 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
8059 diag::warn_static_local_in_extern_inline);
8061 }
8062 }
8063
8065 if (IsVariableTemplateSpecialization)
8066 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
8067 << (IsPartialSpecialization ? 1 : 0)
8070 else if (IsMemberSpecialization)
8071 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
8072 << 2
8074 else if (NewVD->hasLocalStorage())
8075 Diag(NewVD->getLocation(), diag::err_module_private_local)
8076 << 0 << NewVD
8080 else {
8081 NewVD->setModulePrivate();
8082 if (NewTemplate)
8083 NewTemplate->setModulePrivate();
8084 for (auto *B : Bindings)
8085 B->setModulePrivate();
8086 }
8087 }
8088
8089 if (getLangOpts().OpenCL) {
8091
8093 if (TSC != TSCS_unspecified) {
8095 diag::err_opencl_unknown_type_specifier)
8097 << DeclSpec::getSpecifierName(TSC) << 1;
8098 NewVD->setInvalidDecl();
8099 }
8100 }
8101
8102 // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
8103 // address space if the table has local storage (semantic checks elsewhere
8104 // will produce an error anyway).
8105 if (const auto *ATy = dyn_cast<ArrayType>(NewVD->getType())) {
8106 if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&
8107 !NewVD->hasLocalStorage()) {
8108 QualType Type = Context.getAddrSpaceQualType(
8109 NewVD->getType(), Context.getLangASForBuiltinAddressSpace(1));
8110 NewVD->setType(Type);
8111 }
8112 }
8113
8114 // Handle attributes prior to checking for duplicates in MergeVarDecl
8115 ProcessDeclAttributes(S, NewVD, D);
8116
8117 if (getLangOpts().HLSL)
8119
8120 if (getLangOpts().OpenACC)
8122
8123 // FIXME: This is probably the wrong location to be doing this and we should
8124 // probably be doing this for more attributes (especially for function
8125 // pointer attributes such as format, warn_unused_result, etc.). Ideally
8126 // the code to copy attributes would be generated by TableGen.
8127 if (R->isFunctionPointerType())
8128 if (const auto *TT = R->getAs<TypedefType>())
8130
8131 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8132 if (EmitTLSUnsupportedError &&
8134 (getLangOpts().OpenMPIsTargetDevice &&
8135 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
8137 diag::err_thread_unsupported);
8138
8139 if (EmitTLSUnsupportedError &&
8140 (LangOpts.SYCLIsDevice ||
8141 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)))
8142 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
8143 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
8144 // storage [duration]."
8145 if (SC == SC_None && S->getFnParent() != nullptr &&
8146 (NewVD->hasAttr<CUDASharedAttr>() ||
8147 NewVD->hasAttr<CUDAConstantAttr>())) {
8148 NewVD->setStorageClass(SC_Static);
8149 }
8150 }
8151
8152 // Ensure that dllimport globals without explicit storage class are treated as
8153 // extern. The storage class is set above using parsed attributes. Now we can
8154 // check the VarDecl itself.
8155 assert(!NewVD->hasAttr<DLLImportAttr>() ||
8156 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
8157 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
8158
8159 // In auto-retain/release, infer strong retension for variables of
8160 // retainable type.
8161 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewVD))
8162 NewVD->setInvalidDecl();
8163
8164 // Handle GNU asm-label extension (encoded as an attribute).
8165 if (Expr *E = D.getAsmLabel()) {
8166 // The parser guarantees this is a string.
8168 StringRef Label = SE->getString();
8169 if (S->getFnParent() != nullptr) {
8170 switch (SC) {
8171 case SC_None:
8172 case SC_Auto:
8173 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
8174 break;
8175 case SC_Register:
8176 // Local Named register
8177 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
8179 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
8180 break;
8181 case SC_Static:
8182 case SC_Extern:
8183 case SC_PrivateExtern:
8184 break;
8185 }
8186 } else if (SC == SC_Register) {
8187 // Global Named register
8188 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
8189 const auto &TI = Context.getTargetInfo();
8190 bool HasSizeMismatch;
8191
8192 if (!TI.isValidGCCRegisterName(Label))
8193 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
8194 else if (!TI.validateGlobalRegisterVariable(Label,
8195 Context.getTypeSize(R),
8196 HasSizeMismatch))
8197 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
8198 else if (HasSizeMismatch)
8199 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
8200 }
8201
8202 if (!R->isIntegralType(Context) && !R->isPointerType()) {
8203 Diag(TInfo->getTypeLoc().getBeginLoc(),
8204 diag::err_asm_unsupported_register_type)
8205 << TInfo->getTypeLoc().getSourceRange();
8206 NewVD->setInvalidDecl(true);
8207 }
8208 }
8209
8210 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, SE->getStrTokenLoc(0)));
8211 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8212 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8214 if (I != ExtnameUndeclaredIdentifiers.end()) {
8215 if (isDeclExternC(NewVD)) {
8216 NewVD->addAttr(I->second);
8218 } else
8219 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
8220 << /*Variable*/1 << NewVD;
8221 }
8222 }
8223
8224 // Find the shadowed declaration before filtering for scope.
8225 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
8227 : nullptr;
8228
8229 // Don't consider existing declarations that are in a different
8230 // scope and are out-of-semantic-context declarations (if the new
8231 // declaration has linkage).
8234 IsMemberSpecialization ||
8235 IsVariableTemplateSpecialization);
8236
8237 // Check whether the previous declaration is in the same block scope. This
8238 // affects whether we merge types with it, per C++11 [dcl.array]p3.
8239 if (getLangOpts().CPlusPlus &&
8240 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
8242 Previous.isSingleResult() && !Previous.isShadowed() &&
8243 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
8244
8245 if (!getLangOpts().CPlusPlus) {
8247 } else {
8248 // If this is an explicit specialization of a static data member, check it.
8249 if (IsMemberSpecialization && !IsVariableTemplate &&
8250 !IsVariableTemplateSpecialization && !NewVD->isInvalidDecl() &&
8252 NewVD->setInvalidDecl();
8253
8254 // Merge the decl with the existing one if appropriate.
8255 if (!Previous.empty()) {
8256 if (Previous.isSingleResult() &&
8257 isa<FieldDecl>(Previous.getFoundDecl()) &&
8258 D.getCXXScopeSpec().isSet()) {
8259 // The user tried to define a non-static data member
8260 // out-of-line (C++ [dcl.meaning]p1).
8261 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
8262 << D.getCXXScopeSpec().getRange();
8263 Previous.clear();
8264 NewVD->setInvalidDecl();
8265 }
8266 } else if (D.getCXXScopeSpec().isSet() &&
8267 !IsVariableTemplateSpecialization) {
8268 // No previous declaration in the qualifying scope.
8269 Diag(D.getIdentifierLoc(), diag::err_no_member)
8270 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
8271 << D.getCXXScopeSpec().getRange();
8272 NewVD->setInvalidDecl();
8273 }
8274
8275 if (!IsPlaceholderVariable)
8277
8278 // CheckVariableDeclaration will set NewVD as invalid if something is in
8279 // error like WebAssembly tables being declared as arrays with a non-zero
8280 // size, but then parsing continues and emits further errors on that line.
8281 // To avoid that we check here if it happened and return nullptr.
8282 if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())
8283 return nullptr;
8284
8285 if (NewTemplate) {
8286 VarTemplateDecl *PrevVarTemplate =
8287 NewVD->getPreviousDecl()
8289 : nullptr;
8290
8291 // Check the template parameter list of this declaration, possibly
8292 // merging in the template parameter list from the previous variable
8293 // template declaration.
8295 TemplateParams,
8296 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8297 : nullptr,
8298 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8299 DC->isDependentContext())
8301 : TPC_Other))
8302 NewVD->setInvalidDecl();
8303
8304 // If we are providing an explicit specialization of a static variable
8305 // template, make a note of that.
8306 if (PrevVarTemplate &&
8307 PrevVarTemplate->getInstantiatedFromMemberTemplate())
8308 PrevVarTemplate->setMemberSpecialization();
8309 }
8310 }
8311
8312 // Diagnose shadowed variables iff this isn't a redeclaration.
8313 if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration())
8314 CheckShadow(NewVD, ShadowedDecl, Previous);
8315
8316 ProcessPragmaWeak(S, NewVD);
8317
8318 // If this is the first declaration of an extern C variable, update
8319 // the map of such variables.
8320 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8321 isIncompleteDeclExternC(*this, NewVD))
8323
8324 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8326 Decl *ManglingContextDecl;
8327 std::tie(MCtx, ManglingContextDecl) =
8329 if (MCtx) {
8330 Context.setManglingNumber(
8331 NewVD, MCtx->getManglingNumber(
8332 NewVD, getMSManglingNumber(getLangOpts(), S)));
8333 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
8334 }
8335 }
8336
8337 // Special handling of variable named 'main'.
8338 if (!getLangOpts().Freestanding && isMainVar(Name, NewVD)) {
8339 // C++ [basic.start.main]p3:
8340 // A program that declares
8341 // - a variable main at global scope, or
8342 // - an entity named main with C language linkage (in any namespace)
8343 // is ill-formed
8344 if (getLangOpts().CPlusPlus)
8345 Diag(D.getBeginLoc(), diag::err_main_global_variable)
8346 << NewVD->isExternC();
8347
8348 // In C, and external-linkage variable named main results in undefined
8349 // behavior.
8350 else if (NewVD->hasExternalFormalLinkage())
8351 Diag(D.getBeginLoc(), diag::warn_main_redefined);
8352 }
8353
8354 if (D.isRedeclaration() && !Previous.empty()) {
8355 NamedDecl *Prev = Previous.getRepresentativeDecl();
8356 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
8358 }
8359
8360 if (NewTemplate) {
8361 if (NewVD->isInvalidDecl())
8362 NewTemplate->setInvalidDecl();
8363 ActOnDocumentableDecl(NewTemplate);
8364 return NewTemplate;
8365 }
8366
8367 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8369
8371
8372 return NewVD;
8373}
8374
8375/// Enum describing the %select options in diag::warn_decl_shadow.
8385
8386/// Determine what kind of declaration we're shadowing.
8388 const DeclContext *OldDC) {
8389 if (isa<TypeAliasDecl>(ShadowedDecl))
8390 return SDK_Using;
8391 else if (isa<TypedefDecl>(ShadowedDecl))
8392 return SDK_Typedef;
8393 else if (isa<BindingDecl>(ShadowedDecl))
8394 return SDK_StructuredBinding;
8395 else if (isa<RecordDecl>(OldDC))
8396 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8397
8398 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8399}
8400
8401/// Return the location of the capture if the given lambda captures the given
8402/// variable \p VD, or an invalid source location otherwise.
8404 const VarDecl *VD) {
8405 for (const Capture &Capture : LSI->Captures) {
8407 return Capture.getLocation();
8408 }
8409 return SourceLocation();
8410}
8411
8413 const LookupResult &R) {
8414 // Only diagnose if we're shadowing an unambiguous field or variable.
8416 return false;
8417
8418 // Return false if warning is ignored.
8419 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
8420}
8421
8423 const LookupResult &R) {
8425 return nullptr;
8426
8427 // Don't diagnose declarations at file scope.
8428 if (D->hasGlobalStorage() && !D->isStaticLocal())
8429 return nullptr;
8430
8431 NamedDecl *ShadowedDecl = R.getFoundDecl();
8432 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8433 : nullptr;
8434}
8435
8437 const LookupResult &R) {
8438 // Don't warn if typedef declaration is part of a class
8439 if (D->getDeclContext()->isRecord())
8440 return nullptr;
8441
8443 return nullptr;
8444
8445 NamedDecl *ShadowedDecl = R.getFoundDecl();
8446 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
8447}
8448
8450 const LookupResult &R) {
8452 return nullptr;
8453
8454 NamedDecl *ShadowedDecl = R.getFoundDecl();
8455 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8456 : nullptr;
8457}
8458
8460 const LookupResult &R) {
8461 DeclContext *NewDC = D->getDeclContext();
8462
8463 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
8464 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) {
8465 // Fields are not shadowed by variables in C++ static methods.
8466 if (MD->isStatic())
8467 return;
8468
8469 if (!MD->getParent()->isLambda() && MD->isExplicitObjectMemberFunction())
8470 return;
8471 }
8472 // Fields shadowed by constructor parameters are a special case. Usually
8473 // the constructor initializes the field with the parameter.
8474 if (isa<CXXConstructorDecl>(NewDC))
8475 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
8476 // Remember that this was shadowed so we can either warn about its
8477 // modification or its existence depending on warning settings.
8478 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
8479 return;
8480 }
8481 }
8482
8483 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
8484 if (shadowedVar->isExternC()) {
8485 // For shadowing external vars, make sure that we point to the global
8486 // declaration, not a locally scoped extern declaration.
8487 for (auto *I : shadowedVar->redecls())
8488 if (I->isFileVarDecl()) {
8489 ShadowedDecl = I;
8490 break;
8491 }
8492 }
8493
8494 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8495
8496 unsigned WarningDiag = diag::warn_decl_shadow;
8497 SourceLocation CaptureLoc;
8498 if (isa<VarDecl>(D) && NewDC && isa<CXXMethodDecl>(NewDC)) {
8499 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
8500 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
8501 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl)) {
8502 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
8503 if (RD->getLambdaCaptureDefault() == LCD_None) {
8504 // Try to avoid warnings for lambdas with an explicit capture
8505 // list. Warn only when the lambda captures the shadowed decl
8506 // explicitly.
8507 CaptureLoc = getCaptureLocation(LSI, VD);
8508 if (CaptureLoc.isInvalid())
8509 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8510 } else {
8511 // Remember that this was shadowed so we can avoid the warning if
8512 // the shadowed decl isn't captured and the warning settings allow
8513 // it.
8515 ->ShadowingDecls.push_back({D, VD});
8516 return;
8517 }
8518 }
8519 if (isa<FieldDecl>(ShadowedDecl)) {
8520 // If lambda can capture this, then emit default shadowing warning,
8521 // Otherwise it is not really a shadowing case since field is not
8522 // available in lambda's body.
8523 // At this point we don't know that lambda can capture this, so
8524 // remember that this was shadowed and delay until we know.
8526 ->ShadowingDecls.push_back({D, ShadowedDecl});
8527 return;
8528 }
8529 }
8530 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl);
8531 VD && VD->hasLocalStorage()) {
8532 // A variable can't shadow a local variable in an enclosing scope, if
8533 // they are separated by a non-capturing declaration context.
8534 for (DeclContext *ParentDC = NewDC;
8535 ParentDC && !ParentDC->Equals(OldDC);
8536 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
8537 // Only block literals, captured statements, and lambda expressions
8538 // can capture; other scopes don't.
8539 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
8540 !isLambdaCallOperator(ParentDC)) {
8541 return;
8542 }
8543 }
8544 }
8545 }
8546 }
8547
8548 // Never warn about shadowing a placeholder variable.
8549 if (ShadowedDecl->isPlaceholderVar(getLangOpts()))
8550 return;
8551
8552 // Only warn about certain kinds of shadowing for class members.
8553 if (NewDC) {
8554 // In particular, don't warn about shadowing non-class members.
8555 if (NewDC->isRecord() && !OldDC->isRecord())
8556 return;
8557
8558 // Skip shadowing check if we're in a class scope, dealing with an enum
8559 // constant in a different context.
8560 DeclContext *ReDC = NewDC->getRedeclContext();
8561 if (ReDC->isRecord() && isa<EnumConstantDecl>(D) && !OldDC->Equals(ReDC))
8562 return;
8563
8564 // TODO: should we warn about static data members shadowing
8565 // static data members from base classes?
8566
8567 // TODO: don't diagnose for inaccessible shadowed members.
8568 // This is hard to do perfectly because we might friend the
8569 // shadowing context, but that's just a false negative.
8570 }
8571
8572 DeclarationName Name = R.getLookupName();
8573
8574 // Emit warning and note.
8575 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8576 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8577 if (!CaptureLoc.isInvalid())
8578 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8579 << Name << /*explicitly*/ 1;
8580 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8581}
8582
8584 for (const auto &Shadow : LSI->ShadowingDecls) {
8585 const NamedDecl *ShadowedDecl = Shadow.ShadowedDecl;
8586 // Try to avoid the warning when the shadowed decl isn't captured.
8587 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8588 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl)) {
8589 SourceLocation CaptureLoc = getCaptureLocation(LSI, VD);
8590 Diag(Shadow.VD->getLocation(),
8591 CaptureLoc.isInvalid() ? diag::warn_decl_shadow_uncaptured_local
8592 : diag::warn_decl_shadow)
8593 << Shadow.VD->getDeclName()
8594 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8595 if (CaptureLoc.isValid())
8596 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8597 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8598 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8599 } else if (isa<FieldDecl>(ShadowedDecl)) {
8600 Diag(Shadow.VD->getLocation(),
8601 LSI->isCXXThisCaptured() ? diag::warn_decl_shadow
8602 : diag::warn_decl_shadow_uncaptured_local)
8603 << Shadow.VD->getDeclName()
8604 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8605 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8606 }
8607 }
8608}
8609
8611 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8612 return;
8613
8614 LookupResult R(*this, D->getDeclName(), D->getLocation(),
8617 LookupName(R, S);
8618 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8619 CheckShadow(D, ShadowedDecl, R);
8620}
8621
8622/// Check if 'E', which is an expression that is about to be modified, refers
8623/// to a constructor parameter that shadows a field.
8625 // Quickly ignore expressions that can't be shadowing ctor parameters.
8626 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8627 return;
8628 E = E->IgnoreParenImpCasts();
8629 auto *DRE = dyn_cast<DeclRefExpr>(E);
8630 if (!DRE)
8631 return;
8632 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8633 auto I = ShadowingDecls.find(D);
8634 if (I == ShadowingDecls.end())
8635 return;
8636 const NamedDecl *ShadowedDecl = I->second;
8637 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8638 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8639 Diag(D->getLocation(), diag::note_var_declared_here) << D;
8640 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8641
8642 // Avoid issuing multiple warnings about the same decl.
8643 ShadowingDecls.erase(I);
8644}
8645
8646/// Check for conflict between this global or extern "C" declaration and
8647/// previous global or extern "C" declarations. This is only used in C++.
8648template<typename T>
8650 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8651 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8652 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8653
8654 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8655 // The common case: this global doesn't conflict with any extern "C"
8656 // declaration.
8657 return false;
8658 }
8659
8660 if (Prev) {
8661 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8662 // Both the old and new declarations have C language linkage. This is a
8663 // redeclaration.
8664 Previous.clear();
8665 Previous.addDecl(Prev);
8666 return true;
8667 }
8668
8669 // This is a global, non-extern "C" declaration, and there is a previous
8670 // non-global extern "C" declaration. Diagnose if this is a variable
8671 // declaration.
8672 if (!isa<VarDecl>(ND))
8673 return false;
8674 } else {
8675 // The declaration is extern "C". Check for any declaration in the
8676 // translation unit which might conflict.
8677 if (IsGlobal) {
8678 // We have already performed the lookup into the translation unit.
8679 IsGlobal = false;
8680 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8681 I != E; ++I) {
8682 if (isa<VarDecl>(*I)) {
8683 Prev = *I;
8684 break;
8685 }
8686 }
8687 } else {
8689 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8690 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8691 I != E; ++I) {
8692 if (isa<VarDecl>(*I)) {
8693 Prev = *I;
8694 break;
8695 }
8696 // FIXME: If we have any other entity with this name in global scope,
8697 // the declaration is ill-formed, but that is a defect: it breaks the
8698 // 'stat' hack, for instance. Only variables can have mangled name
8699 // clashes with extern "C" declarations, so only they deserve a
8700 // diagnostic.
8701 }
8702 }
8703
8704 if (!Prev)
8705 return false;
8706 }
8707
8708 // Use the first declaration's location to ensure we point at something which
8709 // is lexically inside an extern "C" linkage-spec.
8710 assert(Prev && "should have found a previous declaration to diagnose");
8711 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8712 Prev = FD->getFirstDecl();
8713 else
8714 Prev = cast<VarDecl>(Prev)->getFirstDecl();
8715
8716 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8717 << IsGlobal << ND;
8718 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8719 << IsGlobal;
8720 return false;
8721}
8722
8723/// Apply special rules for handling extern "C" declarations. Returns \c true
8724/// if we have found that this is a redeclaration of some prior entity.
8725///
8726/// Per C++ [dcl.link]p6:
8727/// Two declarations [for a function or variable] with C language linkage
8728/// with the same name that appear in different scopes refer to the same
8729/// [entity]. An entity with C language linkage shall not be declared with
8730/// the same name as an entity in global scope.
8731template<typename T>
8734 if (!S.getLangOpts().CPlusPlus) {
8735 // In C, when declaring a global variable, look for a corresponding 'extern'
8736 // variable declared in function scope. We don't need this in C++, because
8737 // we find local extern decls in the surrounding file-scope DeclContext.
8738 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8739 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8740 Previous.clear();
8741 Previous.addDecl(Prev);
8742 return true;
8743 }
8744 }
8745 return false;
8746 }
8747
8748 // A declaration in the translation unit can conflict with an extern "C"
8749 // declaration.
8750 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8751 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8752
8753 // An extern "C" declaration can conflict with a declaration in the
8754 // translation unit or can be a redeclaration of an extern "C" declaration
8755 // in another scope.
8756 if (isIncompleteDeclExternC(S,ND))
8757 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8758
8759 // Neither global nor extern "C": nothing to do.
8760 return false;
8761}
8762
8763static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc,
8764 QualType T) {
8765 QualType CanonT = SemaRef.Context.getCanonicalType(T);
8766 // C23 6.7.1p5: An object declared with storage-class specifier constexpr or
8767 // any of its members, even recursively, shall not have an atomic type, or a
8768 // variably modified type, or a type that is volatile or restrict qualified.
8769 if (CanonT->isVariablyModifiedType()) {
8770 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8771 return true;
8772 }
8773
8774 // Arrays are qualified by their element type, so get the base type (this
8775 // works on non-arrays as well).
8776 CanonT = SemaRef.Context.getBaseElementType(CanonT);
8777
8778 if (CanonT->isAtomicType() || CanonT.isVolatileQualified() ||
8779 CanonT.isRestrictQualified()) {
8780 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8781 return true;
8782 }
8783
8784 if (CanonT->isRecordType()) {
8785 const RecordDecl *RD = CanonT->getAsRecordDecl();
8786 if (!RD->isInvalidDecl() &&
8787 llvm::any_of(RD->fields(), [&SemaRef, VarLoc](const FieldDecl *F) {
8788 return CheckC23ConstexprVarType(SemaRef, VarLoc, F->getType());
8789 }))
8790 return true;
8791 }
8792
8793 return false;
8794}
8795
8797 // If the decl is already known invalid, don't check it.
8798 if (NewVD->isInvalidDecl())
8799 return;
8800
8801 QualType T = NewVD->getType();
8802
8803 // Defer checking an 'auto' type until its initializer is attached.
8804 if (T->isUndeducedType())
8805 return;
8806
8807 if (NewVD->hasAttrs())
8809
8810 if (T->isObjCObjectType()) {
8811 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8812 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8813 T = Context.getObjCObjectPointerType(T);
8814 NewVD->setType(T);
8815 }
8816
8817 // Emit an error if an address space was applied to decl with local storage.
8818 // This includes arrays of objects with address space qualifiers, but not
8819 // automatic variables that point to other address spaces.
8820 // ISO/IEC TR 18037 S5.1.2
8821 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8822 T.getAddressSpace() != LangAS::Default) {
8823 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8824 NewVD->setInvalidDecl();
8825 return;
8826 }
8827
8828 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8829 // scope.
8830 if (getLangOpts().OpenCLVersion == 120 &&
8831 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8832 getLangOpts()) &&
8833 NewVD->isStaticLocal()) {
8834 Diag(NewVD->getLocation(), diag::err_static_function_scope);
8835 NewVD->setInvalidDecl();
8836 return;
8837 }
8838
8839 if (getLangOpts().OpenCL) {
8840 if (!diagnoseOpenCLTypes(*this, NewVD))
8841 return;
8842
8843 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8844 if (NewVD->hasAttr<BlocksAttr>()) {
8845 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8846 return;
8847 }
8848
8849 if (T->isBlockPointerType()) {
8850 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8851 // can't use 'extern' storage class.
8852 if (!T.isConstQualified()) {
8853 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8854 << 0 /*const*/;
8855 NewVD->setInvalidDecl();
8856 return;
8857 }
8858 if (NewVD->hasExternalStorage()) {
8859 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8860 NewVD->setInvalidDecl();
8861 return;
8862 }
8863 }
8864
8865 // FIXME: Adding local AS in C++ for OpenCL might make sense.
8866 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8867 NewVD->hasExternalStorage()) {
8868 if (!T->isSamplerT() && !T->isDependentType() &&
8869 !(T.getAddressSpace() == LangAS::opencl_constant ||
8870 (T.getAddressSpace() == LangAS::opencl_global &&
8871 getOpenCLOptions().areProgramScopeVariablesSupported(
8872 getLangOpts())))) {
8873 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8874 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8875 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8876 << Scope << "global or constant";
8877 else
8878 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8879 << Scope << "constant";
8880 NewVD->setInvalidDecl();
8881 return;
8882 }
8883 } else {
8884 if (T.getAddressSpace() == LangAS::opencl_global) {
8885 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8886 << 1 /*is any function*/ << "global";
8887 NewVD->setInvalidDecl();
8888 return;
8889 }
8890 if (T.getAddressSpace() == LangAS::opencl_constant ||
8891 T.getAddressSpace() == LangAS::opencl_local) {
8893 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8894 // in functions.
8895 if (FD && !FD->hasAttr<DeviceKernelAttr>()) {
8896 if (T.getAddressSpace() == LangAS::opencl_constant)
8897 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8898 << 0 /*non-kernel only*/ << "constant";
8899 else
8900 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8901 << 0 /*non-kernel only*/ << "local";
8902 NewVD->setInvalidDecl();
8903 return;
8904 }
8905 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8906 // in the outermost scope of a kernel function.
8907 if (FD && FD->hasAttr<DeviceKernelAttr>()) {
8908 if (!getCurScope()->isFunctionScope()) {
8909 if (T.getAddressSpace() == LangAS::opencl_constant)
8910 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8911 << "constant";
8912 else
8913 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8914 << "local";
8915 NewVD->setInvalidDecl();
8916 return;
8917 }
8918 }
8919 } else if (T.getAddressSpace() != LangAS::opencl_private &&
8920 // If we are parsing a template we didn't deduce an addr
8921 // space yet.
8922 T.getAddressSpace() != LangAS::Default) {
8923 // Do not allow other address spaces on automatic variable.
8924 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8925 NewVD->setInvalidDecl();
8926 return;
8927 }
8928 }
8929 }
8930
8931 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8932 && !NewVD->hasAttr<BlocksAttr>()) {
8933 if (getLangOpts().getGC() != LangOptions::NonGC)
8934 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8935 else {
8936 assert(!getLangOpts().ObjCAutoRefCount);
8937 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8938 }
8939 }
8940
8941 // WebAssembly tables must be static with a zero length and can't be
8942 // declared within functions.
8943 if (T->isWebAssemblyTableType()) {
8944 if (getCurScope()->getParent()) { // Parent is null at top-level
8945 Diag(NewVD->getLocation(), diag::err_wasm_table_in_function);
8946 NewVD->setInvalidDecl();
8947 return;
8948 }
8949 if (NewVD->getStorageClass() != SC_Static) {
8950 Diag(NewVD->getLocation(), diag::err_wasm_table_must_be_static);
8951 NewVD->setInvalidDecl();
8952 return;
8953 }
8954 const auto *ATy = dyn_cast<ConstantArrayType>(T.getTypePtr());
8955 if (!ATy || ATy->getZExtSize() != 0) {
8956 Diag(NewVD->getLocation(),
8957 diag::err_typecheck_wasm_table_must_have_zero_length);
8958 NewVD->setInvalidDecl();
8959 return;
8960 }
8961 }
8962
8963 // zero sized static arrays are not allowed in HIP device functions
8964 if (getLangOpts().HIP && LangOpts.CUDAIsDevice) {
8965 if (FunctionDecl *FD = getCurFunctionDecl();
8966 FD &&
8967 (FD->hasAttr<CUDADeviceAttr>() || FD->hasAttr<CUDAGlobalAttr>())) {
8968 if (const ConstantArrayType *ArrayT =
8969 getASTContext().getAsConstantArrayType(T);
8970 ArrayT && ArrayT->isZeroSize()) {
8971 Diag(NewVD->getLocation(), diag::err_typecheck_zero_array_size) << 2;
8972 }
8973 }
8974 }
8975
8976 bool isVM = T->isVariablyModifiedType();
8977 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8978 NewVD->hasAttr<BlocksAttr>())
8980
8981 if ((isVM && NewVD->hasLinkage()) ||
8982 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8983 bool SizeIsNegative;
8984 llvm::APSInt Oversized;
8986 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8987 QualType FixedT;
8988 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
8989 FixedT = FixedTInfo->getType();
8990 else if (FixedTInfo) {
8991 // Type and type-as-written are canonically different. We need to fix up
8992 // both types separately.
8993 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8994 Oversized);
8995 }
8996 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8997 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8998 // FIXME: This won't give the correct result for
8999 // int a[10][n];
9000 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
9001
9002 if (NewVD->isFileVarDecl())
9003 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
9004 << SizeRange;
9005 else if (NewVD->isStaticLocal())
9006 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
9007 << SizeRange;
9008 else
9009 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
9010 << SizeRange;
9011 NewVD->setInvalidDecl();
9012 return;
9013 }
9014
9015 if (!FixedTInfo) {
9016 if (NewVD->isFileVarDecl())
9017 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
9018 else
9019 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
9020 NewVD->setInvalidDecl();
9021 return;
9022 }
9023
9024 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
9025 NewVD->setType(FixedT);
9026 NewVD->setTypeSourceInfo(FixedTInfo);
9027 }
9028
9029 if (T->isVoidType()) {
9030 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
9031 // of objects and functions.
9033 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
9034 << T;
9035 NewVD->setInvalidDecl();
9036 return;
9037 }
9038 }
9039
9040 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
9041 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
9042 NewVD->setInvalidDecl();
9043 return;
9044 }
9045
9046 if (!NewVD->hasLocalStorage() && T->isSizelessType() &&
9047 !T.isWebAssemblyReferenceType() && !T->isHLSLSpecificType()) {
9048 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
9049 NewVD->setInvalidDecl();
9050 return;
9051 }
9052
9053 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
9054 Diag(NewVD->getLocation(), diag::err_block_on_vm);
9055 NewVD->setInvalidDecl();
9056 return;
9057 }
9058
9059 if (getLangOpts().C23 && NewVD->isConstexpr() &&
9060 CheckC23ConstexprVarType(*this, NewVD->getLocation(), T)) {
9061 NewVD->setInvalidDecl();
9062 return;
9063 }
9064
9065 if (getLangOpts().CPlusPlus && NewVD->isConstexpr() &&
9066 !T->isDependentType() &&
9068 diag::err_constexpr_var_non_literal)) {
9069 NewVD->setInvalidDecl();
9070 return;
9071 }
9072
9073 // PPC MMA non-pointer types are not allowed as non-local variable types.
9074 if (Context.getTargetInfo().getTriple().isPPC64() &&
9075 !NewVD->isLocalVarDecl() &&
9076 PPC().CheckPPCMMAType(T, NewVD->getLocation())) {
9077 NewVD->setInvalidDecl();
9078 return;
9079 }
9080
9081 // Check that SVE types are only used in functions with SVE available.
9082 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
9084 llvm::StringMap<bool> CallerFeatureMap;
9085 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
9086
9087 if (!Builtin::evaluateRequiredTargetFeatures("sve", CallerFeatureMap)) {
9088 if (!Builtin::evaluateRequiredTargetFeatures("sme", CallerFeatureMap)) {
9089 Diag(NewVD->getLocation(), diag::err_sve_vector_in_non_sve_target) << T;
9090 NewVD->setInvalidDecl();
9091 return;
9092 } else if (!IsArmStreamingFunction(FD,
9093 /*IncludeLocallyStreaming=*/true)) {
9094 Diag(NewVD->getLocation(),
9095 diag::err_sve_vector_in_non_streaming_function)
9096 << T;
9097 NewVD->setInvalidDecl();
9098 return;
9099 }
9100 }
9101 }
9102
9103 if (T->isRVVSizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
9105 llvm::StringMap<bool> CallerFeatureMap;
9106 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
9108 CallerFeatureMap);
9109 }
9110}
9111
9114
9115 // If the decl is already known invalid, don't check it.
9116 if (NewVD->isInvalidDecl())
9117 return false;
9118
9119 // If we did not find anything by this name, look for a non-visible
9120 // extern "C" declaration with the same name.
9121 if (Previous.empty() &&
9123 Previous.setShadowed();
9124
9125 if (!Previous.empty()) {
9126 MergeVarDecl(NewVD, Previous);
9127 return true;
9128 }
9129 return false;
9130}
9131
9134
9135 // Look for methods in base classes that this method might override.
9136 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
9137 /*DetectVirtual=*/false);
9138 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9139 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
9140 DeclarationName Name = MD->getDeclName();
9141
9143 // We really want to find the base class destructor here.
9144 Name = Context.DeclarationNames.getCXXDestructorName(
9145 Context.getCanonicalTagType(BaseRecord));
9146 }
9147
9148 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
9149 CXXMethodDecl *BaseMD =
9150 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
9151 if (!BaseMD || !BaseMD->isVirtual() ||
9152 IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
9153 /*ConsiderCudaAttrs=*/true))
9154 continue;
9155 if (!CheckExplicitObjectOverride(MD, BaseMD))
9156 continue;
9157 if (Overridden.insert(BaseMD).second) {
9158 MD->addOverriddenMethod(BaseMD);
9163 }
9164
9165 // A method can only override one function from each base class. We
9166 // don't track indirectly overridden methods from bases of bases.
9167 return true;
9168 }
9169
9170 return false;
9171 };
9172
9173 DC->lookupInBases(VisitBase, Paths);
9174 return !Overridden.empty();
9175}
9176
9177namespace {
9178 // Struct for holding all of the extra arguments needed by
9179 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
9180 struct ActOnFDArgs {
9181 Scope *S;
9182 Declarator &D;
9183 MultiTemplateParamsArg TemplateParamLists;
9184 bool AddToScope;
9185 };
9186} // end anonymous namespace
9187
9188namespace {
9189
9190// Callback to only accept typo corrections that have a non-zero edit distance.
9191// Also only accept corrections that have the same parent decl.
9192class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
9193 public:
9194 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
9195 CXXRecordDecl *Parent)
9196 : Context(Context), OriginalFD(TypoFD),
9197 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
9198
9199 bool ValidateCandidate(const TypoCorrection &candidate) override {
9200 if (candidate.getEditDistance() == 0)
9201 return false;
9202
9203 SmallVector<unsigned, 1> MismatchedParams;
9204 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
9205 CDeclEnd = candidate.end();
9206 CDecl != CDeclEnd; ++CDecl) {
9207 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9208
9209 if (FD && !FD->hasBody() &&
9210 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
9211 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
9212 CXXRecordDecl *Parent = MD->getParent();
9213 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
9214 return true;
9215 } else if (!ExpectedParent) {
9216 return true;
9217 }
9218 }
9219 }
9220
9221 return false;
9222 }
9223
9224 std::unique_ptr<CorrectionCandidateCallback> clone() override {
9225 return std::make_unique<DifferentNameValidatorCCC>(*this);
9226 }
9227
9228 private:
9229 ASTContext &Context;
9230 FunctionDecl *OriginalFD;
9231 CXXRecordDecl *ExpectedParent;
9232};
9233
9234} // end anonymous namespace
9235
9239
9240/// Generate diagnostics for an invalid function redeclaration.
9241///
9242/// This routine handles generating the diagnostic messages for an invalid
9243/// function redeclaration, including finding possible similar declarations
9244/// or performing typo correction if there are no previous declarations with
9245/// the same name.
9246///
9247/// Returns a NamedDecl iff typo correction was performed and substituting in
9248/// the new declaration name does not cause new errors.
9250 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
9251 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
9252 DeclarationName Name = NewFD->getDeclName();
9253 DeclContext *NewDC = NewFD->getDeclContext();
9254 SmallVector<unsigned, 1> MismatchedParams;
9256 TypoCorrection Correction;
9257 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
9258 unsigned DiagMsg =
9259 IsLocalFriend ? diag::err_no_matching_local_friend :
9260 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
9261 diag::err_member_decl_does_not_match;
9262 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
9263 IsLocalFriend ? Sema::LookupLocalFriendName
9266
9267 NewFD->setInvalidDecl();
9268 if (IsLocalFriend)
9269 SemaRef.LookupName(Prev, S);
9270 else
9271 SemaRef.LookupQualifiedName(Prev, NewDC);
9272 assert(!Prev.isAmbiguous() &&
9273 "Cannot have an ambiguity in previous-declaration lookup");
9274 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9275 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
9276 MD ? MD->getParent() : nullptr);
9277 if (!Prev.empty()) {
9278 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
9279 Func != FuncEnd; ++Func) {
9280 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
9281 if (FD &&
9282 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9283 // Add 1 to the index so that 0 can mean the mismatch didn't
9284 // involve a parameter
9285 unsigned ParamNum =
9286 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
9287 NearMatches.push_back(std::make_pair(FD, ParamNum));
9288 }
9289 }
9290 // If the qualified name lookup yielded nothing, try typo correction
9291 } else if ((Correction = SemaRef.CorrectTypo(
9292 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
9293 &ExtraArgs.D.getCXXScopeSpec(), CCC,
9295 IsLocalFriend ? nullptr : NewDC))) {
9296 // Set up everything for the call to ActOnFunctionDeclarator
9297 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
9298 ExtraArgs.D.getIdentifierLoc());
9299 Previous.clear();
9300 Previous.setLookupName(Correction.getCorrection());
9301 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
9302 CDeclEnd = Correction.end();
9303 CDecl != CDeclEnd; ++CDecl) {
9304 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9305 if (FD && !FD->hasBody() &&
9306 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9307 Previous.addDecl(FD);
9308 }
9309 }
9310 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
9311
9312 NamedDecl *Result;
9313 // Retry building the function declaration with the new previous
9314 // declarations, and with errors suppressed.
9315 {
9316 // Trap errors.
9317 Sema::SFINAETrap Trap(SemaRef);
9318
9319 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
9320 // pieces need to verify the typo-corrected C++ declaration and hopefully
9321 // eliminate the need for the parameter pack ExtraArgs.
9322 Result = SemaRef.ActOnFunctionDeclarator(
9323 ExtraArgs.S, ExtraArgs.D,
9324 Correction.getCorrectionDecl()->getDeclContext(),
9325 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
9326 ExtraArgs.AddToScope);
9327
9328 if (Trap.hasErrorOccurred())
9329 Result = nullptr;
9330 }
9331
9332 if (Result) {
9333 // Determine which correction we picked.
9334 Decl *Canonical = Result->getCanonicalDecl();
9335 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9336 I != E; ++I)
9337 if ((*I)->getCanonicalDecl() == Canonical)
9338 Correction.setCorrectionDecl(*I);
9339
9340 // Let Sema know about the correction.
9342 SemaRef.diagnoseTypo(
9343 Correction,
9344 SemaRef.PDiag(IsLocalFriend
9345 ? diag::err_no_matching_local_friend_suggest
9346 : diag::err_member_decl_does_not_match_suggest)
9347 << Name << NewDC << IsDefinition);
9348 return Result;
9349 }
9350
9351 // Pretend the typo correction never occurred
9352 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
9353 ExtraArgs.D.getIdentifierLoc());
9354 ExtraArgs.D.setRedeclaration(wasRedeclaration);
9355 Previous.clear();
9356 Previous.setLookupName(Name);
9357 }
9358
9359 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
9360 << Name << NewDC << IsDefinition << NewFD->getLocation();
9361
9362 CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD);
9363 if (NewMD && DiagMsg == diag::err_member_decl_does_not_match) {
9364 CXXRecordDecl *RD = NewMD->getParent();
9365 SemaRef.Diag(RD->getLocation(), diag::note_defined_here)
9366 << RD->getName() << RD->getLocation();
9367 }
9368
9369 bool NewFDisConst = NewMD && NewMD->isConst();
9370
9371 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
9372 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
9373 NearMatch != NearMatchEnd; ++NearMatch) {
9374 FunctionDecl *FD = NearMatch->first;
9375 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
9376 bool FDisConst = MD && MD->isConst();
9377 bool IsMember = MD || !IsLocalFriend;
9378
9379 // FIXME: These notes are poorly worded for the local friend case.
9380 if (unsigned Idx = NearMatch->second) {
9381 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
9382 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
9383 if (Loc.isInvalid()) Loc = FD->getLocation();
9384 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
9385 : diag::note_local_decl_close_param_match)
9386 << Idx << FDParam->getType()
9387 << NewFD->getParamDecl(Idx - 1)->getType();
9388 } else if (FDisConst != NewFDisConst) {
9389 auto DB = SemaRef.Diag(FD->getLocation(),
9390 diag::note_member_def_close_const_match)
9391 << NewFDisConst << FD->getSourceRange().getEnd();
9392 if (const auto &FTI = ExtraArgs.D.getFunctionTypeInfo(); !NewFDisConst)
9393 DB << FixItHint::CreateInsertion(FTI.getRParenLoc().getLocWithOffset(1),
9394 " const");
9395 else if (FTI.hasMethodTypeQualifiers() &&
9396 FTI.getConstQualifierLoc().isValid())
9397 DB << FixItHint::CreateRemoval(FTI.getConstQualifierLoc());
9398 } else {
9399 SemaRef.Diag(FD->getLocation(),
9400 IsMember ? diag::note_member_def_close_match
9401 : diag::note_local_decl_close_match);
9402 }
9403 }
9404 return nullptr;
9405}
9406
9408 switch (D.getDeclSpec().getStorageClassSpec()) {
9409 default: llvm_unreachable("Unknown storage class!");
9410 case DeclSpec::SCS_auto:
9414 diag::err_typecheck_sclass_func);
9416 D.setInvalidType();
9417 break;
9418 case DeclSpec::SCS_unspecified: break;
9421 return SC_None;
9422 return SC_Extern;
9423 case DeclSpec::SCS_static: {
9425 // C99 6.7.1p5:
9426 // The declaration of an identifier for a function that has
9427 // block scope shall have no explicit storage-class specifier
9428 // other than extern
9429 // See also (C++ [dcl.stc]p4).
9431 diag::err_static_block_func);
9432 break;
9433 } else
9434 return SC_Static;
9435 }
9437 }
9438
9439 // No explicit storage class has already been returned
9440 return SC_None;
9441}
9442
9444 DeclContext *DC, QualType &R,
9445 TypeSourceInfo *TInfo,
9446 StorageClass SC,
9447 bool &IsVirtualOkay) {
9448 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9449 DeclarationName Name = NameInfo.getName();
9450
9451 FunctionDecl *NewFD = nullptr;
9452 bool isInline = D.getDeclSpec().isInlineSpecified();
9453
9455 if (ConstexprKind == ConstexprSpecKind::Constinit ||
9456 (SemaRef.getLangOpts().C23 &&
9457 ConstexprKind == ConstexprSpecKind::Constexpr)) {
9458
9459 if (SemaRef.getLangOpts().C23)
9460 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9461 diag::err_c23_constexpr_not_variable);
9462 else
9463 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9464 diag::err_constexpr_wrong_decl_kind)
9465 << static_cast<int>(ConstexprKind);
9466 ConstexprKind = ConstexprSpecKind::Unspecified;
9468 }
9469
9470 if (!SemaRef.getLangOpts().CPlusPlus) {
9471 // Determine whether the function was written with a prototype. This is
9472 // true when:
9473 // - there is a prototype in the declarator, or
9474 // - the type R of the function is some kind of typedef or other non-
9475 // attributed reference to a type name (which eventually refers to a
9476 // function type). Note, we can't always look at the adjusted type to
9477 // check this case because attributes may cause a non-function
9478 // declarator to still have a function type. e.g.,
9479 // typedef void func(int a);
9480 // __attribute__((noreturn)) func other_func; // This has a prototype
9481 bool HasPrototype =
9483 (D.getDeclSpec().isTypeRep() &&
9484 SemaRef.GetTypeFromParser(D.getDeclSpec().getRepAsType(), nullptr)
9485 ->isFunctionProtoType()) ||
9487 assert(
9488 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9489 "Strict prototypes are required");
9490
9491 NewFD = FunctionDecl::Create(
9492 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9493 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
9495 /*TrailingRequiresClause=*/{});
9496 if (D.isInvalidType())
9497 NewFD->setInvalidDecl();
9498
9499 return NewFD;
9500 }
9501
9503 AssociatedConstraint TrailingRequiresClause(D.getTrailingRequiresClause());
9504
9505 SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R);
9506
9508 // This is a C++ constructor declaration.
9509 assert(DC->isRecord() &&
9510 "Constructors can only be declared in a member context");
9511
9512 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9514 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9516 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9517 InheritedConstructor(), TrailingRequiresClause);
9518
9519 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9520 // This is a C++ destructor declaration.
9521 if (DC->isRecord()) {
9522 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9525 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
9526 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9527 /*isImplicitlyDeclared=*/false, ConstexprKind,
9528 TrailingRequiresClause);
9529 // User defined destructors start as not selected if the class definition is still
9530 // not done.
9531 if (Record->isBeingDefined())
9532 NewDD->setIneligibleOrNotSelected(true);
9533
9534 // If the destructor needs an implicit exception specification, set it
9535 // now. FIXME: It'd be nice to be able to create the right type to start
9536 // with, but the type needs to reference the destructor declaration.
9537 if (SemaRef.getLangOpts().CPlusPlus11)
9538 SemaRef.AdjustDestructorExceptionSpec(NewDD);
9539
9540 IsVirtualOkay = true;
9541 return NewDD;
9542
9543 } else {
9544 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
9545 D.setInvalidType();
9546
9547 // Create a FunctionDecl to satisfy the function definition parsing
9548 // code path.
9549 return FunctionDecl::Create(
9550 SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
9551 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9552 /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
9553 }
9554
9556 if (!DC->isRecord()) {
9557 SemaRef.Diag(D.getIdentifierLoc(),
9558 diag::err_conv_function_not_member);
9559 return nullptr;
9560 }
9561
9562 SemaRef.CheckConversionDeclarator(D, R, SC);
9563 if (D.isInvalidType())
9564 return nullptr;
9565
9566 IsVirtualOkay = true;
9568 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9569 TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9570 ExplicitSpecifier, ConstexprKind, SourceLocation(),
9571 TrailingRequiresClause);
9572
9574 if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))
9575 return nullptr;
9577 SemaRef.Context, DC, D.getBeginLoc(), ExplicitSpecifier, NameInfo, R,
9578 TInfo, D.getEndLoc(), /*Ctor=*/nullptr,
9579 /*Kind=*/DeductionCandidate::Normal, TrailingRequiresClause);
9580 } else if (DC->isRecord()) {
9581 // If the name of the function is the same as the name of the record,
9582 // then this must be an invalid constructor that has a return type.
9583 // (The parser checks for a return type and makes the declarator a
9584 // constructor if it has no return type).
9585 if (Name.getAsIdentifierInfo() &&
9586 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
9587 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
9590 return nullptr;
9591 }
9592
9593 // This is a C++ method declaration.
9595 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9596 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9597 ConstexprKind, SourceLocation(), TrailingRequiresClause);
9598 IsVirtualOkay = !Ret->isStatic();
9599 return Ret;
9600 } else {
9601 bool isFriend =
9602 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9603 if (!isFriend && SemaRef.CurContext->isRecord())
9604 return nullptr;
9605
9606 // Determine whether the function was written with a
9607 // prototype. This true when:
9608 // - we're in C++ (where every function has a prototype),
9609 return FunctionDecl::Create(
9610 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9611 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9612 true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9613 }
9614}
9615
9624
9626 // Size dependent types are just typedefs to normal integer types
9627 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9628 // integers other than by their names.
9629 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9630
9631 // Remove typedefs one by one until we reach a typedef
9632 // for a size dependent type.
9633 QualType DesugaredTy = Ty;
9634 do {
9635 ArrayRef<StringRef> Names(SizeTypeNames);
9636 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
9637 if (Names.end() != Match)
9638 return true;
9639
9640 Ty = DesugaredTy;
9641 DesugaredTy = Ty.getSingleStepDesugaredType(C);
9642 } while (DesugaredTy != Ty);
9643
9644 return false;
9645}
9646
9648 if (PT->isDependentType())
9649 return InvalidKernelParam;
9650
9651 if (PT->isPointerOrReferenceType()) {
9652 QualType PointeeType = PT->getPointeeType();
9653 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9654 PointeeType.getAddressSpace() == LangAS::opencl_private ||
9655 PointeeType.getAddressSpace() == LangAS::Default)
9657
9658 if (PointeeType->isPointerType()) {
9659 // This is a pointer to pointer parameter.
9660 // Recursively check inner type.
9661 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
9662 if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9663 ParamKind == InvalidKernelParam)
9664 return ParamKind;
9665
9666 // OpenCL v3.0 s6.11.a:
9667 // A restriction to pass pointers to pointers only applies to OpenCL C
9668 // v1.2 or below.
9670 return ValidKernelParam;
9671
9672 return PtrPtrKernelParam;
9673 }
9674
9675 // C++ for OpenCL v1.0 s2.4:
9676 // Moreover the types used in parameters of the kernel functions must be:
9677 // Standard layout types for pointer parameters. The same applies to
9678 // reference if an implementation supports them in kernel parameters.
9679 if (S.getLangOpts().OpenCLCPlusPlus &&
9681 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts())) {
9682 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9683 bool IsStandardLayoutType = true;
9684 if (CXXRec) {
9685 // If template type is not ODR-used its definition is only available
9686 // in the template definition not its instantiation.
9687 // FIXME: This logic doesn't work for types that depend on template
9688 // parameter (PR58590).
9689 if (!CXXRec->hasDefinition())
9690 CXXRec = CXXRec->getTemplateInstantiationPattern();
9691 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9692 IsStandardLayoutType = false;
9693 }
9694 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9695 !IsStandardLayoutType)
9696 return InvalidKernelParam;
9697 }
9698
9699 // OpenCL v1.2 s6.9.p:
9700 // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9702 return ValidKernelParam;
9703
9704 return PtrKernelParam;
9705 }
9706
9707 // OpenCL v1.2 s6.9.k:
9708 // Arguments to kernel functions in a program cannot be declared with the
9709 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9710 // uintptr_t or a struct and/or union that contain fields declared to be one
9711 // of these built-in scalar types.
9713 return InvalidKernelParam;
9714
9715 if (PT->isImageType())
9716 return PtrKernelParam;
9717
9718 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9719 return InvalidKernelParam;
9720
9721 // OpenCL extension spec v1.2 s9.5:
9722 // This extension adds support for half scalar and vector types as built-in
9723 // types that can be used for arithmetic operations, conversions etc.
9724 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
9725 PT->isHalfType())
9726 return InvalidKernelParam;
9727
9728 // Look into an array argument to check if it has a forbidden type.
9729 if (PT->isArrayType()) {
9730 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9731 // Call ourself to check an underlying type of an array. Since the
9732 // getPointeeOrArrayElementType returns an innermost type which is not an
9733 // array, this recursive call only happens once.
9734 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
9735 }
9736
9737 // C++ for OpenCL v1.0 s2.4:
9738 // Moreover the types used in parameters of the kernel functions must be:
9739 // Trivial and standard-layout types C++17 [basic.types] (plain old data
9740 // types) for parameters passed by value;
9741 if (S.getLangOpts().OpenCLCPlusPlus &&
9743 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9744 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
9745 return InvalidKernelParam;
9746
9747 if (PT->isRecordType())
9748 return RecordKernelParam;
9749
9750 return ValidKernelParam;
9751}
9752
9754 Sema &S,
9755 Declarator &D,
9756 ParmVarDecl *Param,
9757 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9758 QualType PT = Param->getType();
9759
9760 // Cache the valid types we encounter to avoid rechecking structs that are
9761 // used again
9762 if (ValidTypes.count(PT.getTypePtr()))
9763 return;
9764
9765 switch (getOpenCLKernelParameterType(S, PT)) {
9766 case PtrPtrKernelParam:
9767 // OpenCL v3.0 s6.11.a:
9768 // A kernel function argument cannot be declared as a pointer to a pointer
9769 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9770 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9771 D.setInvalidType();
9772 return;
9773
9775 // OpenCL v1.0 s6.5:
9776 // __kernel function arguments declared to be a pointer of a type can point
9777 // to one of the following address spaces only : __global, __local or
9778 // __constant.
9779 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9780 D.setInvalidType();
9781 return;
9782
9783 // OpenCL v1.2 s6.9.k:
9784 // Arguments to kernel functions in a program cannot be declared with the
9785 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9786 // uintptr_t or a struct and/or union that contain fields declared to be
9787 // one of these built-in scalar types.
9788
9789 case InvalidKernelParam:
9790 // OpenCL v1.2 s6.8 n:
9791 // A kernel function argument cannot be declared
9792 // of event_t type.
9793 // Do not diagnose half type since it is diagnosed as invalid argument
9794 // type for any function elsewhere.
9795 if (!PT->isHalfType()) {
9796 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9797
9798 // Explain what typedefs are involved.
9799 const TypedefType *Typedef = nullptr;
9800 while ((Typedef = PT->getAs<TypedefType>())) {
9801 SourceLocation Loc = Typedef->getDecl()->getLocation();
9802 // SourceLocation may be invalid for a built-in type.
9803 if (Loc.isValid())
9804 S.Diag(Loc, diag::note_entity_declared_at) << PT;
9805 PT = Typedef->desugar();
9806 }
9807 }
9808
9809 D.setInvalidType();
9810 return;
9811
9812 case PtrKernelParam:
9813 case ValidKernelParam:
9814 ValidTypes.insert(PT.getTypePtr());
9815 return;
9816
9817 case RecordKernelParam:
9818 break;
9819 }
9820
9821 // Track nested structs we will inspect
9823
9824 // Track where we are in the nested structs. Items will migrate from
9825 // VisitStack to HistoryStack as we do the DFS for bad field.
9827 HistoryStack.push_back(nullptr);
9828
9829 // At this point we already handled everything except of a RecordType.
9830 assert(PT->isRecordType() && "Unexpected type.");
9831 const auto *PD = PT->castAsRecordDecl();
9832 VisitStack.push_back(PD);
9833 assert(VisitStack.back() && "First decl null?");
9834
9835 do {
9836 const Decl *Next = VisitStack.pop_back_val();
9837 if (!Next) {
9838 assert(!HistoryStack.empty());
9839 // Found a marker, we have gone up a level
9840 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9841 ValidTypes.insert(Hist->getType().getTypePtr());
9842
9843 continue;
9844 }
9845
9846 // Adds everything except the original parameter declaration (which is not a
9847 // field itself) to the history stack.
9848 const RecordDecl *RD;
9849 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9850 HistoryStack.push_back(Field);
9851
9852 QualType FieldTy = Field->getType();
9853 // Other field types (known to be valid or invalid) are handled while we
9854 // walk around RecordDecl::fields().
9855 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9856 "Unexpected type.");
9857 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9858
9859 RD = FieldRecTy->castAsRecordDecl();
9860 } else {
9861 RD = cast<RecordDecl>(Next);
9862 }
9863
9864 // Add a null marker so we know when we've gone back up a level
9865 VisitStack.push_back(nullptr);
9866
9867 for (const auto *FD : RD->fields()) {
9868 QualType QT = FD->getType();
9869
9870 if (ValidTypes.count(QT.getTypePtr()))
9871 continue;
9872
9874 if (ParamType == ValidKernelParam)
9875 continue;
9876
9877 if (ParamType == RecordKernelParam) {
9878 VisitStack.push_back(FD);
9879 continue;
9880 }
9881
9882 // OpenCL v1.2 s6.9.p:
9883 // Arguments to kernel functions that are declared to be a struct or union
9884 // do not allow OpenCL objects to be passed as elements of the struct or
9885 // union. This restriction was lifted in OpenCL v2.0 with the introduction
9886 // of SVM.
9887 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9888 ParamType == InvalidAddrSpacePtrKernelParam) {
9889 S.Diag(Param->getLocation(),
9890 diag::err_record_with_pointers_kernel_param)
9891 << PT->isUnionType()
9892 << PT;
9893 } else {
9894 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9895 }
9896
9897 S.Diag(PD->getLocation(), diag::note_within_field_of_type)
9898 << PD->getDeclName();
9899
9900 // We have an error, now let's go back up through history and show where
9901 // the offending field came from
9903 I = HistoryStack.begin() + 1,
9904 E = HistoryStack.end();
9905 I != E; ++I) {
9906 const FieldDecl *OuterField = *I;
9907 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9908 << OuterField->getType();
9909 }
9910
9911 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9912 << QT->isPointerType()
9913 << QT;
9914 D.setInvalidType();
9915 return;
9916 }
9917 } while (!VisitStack.empty());
9918}
9919
9920/// Find the DeclContext in which a tag is implicitly declared if we see an
9921/// elaborated type specifier in the specified context, and lookup finds
9922/// nothing.
9924 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9925 DC = DC->getParent();
9926 return DC;
9927}
9928
9929/// Find the Scope in which a tag is implicitly declared if we see an
9930/// elaborated type specifier in the specified context, and lookup finds
9931/// nothing.
9932static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9933 while (S->isClassScope() ||
9934 (LangOpts.CPlusPlus &&
9936 ((S->getFlags() & Scope::DeclScope) == 0) ||
9937 (S->getEntity() && S->getEntity()->isTransparentContext()))
9938 S = S->getParent();
9939 return S;
9940}
9941
9942/// Determine whether a declaration matches a known function in namespace std.
9944 unsigned BuiltinID) {
9945 switch (BuiltinID) {
9946 case Builtin::BI__GetExceptionInfo:
9947 // No type checking whatsoever.
9948 return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
9949
9950 case Builtin::BIaddressof:
9951 case Builtin::BI__addressof:
9952 case Builtin::BIforward:
9953 case Builtin::BIforward_like:
9954 case Builtin::BImove:
9955 case Builtin::BImove_if_noexcept:
9956 case Builtin::BIas_const: {
9957 // Ensure that we don't treat the algorithm
9958 // OutputIt std::move(InputIt, InputIt, OutputIt)
9959 // as the builtin std::move.
9960 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9961 return FPT->getNumParams() == 1 && !FPT->isVariadic();
9962 }
9963
9964 default:
9965 return false;
9966 }
9967}
9968
9969NamedDecl*
9972 MultiTemplateParamsArg TemplateParamListsRef,
9973 bool &AddToScope) {
9974 QualType R = TInfo->getType();
9975
9976 assert(R->isFunctionType());
9978 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9979
9980 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9981 llvm::append_range(TemplateParamLists, TemplateParamListsRef);
9983 if (!TemplateParamLists.empty() && !TemplateParamLists.back()->empty() &&
9984 Invented->getDepth() == TemplateParamLists.back()->getDepth())
9985 TemplateParamLists.back() = Invented;
9986 else
9987 TemplateParamLists.push_back(Invented);
9988 }
9989
9990 // TODO: consider using NameInfo for diagnostic.
9992 DeclarationName Name = NameInfo.getName();
9994
9997 diag::err_invalid_thread)
9999
10004
10005 bool isFriend = false;
10007 bool isMemberSpecialization = false;
10008 bool isFunctionTemplateSpecialization = false;
10009
10010 bool HasExplicitTemplateArgs = false;
10011 TemplateArgumentListInfo TemplateArgs;
10012
10013 bool isVirtualOkay = false;
10014
10015 DeclContext *OriginalDC = DC;
10016 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
10017
10018 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
10019 isVirtualOkay);
10020 if (!NewFD) return nullptr;
10021
10022 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
10024
10025 // Set the lexical context. If this is a function-scope declaration, or has a
10026 // C++ scope specifier, or is the object of a friend declaration, the lexical
10027 // context will be different from the semantic context.
10029
10030 if (IsLocalExternDecl)
10031 NewFD->setLocalExternDecl();
10032
10033 if (getLangOpts().CPlusPlus) {
10034 // The rules for implicit inlines changed in C++20 for methods and friends
10035 // with an in-class definition (when such a definition is not attached to
10036 // the global module). This does not affect declarations that are already
10037 // inline (whether explicitly or implicitly by being declared constexpr,
10038 // consteval, etc).
10039 // FIXME: We need a better way to separate C++ standard and clang modules.
10040 bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
10041 !NewFD->getOwningModule() ||
10042 NewFD->isFromGlobalModule() ||
10044 bool isInline = D.getDeclSpec().isInlineSpecified();
10045 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10046 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
10047 isFriend = D.getDeclSpec().isFriendSpecified();
10048 if (ImplicitInlineCXX20 && isFriend && D.isFunctionDefinition()) {
10049 // Pre-C++20 [class.friend]p5
10050 // A function can be defined in a friend declaration of a
10051 // class . . . . Such a function is implicitly inline.
10052 // Post C++20 [class.friend]p7
10053 // Such a function is implicitly an inline function if it is attached
10054 // to the global module.
10055 NewFD->setImplicitlyInline();
10056 }
10057
10058 // If this is a method defined in an __interface, and is not a constructor
10059 // or an overloaded operator, then set the pure flag (isVirtual will already
10060 // return true).
10061 if (const CXXRecordDecl *Parent =
10062 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
10063 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
10064 NewFD->setIsPureVirtual(true);
10065
10066 // C++ [class.union]p2
10067 // A union can have member functions, but not virtual functions.
10068 if (isVirtual && Parent->isUnion()) {
10069 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
10070 NewFD->setInvalidDecl();
10071 }
10072 if ((Parent->isClass() || Parent->isStruct()) &&
10073 Parent->hasAttr<SYCLSpecialClassAttr>() &&
10074 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
10075 NewFD->getName() == "__init" && D.isFunctionDefinition()) {
10076 if (auto *Def = Parent->getDefinition())
10077 Def->setInitMethod(true);
10078 }
10079 }
10080
10081 SetNestedNameSpecifier(*this, NewFD, D);
10082 isMemberSpecialization = false;
10083 isFunctionTemplateSpecialization = false;
10084 if (D.isInvalidType())
10085 NewFD->setInvalidDecl();
10086
10087 // Match up the template parameter lists with the scope specifier, then
10088 // determine whether we have a template or a template specialization.
10089 bool Invalid = false;
10090 TemplateIdAnnotation *TemplateId =
10092 ? D.getName().TemplateId
10093 : nullptr;
10094 TemplateParameterList *TemplateParams =
10097 D.getCXXScopeSpec(), TemplateId, TemplateParamLists, isFriend,
10098 isMemberSpecialization, Invalid);
10099 if (TemplateParams) {
10100 // Check that we can declare a template here.
10101 if (CheckTemplateDeclScope(S, TemplateParams))
10102 NewFD->setInvalidDecl();
10103
10104 if (TemplateParams->size() > 0) {
10105 // This is a function template
10106
10107 // A destructor cannot be a template.
10109 Diag(NewFD->getLocation(), diag::err_destructor_template);
10110 NewFD->setInvalidDecl();
10111 // Function template with explicit template arguments.
10112 } else if (TemplateId) {
10113 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
10114 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
10115 NewFD->setInvalidDecl();
10116 }
10117
10118 // If we're adding a template to a dependent context, we may need to
10119 // rebuilding some of the types used within the template parameter list,
10120 // now that we know what the current instantiation is.
10121 if (DC->isDependentContext()) {
10122 ContextRAII SavedContext(*this, DC);
10124 Invalid = true;
10125 }
10126
10128 NewFD->getLocation(),
10129 Name, TemplateParams,
10130 NewFD);
10131 FunctionTemplate->setLexicalDeclContext(CurContext);
10133
10134 // For source fidelity, store the other template param lists.
10135 if (TemplateParamLists.size() > 1) {
10137 ArrayRef<TemplateParameterList *>(TemplateParamLists)
10138 .drop_back(1));
10139 }
10140 } else {
10141 // This is a function template specialization.
10142 isFunctionTemplateSpecialization = true;
10143 // For source fidelity, store all the template param lists.
10144 if (TemplateParamLists.size() > 0)
10145 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
10146
10147 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
10148 if (isFriend) {
10149 // We want to remove the "template<>", found here.
10150 SourceRange RemoveRange = TemplateParams->getSourceRange();
10151
10152 // If we remove the template<> and the name is not a
10153 // template-id, we're actually silently creating a problem:
10154 // the friend declaration will refer to an untemplated decl,
10155 // and clearly the user wants a template specialization. So
10156 // we need to insert '<>' after the name.
10157 SourceLocation InsertLoc;
10159 InsertLoc = D.getName().getSourceRange().getEnd();
10160 InsertLoc = getLocForEndOfToken(InsertLoc);
10161 }
10162
10163 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
10164 << Name << RemoveRange
10165 << FixItHint::CreateRemoval(RemoveRange)
10166 << FixItHint::CreateInsertion(InsertLoc, "<>");
10167 Invalid = true;
10168
10169 // Recover by faking up an empty template argument list.
10170 HasExplicitTemplateArgs = true;
10171 TemplateArgs.setLAngleLoc(InsertLoc);
10172 TemplateArgs.setRAngleLoc(InsertLoc);
10173 }
10174 }
10175 } else {
10176 // Check that we can declare a template here.
10177 if (!TemplateParamLists.empty() && isMemberSpecialization &&
10178 CheckTemplateDeclScope(S, TemplateParamLists.back()))
10179 NewFD->setInvalidDecl();
10180
10181 // All template param lists were matched against the scope specifier:
10182 // this is NOT (an explicit specialization of) a template.
10183 if (TemplateParamLists.size() > 0)
10184 // For source fidelity, store all the template param lists.
10185 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
10186
10187 // "friend void foo<>(int);" is an implicit specialization decl.
10188 if (isFriend && TemplateId)
10189 isFunctionTemplateSpecialization = true;
10190 }
10191
10192 // If this is a function template specialization and the unqualified-id of
10193 // the declarator-id is a template-id, convert the template argument list
10194 // into our AST format and check for unexpanded packs.
10195 if (isFunctionTemplateSpecialization && TemplateId) {
10196 HasExplicitTemplateArgs = true;
10197
10198 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
10199 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
10200 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
10201 TemplateId->NumArgs);
10202 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
10203
10204 // FIXME: Should we check for unexpanded packs if this was an (invalid)
10205 // declaration of a function template partial specialization? Should we
10206 // consider the unexpanded pack context to be a partial specialization?
10207 for (const TemplateArgumentLoc &ArgLoc : TemplateArgs.arguments()) {
10209 ArgLoc, isFriend ? UPPC_FriendDeclaration
10211 NewFD->setInvalidDecl();
10212 }
10213 }
10214
10215 if (Invalid) {
10216 NewFD->setInvalidDecl();
10217 if (FunctionTemplate)
10218 FunctionTemplate->setInvalidDecl();
10219 }
10220
10221 // C++ [dcl.fct.spec]p5:
10222 // The virtual specifier shall only be used in declarations of
10223 // nonstatic class member functions that appear within a
10224 // member-specification of a class declaration; see 10.3.
10225 //
10226 if (isVirtual && !NewFD->isInvalidDecl()) {
10227 if (!isVirtualOkay) {
10229 diag::err_virtual_non_function);
10230 } else if (!CurContext->isRecord()) {
10231 // 'virtual' was specified outside of the class.
10233 diag::err_virtual_out_of_class)
10235 } else if (NewFD->getDescribedFunctionTemplate()) {
10236 // C++ [temp.mem]p3:
10237 // A member function template shall not be virtual.
10239 diag::err_virtual_member_function_template)
10241 } else {
10242 // Okay: Add virtual to the method.
10243 NewFD->setVirtualAsWritten(true);
10244 }
10245
10246 if (getLangOpts().CPlusPlus14 &&
10247 NewFD->getReturnType()->isUndeducedType())
10248 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
10249 }
10250
10251 // C++ [dcl.fct.spec]p3:
10252 // The inline specifier shall not appear on a block scope function
10253 // declaration.
10254 if (isInline && !NewFD->isInvalidDecl()) {
10255 if (CurContext->isFunctionOrMethod()) {
10256 // 'inline' is not allowed on block scope function declaration.
10258 diag::err_inline_declaration_block_scope) << Name
10260 }
10261 }
10262
10263 // C++ [dcl.fct.spec]p6:
10264 // The explicit specifier shall be used only in the declaration of a
10265 // constructor or conversion function within its class definition;
10266 // see 12.3.1 and 12.3.2.
10267 if (hasExplicit && !NewFD->isInvalidDecl() &&
10269 if (!CurContext->isRecord()) {
10270 // 'explicit' was specified outside of the class.
10272 diag::err_explicit_out_of_class)
10274 } else if (!isa<CXXConstructorDecl>(NewFD) &&
10275 !isa<CXXConversionDecl>(NewFD)) {
10276 // 'explicit' was specified on a function that wasn't a constructor
10277 // or conversion function.
10279 diag::err_explicit_non_ctor_or_conv_function)
10281 }
10282 }
10283
10285 if (ConstexprKind != ConstexprSpecKind::Unspecified) {
10286 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
10287 // are implicitly inline.
10288 NewFD->setImplicitlyInline();
10289
10290 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
10291 // be either constructors or to return a literal type. Therefore,
10292 // destructors cannot be declared constexpr.
10293 if (isa<CXXDestructorDecl>(NewFD) &&
10295 ConstexprKind == ConstexprSpecKind::Consteval)) {
10296 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
10297 << static_cast<int>(ConstexprKind);
10301 }
10302 // C++20 [dcl.constexpr]p2: An allocation function, or a
10303 // deallocation function shall not be declared with the consteval
10304 // specifier.
10305 if (ConstexprKind == ConstexprSpecKind::Consteval &&
10308 diag::err_invalid_consteval_decl_kind)
10309 << NewFD;
10311 }
10312 }
10313
10314 // If __module_private__ was specified, mark the function accordingly.
10316 if (isFunctionTemplateSpecialization) {
10317 SourceLocation ModulePrivateLoc
10319 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
10320 << 0
10321 << FixItHint::CreateRemoval(ModulePrivateLoc);
10322 } else {
10323 NewFD->setModulePrivate();
10324 if (FunctionTemplate)
10325 FunctionTemplate->setModulePrivate();
10326 }
10327 }
10328
10329 if (isFriend) {
10330 if (FunctionTemplate) {
10331 FunctionTemplate->setObjectOfFriendDecl();
10332 FunctionTemplate->setAccess(AS_public);
10333 }
10334 NewFD->setObjectOfFriendDecl();
10335 NewFD->setAccess(AS_public);
10336 }
10337
10338 // If a function is defined as defaulted or deleted, mark it as such now.
10339 // We'll do the relevant checks on defaulted / deleted functions later.
10340 switch (D.getFunctionDefinitionKind()) {
10343 break;
10344
10346 NewFD->setDefaulted();
10347 break;
10348
10350 NewFD->setDeletedAsWritten();
10351 break;
10352 }
10353
10354 if (ImplicitInlineCXX20 && isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
10356 // Pre C++20 [class.mfct]p2:
10357 // A member function may be defined (8.4) in its class definition, in
10358 // which case it is an inline member function (7.1.2)
10359 // Post C++20 [class.mfct]p1:
10360 // If a member function is attached to the global module and is defined
10361 // in its class definition, it is inline.
10362 NewFD->setImplicitlyInline();
10363 }
10364
10365 if (!isFriend && SC != SC_None) {
10366 // C++ [temp.expl.spec]p2:
10367 // The declaration in an explicit-specialization shall not be an
10368 // export-declaration. An explicit specialization shall not use a
10369 // storage-class-specifier other than thread_local.
10370 //
10371 // We diagnose friend declarations with storage-class-specifiers
10372 // elsewhere.
10373 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10375 diag::ext_explicit_specialization_storage_class)
10378 }
10379
10380 if (SC == SC_Static && !CurContext->isRecord() && DC->isRecord()) {
10381 assert(isa<CXXMethodDecl>(NewFD) &&
10382 "Out-of-line member function should be a CXXMethodDecl");
10383 // C++ [class.static]p1:
10384 // A data or function member of a class may be declared static
10385 // in a class definition, in which case it is a static member of
10386 // the class.
10387
10388 // Complain about the 'static' specifier if it's on an out-of-line
10389 // member function definition.
10390
10391 // MSVC permits the use of a 'static' storage specifier on an
10392 // out-of-line member function template declaration and class member
10393 // template declaration (MSVC versions before 2015), warn about this.
10395 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
10396 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
10397 (getLangOpts().MSVCCompat &&
10399 ? diag::ext_static_out_of_line
10400 : diag::err_static_out_of_line)
10403 }
10404 }
10405
10406 // C++11 [except.spec]p15:
10407 // A deallocation function with no exception-specification is treated
10408 // as if it were specified with noexcept(true).
10409 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10410 if (Name.isAnyOperatorDelete() && getLangOpts().CPlusPlus11 && FPT &&
10411 !FPT->hasExceptionSpec())
10412 NewFD->setType(Context.getFunctionType(
10413 FPT->getReturnType(), FPT->getParamTypes(),
10415
10416 // C++20 [dcl.inline]/7
10417 // If an inline function or variable that is attached to a named module
10418 // is declared in a definition domain, it shall be defined in that
10419 // domain.
10420 // So, if the current declaration does not have a definition, we must
10421 // check at the end of the TU (or when the PMF starts) to see that we
10422 // have a definition at that point.
10423 if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
10424 NewFD->isInNamedModule()) {
10425 PendingInlineFuncDecls.insert(NewFD);
10426 }
10427 }
10428
10429 // Filter out previous declarations that don't match the scope.
10432 isMemberSpecialization ||
10433 isFunctionTemplateSpecialization);
10434
10435 // Handle GNU asm-label extension (encoded as an attribute).
10436 if (Expr *E = D.getAsmLabel()) {
10437 // The parser guarantees this is a string.
10439 NewFD->addAttr(
10440 AsmLabelAttr::Create(Context, SE->getString(), SE->getStrTokenLoc(0)));
10441 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10442 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
10444 if (I != ExtnameUndeclaredIdentifiers.end()) {
10445 if (isDeclExternC(NewFD)) {
10446 NewFD->addAttr(I->second);
10448 } else
10449 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
10450 << /*Variable*/0 << NewFD;
10451 }
10452 }
10453
10454 // Copy the parameter declarations from the declarator D to the function
10455 // declaration NewFD, if they are available. First scavenge them into Params.
10457 unsigned FTIIdx;
10458 if (D.isFunctionDeclarator(FTIIdx)) {
10460
10461 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10462 // function that takes no arguments, not a function that takes a
10463 // single void argument.
10464 // We let through "const void" here because Sema::GetTypeForDeclarator
10465 // already checks for that case.
10466 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10467 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10468 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
10469 assert(Param->getDeclContext() != NewFD && "Was set before ?");
10470 Param->setDeclContext(NewFD);
10471 Params.push_back(Param);
10472
10473 if (Param->isInvalidDecl())
10474 NewFD->setInvalidDecl();
10475 }
10476 }
10477
10478 if (!getLangOpts().CPlusPlus) {
10479 // In C, find all the tag declarations from the prototype and move them
10480 // into the function DeclContext. Remove them from the surrounding tag
10481 // injection context of the function, which is typically but not always
10482 // the TU.
10483 DeclContext *PrototypeTagContext =
10485 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10486 auto *TD = dyn_cast<TagDecl>(NonParmDecl);
10487
10488 // We don't want to reparent enumerators. Look at their parent enum
10489 // instead.
10490 if (!TD) {
10491 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
10492 TD = cast<EnumDecl>(ECD->getDeclContext());
10493 }
10494 if (!TD)
10495 continue;
10496 DeclContext *TagDC = TD->getLexicalDeclContext();
10497 if (!TagDC->containsDecl(TD))
10498 continue;
10499 TagDC->removeDecl(TD);
10500 TD->setDeclContext(NewFD);
10501 NewFD->addDecl(TD);
10502
10503 // Preserve the lexical DeclContext if it is not the surrounding tag
10504 // injection context of the FD. In this example, the semantic context of
10505 // E will be f and the lexical context will be S, while both the
10506 // semantic and lexical contexts of S will be f:
10507 // void f(struct S { enum E { a } f; } s);
10508 if (TagDC != PrototypeTagContext)
10509 TD->setLexicalDeclContext(TagDC);
10510 }
10511 }
10512 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10513 // When we're declaring a function with a typedef, typeof, etc as in the
10514 // following example, we'll need to synthesize (unnamed)
10515 // parameters for use in the declaration.
10516 //
10517 // @code
10518 // typedef void fn(int);
10519 // fn f;
10520 // @endcode
10521
10522 // Synthesize a parameter for each argument type.
10523 for (const auto &AI : FT->param_types()) {
10524 ParmVarDecl *Param =
10526 Param->setScopeInfo(0, Params.size());
10527 Params.push_back(Param);
10528 }
10529 } else {
10530 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10531 "Should not need args for typedef of non-prototype fn");
10532 }
10533
10534 // Finally, we know we have the right number of parameters, install them.
10535 NewFD->setParams(Params);
10536
10537 // If this declarator is a declaration and not a definition, its parameters
10538 // will not be pushed onto a scope chain. That means we will not issue any
10539 // reserved identifier warnings for the declaration, but we will for the
10540 // definition. Handle those here.
10541 if (!D.isFunctionDefinition()) {
10542 for (const ParmVarDecl *PVD : Params)
10544 }
10545
10547 NewFD->addAttr(
10548 C11NoReturnAttr::Create(Context, D.getDeclSpec().getNoreturnSpecLoc()));
10549
10550 // Functions returning a variably modified type violate C99 6.7.5.2p2
10551 // because all functions have linkage.
10552 if (!NewFD->isInvalidDecl() &&
10554 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
10555 NewFD->setInvalidDecl();
10556 }
10557
10558 // Apply an implicit SectionAttr if '#pragma clang section text' is active
10560 !NewFD->hasAttr<SectionAttr>())
10561 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
10562 Context, PragmaClangTextSection.SectionName,
10563 PragmaClangTextSection.PragmaLocation));
10564
10565 // Apply an implicit SectionAttr if #pragma code_seg is active.
10566 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10567 !NewFD->hasAttr<SectionAttr>()) {
10568 NewFD->addAttr(SectionAttr::CreateImplicit(
10569 Context, CodeSegStack.CurrentValue->getString(),
10570 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate));
10571 if (UnifySection(CodeSegStack.CurrentValue->getString(),
10574 NewFD))
10575 NewFD->dropAttr<SectionAttr>();
10576 }
10577
10578 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10579 // active.
10580 if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() &&
10581 !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10582 NewFD->addAttr(StrictGuardStackCheckAttr::CreateImplicit(
10583 Context, PragmaClangTextSection.PragmaLocation));
10584
10585 // Apply an implicit CodeSegAttr from class declspec or
10586 // apply an implicit SectionAttr from #pragma code_seg if active.
10587 if (!NewFD->hasAttr<CodeSegAttr>()) {
10589 D.isFunctionDefinition())) {
10590 NewFD->addAttr(SAttr);
10591 }
10592 }
10593
10594 // Handle attributes.
10595 ProcessDeclAttributes(S, NewFD, D);
10596 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10597 if (Context.getTargetInfo().getTriple().isAArch64() && NewTVA &&
10598 !NewTVA->isDefaultVersion() &&
10599 !Context.getTargetInfo().hasFeature("fmv")) {
10600 // Don't add to scope fmv functions declarations if fmv disabled
10601 AddToScope = false;
10602 return NewFD;
10603 }
10604
10605 if (getLangOpts().OpenCL || getLangOpts().HLSL) {
10606 // Neither OpenCL nor HLSL allow an address space qualifyer on a return
10607 // type.
10608 //
10609 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10610 // type declaration will generate a compilation error.
10611 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10612 if (AddressSpace != LangAS::Default) {
10613 Diag(NewFD->getLocation(), diag::err_return_value_with_address_space);
10614 NewFD->setInvalidDecl();
10615 }
10616 }
10617
10618 if (!getLangOpts().CPlusPlus) {
10619 // Perform semantic checking on the function declaration.
10620 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10621 CheckMain(NewFD, D.getDeclSpec());
10622
10623 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10624 CheckMSVCRTEntryPoint(NewFD);
10625
10626 if (!NewFD->isInvalidDecl())
10628 isMemberSpecialization,
10630 else if (!Previous.empty())
10631 // Recover gracefully from an invalid redeclaration.
10632 D.setRedeclaration(true);
10633 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10634 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
10635 "previous declaration set still overloaded");
10636
10637 // Diagnose no-prototype function declarations with calling conventions that
10638 // don't support variadic calls. Only do this in C and do it after merging
10639 // possibly prototyped redeclarations.
10640 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10642 CallingConv CC = FT->getExtInfo().getCC();
10643 if (!supportsVariadicCall(CC)) {
10644 // Windows system headers sometimes accidentally use stdcall without
10645 // (void) parameters, so we relax this to a warning.
10646 int DiagID =
10647 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10648 Diag(NewFD->getLocation(), DiagID)
10650 }
10651 }
10652
10656 NewFD->getReturnType(), NewFD->getReturnTypeSourceRange().getBegin(),
10658 } else {
10659 // C++11 [replacement.functions]p3:
10660 // The program's definitions shall not be specified as inline.
10661 //
10662 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10663 //
10664 // Suppress the diagnostic if the function is __attribute__((used)), since
10665 // that forces an external definition to be emitted.
10666 if (D.getDeclSpec().isInlineSpecified() &&
10668 !NewFD->hasAttr<UsedAttr>())
10670 diag::ext_operator_new_delete_declared_inline)
10671 << NewFD->getDeclName();
10672
10673 if (const Expr *TRC = NewFD->getTrailingRequiresClause().ConstraintExpr) {
10674 // C++20 [dcl.decl.general]p4:
10675 // The optional requires-clause in an init-declarator or
10676 // member-declarator shall be present only if the declarator declares a
10677 // templated function.
10678 //
10679 // C++20 [temp.pre]p8:
10680 // An entity is templated if it is
10681 // - a template,
10682 // - an entity defined or created in a templated entity,
10683 // - a member of a templated entity,
10684 // - an enumerator for an enumeration that is a templated entity, or
10685 // - the closure type of a lambda-expression appearing in the
10686 // declaration of a templated entity.
10687 //
10688 // [Note 6: A local class, a local or block variable, or a friend
10689 // function defined in a templated entity is a templated entity.
10690 // — end note]
10691 //
10692 // A templated function is a function template or a function that is
10693 // templated. A templated class is a class template or a class that is
10694 // templated. A templated variable is a variable template or a variable
10695 // that is templated.
10696 if (!FunctionTemplate) {
10697 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10698 // C++ [temp.expl.spec]p8 (proposed resolution for CWG2847):
10699 // An explicit specialization shall not have a trailing
10700 // requires-clause unless it declares a function template.
10701 //
10702 // Since a friend function template specialization cannot be
10703 // definition, and since a non-template friend declaration with a
10704 // trailing requires-clause must be a definition, we diagnose
10705 // friend function template specializations with trailing
10706 // requires-clauses on the same path as explicit specializations
10707 // even though they aren't necessarily prohibited by the same
10708 // language rule.
10709 Diag(TRC->getBeginLoc(), diag::err_non_temp_spec_requires_clause)
10710 << isFriend;
10711 } else if (isFriend && NewFD->isTemplated() &&
10712 !D.isFunctionDefinition()) {
10713 // C++ [temp.friend]p9:
10714 // A non-template friend declaration with a requires-clause shall be
10715 // a definition.
10716 Diag(NewFD->getBeginLoc(),
10717 diag::err_non_temp_friend_decl_with_requires_clause_must_be_def);
10718 NewFD->setInvalidDecl();
10719 } else if (!NewFD->isTemplated() ||
10720 !(isa<CXXMethodDecl>(NewFD) || D.isFunctionDefinition())) {
10721 Diag(TRC->getBeginLoc(),
10722 diag::err_constrained_non_templated_function);
10723 }
10724 }
10725 }
10726
10727 // We do not add HD attributes to specializations here because
10728 // they may have different constexpr-ness compared to their
10729 // templates and, after maybeAddHostDeviceAttrs() is applied,
10730 // may end up with different effective targets. Instead, a
10731 // specialization inherits its target attributes from its template
10732 // in the CheckFunctionTemplateSpecialization() call below.
10733 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
10735
10736 // Handle explicit specializations of function templates
10737 // and friend function declarations with an explicit
10738 // template argument list.
10739 if (isFunctionTemplateSpecialization) {
10740 bool isDependentSpecialization = false;
10741 if (isFriend) {
10742 // For friend function specializations, this is a dependent
10743 // specialization if its semantic context is dependent, its
10744 // type is dependent, or if its template-id is dependent.
10745 isDependentSpecialization =
10746 DC->isDependentContext() || NewFD->getType()->isDependentType() ||
10747 (HasExplicitTemplateArgs &&
10748 TemplateSpecializationType::
10749 anyInstantiationDependentTemplateArguments(
10750 TemplateArgs.arguments()));
10751 assert((!isDependentSpecialization ||
10752 (HasExplicitTemplateArgs == isDependentSpecialization)) &&
10753 "dependent friend function specialization without template "
10754 "args");
10755 } else {
10756 // For class-scope explicit specializations of function templates,
10757 // if the lexical context is dependent, then the specialization
10758 // is dependent.
10759 isDependentSpecialization =
10760 CurContext->isRecord() && CurContext->isDependentContext();
10761 }
10762
10763 TemplateArgumentListInfo *ExplicitTemplateArgs =
10764 HasExplicitTemplateArgs ? &TemplateArgs : nullptr;
10765 if (isDependentSpecialization) {
10766 // If it's a dependent specialization, it may not be possible
10767 // to determine the primary template (for explicit specializations)
10768 // or befriended declaration (for friends) until the enclosing
10769 // template is instantiated. In such cases, we store the declarations
10770 // found by name lookup and defer resolution until instantiation.
10772 NewFD, ExplicitTemplateArgs, Previous))
10773 NewFD->setInvalidDecl();
10774 } else if (!NewFD->isInvalidDecl()) {
10775 if (CheckFunctionTemplateSpecialization(NewFD, ExplicitTemplateArgs,
10776 Previous))
10777 NewFD->setInvalidDecl();
10778 }
10779 } else if (isMemberSpecialization && !FunctionTemplate) {
10781 NewFD->setInvalidDecl();
10782 }
10783
10784 // Perform semantic checking on the function declaration.
10785 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10786 CheckMain(NewFD, D.getDeclSpec());
10787
10788 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10789 CheckMSVCRTEntryPoint(NewFD);
10790
10791 if (!NewFD->isInvalidDecl())
10793 isMemberSpecialization,
10795 else if (!Previous.empty())
10796 // Recover gracefully from an invalid redeclaration.
10797 D.setRedeclaration(true);
10798
10799 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
10800 !D.isRedeclaration() ||
10801 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
10802 "previous declaration set still overloaded");
10803
10804 NamedDecl *PrincipalDecl = (FunctionTemplate
10806 : NewFD);
10807
10808 if (isFriend && NewFD->getPreviousDecl()) {
10809 AccessSpecifier Access = AS_public;
10810 if (!NewFD->isInvalidDecl())
10811 Access = NewFD->getPreviousDecl()->getAccess();
10812
10813 NewFD->setAccess(Access);
10814 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10815 }
10816
10817 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10819 PrincipalDecl->setNonMemberOperator();
10820
10821 // If we have a function template, check the template parameter
10822 // list. This will check and merge default template arguments.
10823 if (FunctionTemplate) {
10824 FunctionTemplateDecl *PrevTemplate =
10825 FunctionTemplate->getPreviousDecl();
10826 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
10827 PrevTemplate ? PrevTemplate->getTemplateParameters()
10828 : nullptr,
10833 : (D.getCXXScopeSpec().isSet() &&
10834 DC && DC->isRecord() &&
10835 DC->isDependentContext())
10838 }
10839
10840 if (NewFD->isInvalidDecl()) {
10841 // Ignore all the rest of this.
10842 } else if (!D.isRedeclaration()) {
10843 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
10844 AddToScope };
10845 // Fake up an access specifier if it's supposed to be a class member.
10846 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10847 NewFD->setAccess(AS_public);
10848
10849 // Qualified decls generally require a previous declaration.
10850 if (D.getCXXScopeSpec().isSet()) {
10851 // ...with the major exception of templated-scope or
10852 // dependent-scope friend declarations.
10853
10854 // TODO: we currently also suppress this check in dependent
10855 // contexts because (1) the parameter depth will be off when
10856 // matching friend templates and (2) we might actually be
10857 // selecting a friend based on a dependent factor. But there
10858 // are situations where these conditions don't apply and we
10859 // can actually do this check immediately.
10860 //
10861 // Unless the scope is dependent, it's always an error if qualified
10862 // redeclaration lookup found nothing at all. Diagnose that now;
10863 // nothing will diagnose that error later.
10864 if (isFriend &&
10866 (!Previous.empty() && CurContext->isDependentContext()))) {
10867 // ignore these
10868 } else if (NewFD->isCPUDispatchMultiVersion() ||
10869 NewFD->isCPUSpecificMultiVersion()) {
10870 // ignore this, we allow the redeclaration behavior here to create new
10871 // versions of the function.
10872 } else {
10873 // The user tried to provide an out-of-line definition for a
10874 // function that is a member of a class or namespace, but there
10875 // was no such member function declared (C++ [class.mfct]p2,
10876 // C++ [namespace.memdef]p2). For example:
10877 //
10878 // class X {
10879 // void f() const;
10880 // };
10881 //
10882 // void X::f() { } // ill-formed
10883 //
10884 // Complain about this problem, and attempt to suggest close
10885 // matches (e.g., those that differ only in cv-qualifiers and
10886 // whether the parameter types are references).
10887
10889 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
10890 AddToScope = ExtraArgs.AddToScope;
10891 return Result;
10892 }
10893 }
10894
10895 // Unqualified local friend declarations are required to resolve
10896 // to something.
10897 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
10899 *this, Previous, NewFD, ExtraArgs, true, S)) {
10900 AddToScope = ExtraArgs.AddToScope;
10901 return Result;
10902 }
10903 }
10904 } else if (!D.isFunctionDefinition() &&
10905 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
10906 !isFriend && !isFunctionTemplateSpecialization &&
10907 !isMemberSpecialization) {
10908 // An out-of-line member function declaration must also be a
10909 // definition (C++ [class.mfct]p2).
10910 // Note that this is not the case for explicit specializations of
10911 // function templates or member functions of class templates, per
10912 // C++ [temp.expl.spec]p2. We also allow these declarations as an
10913 // extension for compatibility with old SWIG code which likes to
10914 // generate them.
10915 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
10916 << D.getCXXScopeSpec().getRange();
10917 }
10918 }
10919
10920 if (getLangOpts().HLSL && D.isFunctionDefinition()) {
10921 // Any top level function could potentially be specified as an entry.
10922 if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier())
10923 HLSL().ActOnTopLevelFunction(NewFD);
10924
10925 if (NewFD->hasAttr<HLSLShaderAttr>())
10926 HLSL().CheckEntryPoint(NewFD);
10927 }
10928
10929 // If this is the first declaration of a library builtin function, add
10930 // attributes as appropriate.
10931 if (!D.isRedeclaration()) {
10932 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
10933 if (unsigned BuiltinID = II->getBuiltinID()) {
10934 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);
10935 if (!InStdNamespace &&
10937 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
10938 // Validate the type matches unless this builtin is specified as
10939 // matching regardless of its declared type.
10940 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
10941 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10942 } else {
10944 LookupNecessaryTypesForBuiltin(S, BuiltinID);
10945 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
10946
10947 if (!Error && !BuiltinType.isNull() &&
10948 Context.hasSameFunctionTypeIgnoringExceptionSpec(
10949 NewFD->getType(), BuiltinType))
10950 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10951 }
10952 }
10953 } else if (InStdNamespace && NewFD->isInStdNamespace() &&
10954 isStdBuiltin(Context, NewFD, BuiltinID)) {
10955 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10956 }
10957 }
10958 }
10959 }
10960
10961 ProcessPragmaWeak(S, NewFD);
10962 checkAttributesAfterMerging(*this, *NewFD);
10963
10965
10966 if (NewFD->hasAttr<OverloadableAttr>() &&
10967 !NewFD->getType()->getAs<FunctionProtoType>()) {
10968 Diag(NewFD->getLocation(),
10969 diag::err_attribute_overloadable_no_prototype)
10970 << NewFD;
10971 NewFD->dropAttr<OverloadableAttr>();
10972 }
10973
10974 // If there's a #pragma GCC visibility in scope, and this isn't a class
10975 // member, set the visibility of this function.
10976 if (!DC->isRecord() && NewFD->isExternallyVisible())
10978
10979 // If there's a #pragma clang arc_cf_code_audited in scope, consider
10980 // marking the function.
10981 ObjC().AddCFAuditedAttribute(NewFD);
10982
10983 // If this is a function definition, check if we have to apply any
10984 // attributes (i.e. optnone and no_builtin) due to a pragma.
10985 if (D.isFunctionDefinition()) {
10986 AddRangeBasedOptnone(NewFD);
10988 AddSectionMSAllocText(NewFD);
10990 }
10991
10992 // If this is the first declaration of an extern C variable, update
10993 // the map of such variables.
10994 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
10995 isIncompleteDeclExternC(*this, NewFD))
10997
10998 // Set this FunctionDecl's range up to the right paren.
10999 NewFD->setRangeEnd(D.getSourceRange().getEnd());
11000
11001 if (D.isRedeclaration() && !Previous.empty()) {
11002 NamedDecl *Prev = Previous.getRepresentativeDecl();
11003 checkDLLAttributeRedeclaration(*this, Prev, NewFD,
11004 isMemberSpecialization ||
11005 isFunctionTemplateSpecialization,
11007 }
11008
11009 if (getLangOpts().CUDA) {
11010 IdentifierInfo *II = NewFD->getIdentifier();
11011 if (II && II->isStr(CUDA().getConfigureFuncName()) &&
11012 !NewFD->isInvalidDecl() &&
11015 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
11017 Context.setcudaConfigureCallDecl(NewFD);
11018 }
11019
11020 // Variadic functions, other than a *declaration* of printf, are not allowed
11021 // in device-side CUDA code, unless someone passed
11022 // -fcuda-allow-variadic-functions.
11023 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
11024 (NewFD->hasAttr<CUDADeviceAttr>() ||
11025 NewFD->hasAttr<CUDAGlobalAttr>()) &&
11026 !(II && II->isStr("printf") && NewFD->isExternC() &&
11027 !D.isFunctionDefinition())) {
11028 Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
11029 }
11030 }
11031
11033
11034 if (getLangOpts().OpenCL && NewFD->hasAttr<DeviceKernelAttr>()) {
11035 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
11036 if (SC == SC_Static) {
11037 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
11038 D.setInvalidType();
11039 }
11040
11041 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
11042 if (!NewFD->getReturnType()->isVoidType()) {
11043 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
11044 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
11045 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
11046 : FixItHint());
11047 D.setInvalidType();
11048 }
11049
11051 for (auto *Param : NewFD->parameters())
11052 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
11053
11054 if (getLangOpts().OpenCLCPlusPlus) {
11055 if (DC->isRecord()) {
11056 Diag(D.getIdentifierLoc(), diag::err_method_kernel);
11057 D.setInvalidType();
11058 }
11059 if (FunctionTemplate) {
11060 Diag(D.getIdentifierLoc(), diag::err_template_kernel);
11061 D.setInvalidType();
11062 }
11063 }
11064 }
11065
11066 if (getLangOpts().CPlusPlus) {
11067 // Precalculate whether this is a friend function template with a constraint
11068 // that depends on an enclosing template, per [temp.friend]p9.
11069 if (isFriend && FunctionTemplate &&
11072
11073 // C++ [temp.friend]p9:
11074 // A friend function template with a constraint that depends on a
11075 // template parameter from an enclosing template shall be a definition.
11076 if (!D.isFunctionDefinition()) {
11077 Diag(NewFD->getBeginLoc(),
11078 diag::err_friend_decl_with_enclosing_temp_constraint_must_be_def);
11079 NewFD->setInvalidDecl();
11080 }
11081 }
11082
11083 if (FunctionTemplate) {
11084 if (NewFD->isInvalidDecl())
11085 FunctionTemplate->setInvalidDecl();
11086 return FunctionTemplate;
11087 }
11088
11089 if (isMemberSpecialization && !NewFD->isInvalidDecl())
11091 }
11092
11093 for (const ParmVarDecl *Param : NewFD->parameters()) {
11094 QualType PT = Param->getType();
11095
11096 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
11097 // types.
11098 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
11099 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
11100 QualType ElemTy = PipeTy->getElementType();
11101 if (ElemTy->isPointerOrReferenceType()) {
11102 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type);
11103 D.setInvalidType();
11104 }
11105 }
11106 }
11107 // WebAssembly tables can't be used as function parameters.
11108 if (Context.getTargetInfo().getTriple().isWasm()) {
11110 Diag(Param->getTypeSpecStartLoc(),
11111 diag::err_wasm_table_as_function_parameter);
11112 D.setInvalidType();
11113 }
11114 }
11115 }
11116
11117 // Diagnose availability attributes. Availability cannot be used on functions
11118 // that are run during load/unload.
11119 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
11120 if (NewFD->hasAttr<ConstructorAttr>()) {
11121 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
11122 << 1;
11123 NewFD->dropAttr<AvailabilityAttr>();
11124 }
11125 if (NewFD->hasAttr<DestructorAttr>()) {
11126 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
11127 << 2;
11128 NewFD->dropAttr<AvailabilityAttr>();
11129 }
11130 }
11131
11132 // Diagnose no_builtin attribute on function declaration that are not a
11133 // definition.
11134 // FIXME: We should really be doing this in
11135 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
11136 // the FunctionDecl and at this point of the code
11137 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
11138 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11139 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
11140 switch (D.getFunctionDefinitionKind()) {
11143 Diag(NBA->getLocation(),
11144 diag::err_attribute_no_builtin_on_defaulted_deleted_function)
11145 << NBA->getSpelling();
11146 break;
11148 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
11149 << NBA->getSpelling();
11150 break;
11152 break;
11153 }
11154
11155 // Similar to no_builtin logic above, at this point of the code
11156 // FunctionDecl::isThisDeclarationADefinition() always returns `false`
11157 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11158 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
11159 !NewFD->isInvalidDecl() &&
11161 ExternalDeclarations.push_back(NewFD);
11162
11163 // Used for a warning on the 'next' declaration when used with a
11164 // `routine(name)`.
11165 if (getLangOpts().OpenACC)
11167
11168 return NewFD;
11169}
11170
11171/// Return a CodeSegAttr from a containing class. The Microsoft docs say
11172/// when __declspec(code_seg) "is applied to a class, all member functions of
11173/// the class and nested classes -- this includes compiler-generated special
11174/// member functions -- are put in the specified segment."
11175/// The actual behavior is a little more complicated. The Microsoft compiler
11176/// won't check outer classes if there is an active value from #pragma code_seg.
11177/// The CodeSeg is always applied from the direct parent but only from outer
11178/// classes when the #pragma code_seg stack is empty. See:
11179/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
11180/// available since MS has removed the page.
11182 const auto *Method = dyn_cast<CXXMethodDecl>(FD);
11183 if (!Method)
11184 return nullptr;
11185 const CXXRecordDecl *Parent = Method->getParent();
11186 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11187 Attr *NewAttr = SAttr->clone(S.getASTContext());
11188 NewAttr->setImplicit(true);
11189 return NewAttr;
11190 }
11191
11192 // The Microsoft compiler won't check outer classes for the CodeSeg
11193 // when the #pragma code_seg stack is active.
11194 if (S.CodeSegStack.CurrentValue)
11195 return nullptr;
11196
11197 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
11198 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11199 Attr *NewAttr = SAttr->clone(S.getASTContext());
11200 NewAttr->setImplicit(true);
11201 return NewAttr;
11202 }
11203 }
11204 return nullptr;
11205}
11206
11208 bool IsDefinition) {
11209 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
11210 return A;
11211 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
11212 CodeSegStack.CurrentValue)
11213 return SectionAttr::CreateImplicit(
11214 getASTContext(), CodeSegStack.CurrentValue->getString(),
11215 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate);
11216 return nullptr;
11217}
11218
11220 QualType NewT, QualType OldT) {
11222 return true;
11223
11224 // For dependently-typed local extern declarations and friends, we can't
11225 // perform a correct type check in general until instantiation:
11226 //
11227 // int f();
11228 // template<typename T> void g() { T f(); }
11229 //
11230 // (valid if g() is only instantiated with T = int).
11231 if (NewT->isDependentType() &&
11232 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
11233 return false;
11234
11235 // Similarly, if the previous declaration was a dependent local extern
11236 // declaration, we don't really know its type yet.
11237 if (OldT->isDependentType() && OldD->isLocalExternDecl())
11238 return false;
11239
11240 return true;
11241}
11242
11245 return true;
11246
11247 // Don't chain dependent friend function definitions until instantiation, to
11248 // permit cases like
11249 //
11250 // void func();
11251 // template<typename T> class C1 { friend void func() {} };
11252 // template<typename T> class C2 { friend void func() {} };
11253 //
11254 // ... which is valid if only one of C1 and C2 is ever instantiated.
11255 //
11256 // FIXME: This need only apply to function definitions. For now, we proxy
11257 // this by checking for a file-scope function. We do not want this to apply
11258 // to friend declarations nominating member functions, because that gets in
11259 // the way of access checks.
11261 return false;
11262
11263 auto *VD = dyn_cast<ValueDecl>(D);
11264 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
11265 return !VD || !PrevVD ||
11266 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
11267 PrevVD->getType());
11268}
11269
11270/// Check the target or target_version attribute of the function for
11271/// MultiVersion validity.
11272///
11273/// Returns true if there was an error, false otherwise.
11274static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
11275 const auto *TA = FD->getAttr<TargetAttr>();
11276 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11277
11278 assert((TA || TVA) && "Expecting target or target_version attribute");
11279
11281 enum ErrType { Feature = 0, Architecture = 1 };
11282
11283 if (TA) {
11284 ParsedTargetAttr ParseInfo =
11285 S.getASTContext().getTargetInfo().parseTargetAttr(TA->getFeaturesStr());
11286 if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(ParseInfo.CPU)) {
11287 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11288 << Architecture << ParseInfo.CPU;
11289 return true;
11290 }
11291 for (const auto &Feat : ParseInfo.Features) {
11292 auto BareFeat = StringRef{Feat}.substr(1);
11293 if (Feat[0] == '-') {
11294 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11295 << Feature << ("no-" + BareFeat).str();
11296 return true;
11297 }
11298
11299 if (!TargetInfo.validateCpuSupports(BareFeat) ||
11300 !TargetInfo.isValidFeatureName(BareFeat) ||
11301 (BareFeat != "default" && TargetInfo.getFMVPriority(BareFeat) == 0)) {
11302 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11303 << Feature << BareFeat;
11304 return true;
11305 }
11306 }
11307 }
11308
11309 if (TVA) {
11311 ParsedTargetAttr ParseInfo;
11312 if (S.getASTContext().getTargetInfo().getTriple().isRISCV()) {
11313 ParseInfo =
11314 S.getASTContext().getTargetInfo().parseTargetAttr(TVA->getName());
11315 for (auto &Feat : ParseInfo.Features)
11316 Feats.push_back(StringRef{Feat}.substr(1));
11317 } else {
11318 assert(S.getASTContext().getTargetInfo().getTriple().isAArch64());
11319 TVA->getFeatures(Feats);
11320 }
11321 for (const auto &Feat : Feats) {
11322 if (!TargetInfo.validateCpuSupports(Feat)) {
11323 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11324 << Feature << Feat;
11325 return true;
11326 }
11327 }
11328 }
11329 return false;
11330}
11331
11332// Provide a white-list of attributes that are allowed to be combined with
11333// multiversion functions.
11335 MultiVersionKind MVKind) {
11336 // Note: this list/diagnosis must match the list in
11337 // checkMultiversionAttributesAllSame.
11338 switch (Kind) {
11339 default:
11340 return false;
11341 case attr::ArmLocallyStreaming:
11342 return MVKind == MultiVersionKind::TargetVersion ||
11344 case attr::Used:
11345 return MVKind == MultiVersionKind::Target;
11346 case attr::NonNull:
11347 case attr::NoThrow:
11348 return true;
11349 }
11350}
11351
11353 const FunctionDecl *FD,
11354 const FunctionDecl *CausedFD,
11355 MultiVersionKind MVKind) {
11356 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
11357 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
11358 << static_cast<unsigned>(MVKind) << A;
11359 if (CausedFD)
11360 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
11361 return true;
11362 };
11363
11364 for (const Attr *A : FD->attrs()) {
11365 switch (A->getKind()) {
11366 case attr::CPUDispatch:
11367 case attr::CPUSpecific:
11368 if (MVKind != MultiVersionKind::CPUDispatch &&
11370 return Diagnose(S, A);
11371 break;
11372 case attr::Target:
11373 if (MVKind != MultiVersionKind::Target)
11374 return Diagnose(S, A);
11375 break;
11376 case attr::TargetVersion:
11377 if (MVKind != MultiVersionKind::TargetVersion &&
11379 return Diagnose(S, A);
11380 break;
11381 case attr::TargetClones:
11382 if (MVKind != MultiVersionKind::TargetClones &&
11384 return Diagnose(S, A);
11385 break;
11386 default:
11387 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
11388 return Diagnose(S, A);
11389 break;
11390 }
11391 }
11392 return false;
11393}
11394
11396 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11397 const PartialDiagnostic &NoProtoDiagID,
11398 const PartialDiagnosticAt &NoteCausedDiagIDAt,
11399 const PartialDiagnosticAt &NoSupportDiagIDAt,
11400 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11401 bool ConstexprSupported, bool CLinkageMayDiffer) {
11402 enum DoesntSupport {
11403 FuncTemplates = 0,
11404 VirtFuncs = 1,
11405 DeducedReturn = 2,
11406 Constructors = 3,
11407 Destructors = 4,
11408 DeletedFuncs = 5,
11409 DefaultedFuncs = 6,
11410 ConstexprFuncs = 7,
11411 ConstevalFuncs = 8,
11412 Lambda = 9,
11413 };
11414 enum Different {
11415 CallingConv = 0,
11416 ReturnType = 1,
11417 ConstexprSpec = 2,
11418 InlineSpec = 3,
11419 Linkage = 4,
11420 LanguageLinkage = 5,
11421 };
11422
11423 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
11424 !OldFD->getType()->getAs<FunctionProtoType>()) {
11425 Diag(OldFD->getLocation(), NoProtoDiagID);
11426 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
11427 return true;
11428 }
11429
11430 if (NoProtoDiagID.getDiagID() != 0 &&
11431 !NewFD->getType()->getAs<FunctionProtoType>())
11432 return Diag(NewFD->getLocation(), NoProtoDiagID);
11433
11434 if (!TemplatesSupported &&
11436 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11437 << FuncTemplates;
11438
11439 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
11440 if (NewCXXFD->isVirtual())
11441 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11442 << VirtFuncs;
11443
11444 if (isa<CXXConstructorDecl>(NewCXXFD))
11445 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11446 << Constructors;
11447
11448 if (isa<CXXDestructorDecl>(NewCXXFD))
11449 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11450 << Destructors;
11451 }
11452
11453 if (NewFD->isDeleted())
11454 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11455 << DeletedFuncs;
11456
11457 if (NewFD->isDefaulted())
11458 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11459 << DefaultedFuncs;
11460
11461 if (!ConstexprSupported && NewFD->isConstexpr())
11462 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11463 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11464
11465 QualType NewQType = Context.getCanonicalType(NewFD->getType());
11466 const auto *NewType = cast<FunctionType>(NewQType);
11467 QualType NewReturnType = NewType->getReturnType();
11468
11469 if (NewReturnType->isUndeducedType())
11470 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11471 << DeducedReturn;
11472
11473 // Ensure the return type is identical.
11474 if (OldFD) {
11475 QualType OldQType = Context.getCanonicalType(OldFD->getType());
11476 const auto *OldType = cast<FunctionType>(OldQType);
11477 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11478 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11479
11480 const auto *OldFPT = OldFD->getType()->getAs<FunctionProtoType>();
11481 const auto *NewFPT = NewFD->getType()->getAs<FunctionProtoType>();
11482
11483 bool ArmStreamingCCMismatched = false;
11484 if (OldFPT && NewFPT) {
11485 unsigned Diff =
11486 OldFPT->getAArch64SMEAttributes() ^ NewFPT->getAArch64SMEAttributes();
11487 // Arm-streaming, arm-streaming-compatible and non-streaming versions
11488 // cannot be mixed.
11491 ArmStreamingCCMismatched = true;
11492 }
11493
11494 if (OldTypeInfo.getCC() != NewTypeInfo.getCC() || ArmStreamingCCMismatched)
11495 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
11496
11497 QualType OldReturnType = OldType->getReturnType();
11498
11499 if (OldReturnType != NewReturnType)
11500 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
11501
11502 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11503 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
11504
11505 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11506 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
11507
11508 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11509 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
11510
11511 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11512 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
11513
11514 if (CheckEquivalentExceptionSpec(OldFPT, OldFD->getLocation(), NewFPT,
11515 NewFD->getLocation()))
11516 return true;
11517 }
11518 return false;
11519}
11520
11522 const FunctionDecl *NewFD,
11523 bool CausesMV,
11524 MultiVersionKind MVKind) {
11526 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
11527 if (OldFD)
11528 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11529 return true;
11530 }
11531
11532 bool IsCPUSpecificCPUDispatchMVKind =
11535
11536 if (CausesMV && OldFD &&
11537 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
11538 return true;
11539
11540 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
11541 return true;
11542
11543 // Only allow transition to MultiVersion if it hasn't been used.
11544 if (OldFD && CausesMV && OldFD->isUsed(false)) {
11545 S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11546 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11547 return true;
11548 }
11549
11551 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
11553 S.PDiag(diag::note_multiversioning_caused_here)),
11555 S.PDiag(diag::err_multiversion_doesnt_support)
11556 << static_cast<unsigned>(MVKind)),
11558 S.PDiag(diag::err_multiversion_diff)),
11559 /*TemplatesSupported=*/false,
11560 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11561 /*CLinkageMayDiffer=*/false);
11562}
11563
11564/// Check the validity of a multiversion function declaration that is the
11565/// first of its kind. Also sets the multiversion'ness' of the function itself.
11566///
11567/// This sets NewFD->isInvalidDecl() to true if there was an error.
11568///
11569/// Returns true if there was an error, false otherwise.
11572 assert(MVKind != MultiVersionKind::None &&
11573 "Function lacks multiversion attribute");
11574 const auto *TA = FD->getAttr<TargetAttr>();
11575 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11576 // The target attribute only causes MV if this declaration is the default,
11577 // otherwise it is treated as a normal function.
11578 if (TA && !TA->isDefaultVersion())
11579 return false;
11580
11581 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11582 FD->setInvalidDecl();
11583 return true;
11584 }
11585
11586 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
11587 FD->setInvalidDecl();
11588 return true;
11589 }
11590
11591 FD->setIsMultiVersion();
11592 return false;
11593}
11594
11596 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11598 return true;
11599 }
11600
11601 return false;
11602}
11603
11605 if (!From->getASTContext().getTargetInfo().getTriple().isAArch64() &&
11606 !From->getASTContext().getTargetInfo().getTriple().isRISCV())
11607 return;
11608
11609 MultiVersionKind MVKindFrom = From->getMultiVersionKind();
11610 MultiVersionKind MVKindTo = To->getMultiVersionKind();
11611
11612 if (MVKindTo == MultiVersionKind::None &&
11613 (MVKindFrom == MultiVersionKind::TargetVersion ||
11614 MVKindFrom == MultiVersionKind::TargetClones))
11615 To->addAttr(TargetVersionAttr::CreateImplicit(
11616 To->getASTContext(), "default", To->getSourceRange()));
11617}
11618
11620 FunctionDecl *NewFD,
11621 bool &Redeclaration,
11622 NamedDecl *&OldDecl,
11624 assert(!OldFD->isMultiVersion() && "Unexpected MultiVersion");
11625
11626 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11627 const auto *OldTA = OldFD->getAttr<TargetAttr>();
11628 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11629 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11630
11631 assert((NewTA || NewTVA) && "Excpecting target or target_version attribute");
11632
11633 // The definitions should be allowed in any order. If we have discovered
11634 // a new target version and the preceeding was the default, then add the
11635 // corresponding attribute to it.
11636 patchDefaultTargetVersion(NewFD, OldFD);
11637
11638 // If the old decl is NOT MultiVersioned yet, and we don't cause that
11639 // to change, this is a simple redeclaration.
11640 if (NewTA && !NewTA->isDefaultVersion() &&
11641 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
11642 return false;
11643
11644 // Otherwise, this decl causes MultiVersioning.
11645 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
11648 NewFD->setInvalidDecl();
11649 return true;
11650 }
11651
11652 if (CheckMultiVersionValue(S, NewFD)) {
11653 NewFD->setInvalidDecl();
11654 return true;
11655 }
11656
11657 // If this is 'default', permit the forward declaration.
11658 if ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
11659 (NewTVA && NewTVA->isDefaultVersion() && !OldTVA)) {
11660 Redeclaration = true;
11661 OldDecl = OldFD;
11662 OldFD->setIsMultiVersion();
11663 NewFD->setIsMultiVersion();
11664 return false;
11665 }
11666
11667 if ((OldTA || OldTVA) && CheckMultiVersionValue(S, OldFD)) {
11668 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11669 NewFD->setInvalidDecl();
11670 return true;
11671 }
11672
11673 if (NewTA) {
11674 ParsedTargetAttr OldParsed =
11676 OldTA->getFeaturesStr());
11677 llvm::sort(OldParsed.Features);
11678 ParsedTargetAttr NewParsed =
11680 NewTA->getFeaturesStr());
11681 // Sort order doesn't matter, it just needs to be consistent.
11682 llvm::sort(NewParsed.Features);
11683 if (OldParsed == NewParsed) {
11684 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11685 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11686 NewFD->setInvalidDecl();
11687 return true;
11688 }
11689 }
11690
11691 for (const auto *FD : OldFD->redecls()) {
11692 const auto *CurTA = FD->getAttr<TargetAttr>();
11693 const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
11694 // We allow forward declarations before ANY multiversioning attributes, but
11695 // nothing after the fact.
11697 ((NewTA && (!CurTA || CurTA->isInherited())) ||
11698 (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
11699 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
11700 << (NewTA ? 0 : 2);
11701 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11702 NewFD->setInvalidDecl();
11703 return true;
11704 }
11705 }
11706
11707 OldFD->setIsMultiVersion();
11708 NewFD->setIsMultiVersion();
11709 Redeclaration = false;
11710 OldDecl = nullptr;
11711 Previous.clear();
11712 return false;
11713}
11714
11716 MultiVersionKind OldKind = Old->getMultiVersionKind();
11717 MultiVersionKind NewKind = New->getMultiVersionKind();
11718
11719 if (OldKind == NewKind || OldKind == MultiVersionKind::None ||
11720 NewKind == MultiVersionKind::None)
11721 return true;
11722
11723 if (Old->getASTContext().getTargetInfo().getTriple().isAArch64()) {
11724 switch (OldKind) {
11726 return NewKind == MultiVersionKind::TargetClones;
11728 return NewKind == MultiVersionKind::TargetVersion;
11729 default:
11730 return false;
11731 }
11732 } else {
11733 switch (OldKind) {
11735 return NewKind == MultiVersionKind::CPUSpecific;
11737 return NewKind == MultiVersionKind::CPUDispatch;
11738 default:
11739 return false;
11740 }
11741 }
11742}
11743
11744/// Check the validity of a new function declaration being added to an existing
11745/// multiversioned declaration collection.
11747 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
11748 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
11749 const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
11751
11752 // Disallow mixing of multiversioning types.
11753 if (!MultiVersionTypesCompatible(OldFD, NewFD)) {
11754 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
11755 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11756 NewFD->setInvalidDecl();
11757 return true;
11758 }
11759
11760 // Add the default target_version attribute if it's missing.
11761 patchDefaultTargetVersion(OldFD, NewFD);
11762 patchDefaultTargetVersion(NewFD, OldFD);
11763
11764 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11765 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11766 MultiVersionKind NewMVKind = NewFD->getMultiVersionKind();
11767 [[maybe_unused]] MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
11768
11769 ParsedTargetAttr NewParsed;
11770 if (NewTA) {
11772 NewTA->getFeaturesStr());
11773 llvm::sort(NewParsed.Features);
11774 }
11776 if (NewTVA) {
11777 NewTVA->getFeatures(NewFeats);
11778 llvm::sort(NewFeats);
11779 }
11780
11781 bool UseMemberUsingDeclRules =
11782 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
11783
11784 bool MayNeedOverloadableChecks =
11786
11787 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
11788 // of a previous member of the MultiVersion set.
11789 for (NamedDecl *ND : Previous) {
11790 FunctionDecl *CurFD = ND->getAsFunction();
11791 if (!CurFD || CurFD->isInvalidDecl())
11792 continue;
11793 if (MayNeedOverloadableChecks &&
11794 S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
11795 continue;
11796
11797 switch (NewMVKind) {
11799 assert(OldMVKind == MultiVersionKind::TargetClones &&
11800 "Only target_clones can be omitted in subsequent declarations");
11801 break;
11803 const auto *CurTA = CurFD->getAttr<TargetAttr>();
11804 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
11805 NewFD->setIsMultiVersion();
11806 Redeclaration = true;
11807 OldDecl = ND;
11808 return false;
11809 }
11810
11811 ParsedTargetAttr CurParsed =
11813 CurTA->getFeaturesStr());
11814 llvm::sort(CurParsed.Features);
11815 if (CurParsed == NewParsed) {
11816 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11817 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11818 NewFD->setInvalidDecl();
11819 return true;
11820 }
11821 break;
11822 }
11824 if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11825 if (CurTVA->getName() == NewTVA->getName()) {
11826 NewFD->setIsMultiVersion();
11827 Redeclaration = true;
11828 OldDecl = ND;
11829 return false;
11830 }
11832 CurTVA->getFeatures(CurFeats);
11833 llvm::sort(CurFeats);
11834
11835 if (CurFeats == NewFeats) {
11836 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11837 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11838 NewFD->setInvalidDecl();
11839 return true;
11840 }
11841 } else if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11842 // Default
11843 if (NewFeats.empty())
11844 break;
11845
11846 for (unsigned I = 0; I < CurClones->featuresStrs_size(); ++I) {
11848 CurClones->getFeatures(CurFeats, I);
11849 llvm::sort(CurFeats);
11850
11851 if (CurFeats == NewFeats) {
11852 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11853 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11854 NewFD->setInvalidDecl();
11855 return true;
11856 }
11857 }
11858 }
11859 break;
11860 }
11862 assert(NewClones && "MultiVersionKind does not match attribute type");
11863 if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11864 if (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
11865 !std::equal(CurClones->featuresStrs_begin(),
11866 CurClones->featuresStrs_end(),
11867 NewClones->featuresStrs_begin())) {
11868 S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
11869 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11870 NewFD->setInvalidDecl();
11871 return true;
11872 }
11873 } else if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11875 CurTVA->getFeatures(CurFeats);
11876 llvm::sort(CurFeats);
11877
11878 // Default
11879 if (CurFeats.empty())
11880 break;
11881
11882 for (unsigned I = 0; I < NewClones->featuresStrs_size(); ++I) {
11883 NewFeats.clear();
11884 NewClones->getFeatures(NewFeats, I);
11885 llvm::sort(NewFeats);
11886
11887 if (CurFeats == NewFeats) {
11888 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11889 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11890 NewFD->setInvalidDecl();
11891 return true;
11892 }
11893 }
11894 break;
11895 }
11896 Redeclaration = true;
11897 OldDecl = CurFD;
11898 NewFD->setIsMultiVersion();
11899 return false;
11900 }
11903 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
11904 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
11905 // Handle CPUDispatch/CPUSpecific versions.
11906 // Only 1 CPUDispatch function is allowed, this will make it go through
11907 // the redeclaration errors.
11908 if (NewMVKind == MultiVersionKind::CPUDispatch &&
11909 CurFD->hasAttr<CPUDispatchAttr>()) {
11910 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
11911 std::equal(
11912 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
11913 NewCPUDisp->cpus_begin(),
11914 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11915 return Cur->getName() == New->getName();
11916 })) {
11917 NewFD->setIsMultiVersion();
11918 Redeclaration = true;
11919 OldDecl = ND;
11920 return false;
11921 }
11922
11923 // If the declarations don't match, this is an error condition.
11924 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
11925 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11926 NewFD->setInvalidDecl();
11927 return true;
11928 }
11929 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
11930 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
11931 std::equal(
11932 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
11933 NewCPUSpec->cpus_begin(),
11934 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11935 return Cur->getName() == New->getName();
11936 })) {
11937 NewFD->setIsMultiVersion();
11938 Redeclaration = true;
11939 OldDecl = ND;
11940 return false;
11941 }
11942
11943 // Only 1 version of CPUSpecific is allowed for each CPU.
11944 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
11945 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
11946 if (CurII == NewII) {
11947 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
11948 << NewII;
11949 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11950 NewFD->setInvalidDecl();
11951 return true;
11952 }
11953 }
11954 }
11955 }
11956 break;
11957 }
11958 }
11959 }
11960
11961 // Else, this is simply a non-redecl case. Checking the 'value' is only
11962 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
11963 // handled in the attribute adding step.
11964 if ((NewTA || NewTVA) && CheckMultiVersionValue(S, NewFD)) {
11965 NewFD->setInvalidDecl();
11966 return true;
11967 }
11968
11969 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
11970 !OldFD->isMultiVersion(), NewMVKind)) {
11971 NewFD->setInvalidDecl();
11972 return true;
11973 }
11974
11975 // Permit forward declarations in the case where these two are compatible.
11976 if (!OldFD->isMultiVersion()) {
11977 OldFD->setIsMultiVersion();
11978 NewFD->setIsMultiVersion();
11979 Redeclaration = true;
11980 OldDecl = OldFD;
11981 return false;
11982 }
11983
11984 NewFD->setIsMultiVersion();
11985 Redeclaration = false;
11986 OldDecl = nullptr;
11987 Previous.clear();
11988 return false;
11989}
11990
11991/// Check the validity of a mulitversion function declaration.
11992/// Also sets the multiversion'ness' of the function itself.
11993///
11994/// This sets NewFD->isInvalidDecl() to true if there was an error.
11995///
11996/// Returns true if there was an error, false otherwise.
11998 bool &Redeclaration, NamedDecl *&OldDecl,
12000 const TargetInfo &TI = S.getASTContext().getTargetInfo();
12001
12002 // Check if FMV is disabled.
12003 if (TI.getTriple().isAArch64() && !TI.hasFeature("fmv"))
12004 return false;
12005
12006 const auto *NewTA = NewFD->getAttr<TargetAttr>();
12007 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
12008 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
12009 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
12010 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
12011 MultiVersionKind MVKind = NewFD->getMultiVersionKind();
12012
12013 // Main isn't allowed to become a multiversion function, however it IS
12014 // permitted to have 'main' be marked with the 'target' optimization hint,
12015 // for 'target_version' only default is allowed.
12016 if (NewFD->isMain()) {
12017 if (MVKind != MultiVersionKind::None &&
12018 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
12019 !(MVKind == MultiVersionKind::TargetVersion &&
12020 NewTVA->isDefaultVersion())) {
12021 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
12022 NewFD->setInvalidDecl();
12023 return true;
12024 }
12025 return false;
12026 }
12027
12028 // Target attribute on AArch64 is not used for multiversioning
12029 if (NewTA && TI.getTriple().isAArch64())
12030 return false;
12031
12032 // Target attribute on RISCV is not used for multiversioning
12033 if (NewTA && TI.getTriple().isRISCV())
12034 return false;
12035
12036 if (!OldDecl || !OldDecl->getAsFunction() ||
12037 !OldDecl->getDeclContext()->getRedeclContext()->Equals(
12038 NewFD->getDeclContext()->getRedeclContext())) {
12039 // If there's no previous declaration, AND this isn't attempting to cause
12040 // multiversioning, this isn't an error condition.
12041 if (MVKind == MultiVersionKind::None)
12042 return false;
12043 return CheckMultiVersionFirstFunction(S, NewFD);
12044 }
12045
12046 FunctionDecl *OldFD = OldDecl->getAsFunction();
12047
12048 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
12049 return false;
12050
12051 // Multiversioned redeclarations aren't allowed to omit the attribute, except
12052 // for target_clones and target_version.
12053 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
12056 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
12058 NewFD->setInvalidDecl();
12059 return true;
12060 }
12061
12062 if (!OldFD->isMultiVersion()) {
12063 switch (MVKind) {
12067 S, OldFD, NewFD, Redeclaration, OldDecl, Previous);
12069 if (OldFD->isUsed(false)) {
12070 NewFD->setInvalidDecl();
12071 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
12072 }
12073 OldFD->setIsMultiVersion();
12074 break;
12075
12079 break;
12080 }
12081 }
12082
12083 // At this point, we have a multiversion function decl (in OldFD) AND an
12084 // appropriate attribute in the current function decl. Resolve that these are
12085 // still compatible with previous declarations.
12086 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, NewCPUDisp,
12087 NewCPUSpec, NewClones, Redeclaration,
12088 OldDecl, Previous);
12089}
12090
12092 bool IsPure = NewFD->hasAttr<PureAttr>();
12093 bool IsConst = NewFD->hasAttr<ConstAttr>();
12094
12095 // If there are no pure or const attributes, there's nothing to check.
12096 if (!IsPure && !IsConst)
12097 return;
12098
12099 // If the function is marked both pure and const, we retain the const
12100 // attribute because it makes stronger guarantees than the pure attribute, and
12101 // we drop the pure attribute explicitly to prevent later confusion about
12102 // semantics.
12103 if (IsPure && IsConst) {
12104 S.Diag(NewFD->getLocation(), diag::warn_const_attr_with_pure_attr);
12105 NewFD->dropAttrs<PureAttr>();
12106 }
12107
12108 // Constructors and destructors are functions which return void, so are
12109 // handled here as well.
12110 if (NewFD->getReturnType()->isVoidType()) {
12111 S.Diag(NewFD->getLocation(), diag::warn_pure_function_returns_void)
12112 << IsConst;
12113 NewFD->dropAttrs<PureAttr, ConstAttr>();
12114 }
12115}
12116
12119 bool IsMemberSpecialization,
12120 bool DeclIsDefn) {
12121 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
12122 "Variably modified return types are not handled here");
12123
12124 // Determine whether the type of this function should be merged with
12125 // a previous visible declaration. This never happens for functions in C++,
12126 // and always happens in C if the previous declaration was visible.
12127 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
12128 !Previous.isShadowed();
12129
12130 bool Redeclaration = false;
12131 NamedDecl *OldDecl = nullptr;
12132 bool MayNeedOverloadableChecks = false;
12133
12135 // Merge or overload the declaration with an existing declaration of
12136 // the same name, if appropriate.
12137 if (!Previous.empty()) {
12138 // Determine whether NewFD is an overload of PrevDecl or
12139 // a declaration that requires merging. If it's an overload,
12140 // there's no more work to do here; we'll just add the new
12141 // function to the scope.
12143 NamedDecl *Candidate = Previous.getRepresentativeDecl();
12144 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
12145 Redeclaration = true;
12146 OldDecl = Candidate;
12147 }
12148 } else {
12149 MayNeedOverloadableChecks = true;
12150 switch (CheckOverload(S, NewFD, Previous, OldDecl,
12151 /*NewIsUsingDecl*/ false)) {
12153 Redeclaration = true;
12154 break;
12155
12157 Redeclaration = true;
12158 break;
12159
12161 Redeclaration = false;
12162 break;
12163 }
12164 }
12165 }
12166
12167 // Check for a previous extern "C" declaration with this name.
12168 if (!Redeclaration &&
12170 if (!Previous.empty()) {
12171 // This is an extern "C" declaration with the same name as a previous
12172 // declaration, and thus redeclares that entity...
12173 Redeclaration = true;
12174 OldDecl = Previous.getFoundDecl();
12175 MergeTypeWithPrevious = false;
12176
12177 // ... except in the presence of __attribute__((overloadable)).
12178 if (OldDecl->hasAttr<OverloadableAttr>() ||
12179 NewFD->hasAttr<OverloadableAttr>()) {
12180 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
12181 MayNeedOverloadableChecks = true;
12182 Redeclaration = false;
12183 OldDecl = nullptr;
12184 }
12185 }
12186 }
12187 }
12188
12189 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
12190 return Redeclaration;
12191
12192 // PPC MMA non-pointer types are not allowed as function return types.
12193 if (Context.getTargetInfo().getTriple().isPPC64() &&
12194 PPC().CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
12195 NewFD->setInvalidDecl();
12196 }
12197
12198 CheckConstPureAttributesUsage(*this, NewFD);
12199
12200 // C++ [dcl.spec.auto.general]p12:
12201 // Return type deduction for a templated function with a placeholder in its
12202 // declared type occurs when the definition is instantiated even if the
12203 // function body contains a return statement with a non-type-dependent
12204 // operand.
12205 //
12206 // C++ [temp.dep.expr]p3:
12207 // An id-expression is type-dependent if it is a template-id that is not a
12208 // concept-id and is dependent; or if its terminal name is:
12209 // - [...]
12210 // - associated by name lookup with one or more declarations of member
12211 // functions of a class that is the current instantiation declared with a
12212 // return type that contains a placeholder type,
12213 // - [...]
12214 //
12215 // If this is a templated function with a placeholder in its return type,
12216 // make the placeholder type dependent since it won't be deduced until the
12217 // definition is instantiated. We do this here because it needs to happen
12218 // for implicitly instantiated member functions/member function templates.
12219 if (getLangOpts().CPlusPlus14 &&
12220 (NewFD->isDependentContext() &&
12221 NewFD->getReturnType()->isUndeducedType())) {
12222 const FunctionProtoType *FPT =
12223 NewFD->getType()->castAs<FunctionProtoType>();
12224 QualType NewReturnType = SubstAutoTypeDependent(FPT->getReturnType());
12225 NewFD->setType(Context.getFunctionType(NewReturnType, FPT->getParamTypes(),
12226 FPT->getExtProtoInfo()));
12227 }
12228
12229 // C++11 [dcl.constexpr]p8:
12230 // A constexpr specifier for a non-static member function that is not
12231 // a constructor declares that member function to be const.
12232 //
12233 // This needs to be delayed until we know whether this is an out-of-line
12234 // definition of a static member function.
12235 //
12236 // This rule is not present in C++1y, so we produce a backwards
12237 // compatibility warning whenever it happens in C++11.
12238 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
12239 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
12240 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
12242 CXXMethodDecl *OldMD = nullptr;
12243 if (OldDecl)
12244 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
12245 if (!OldMD || !OldMD->isStatic()) {
12246 const FunctionProtoType *FPT =
12249 EPI.TypeQuals.addConst();
12250 MD->setType(Context.getFunctionType(FPT->getReturnType(),
12251 FPT->getParamTypes(), EPI));
12252
12253 // Warn that we did this, if we're not performing template instantiation.
12254 // In that case, we'll have warned already when the template was defined.
12255 if (!inTemplateInstantiation()) {
12256 SourceLocation AddConstLoc;
12259 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
12260
12261 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
12262 << FixItHint::CreateInsertion(AddConstLoc, " const");
12263 }
12264 }
12265 }
12266
12267 if (Redeclaration) {
12268 // NewFD and OldDecl represent declarations that need to be
12269 // merged.
12270 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
12271 DeclIsDefn)) {
12272 NewFD->setInvalidDecl();
12273 return Redeclaration;
12274 }
12275
12276 Previous.clear();
12277 Previous.addDecl(OldDecl);
12278
12279 if (FunctionTemplateDecl *OldTemplateDecl =
12280 dyn_cast<FunctionTemplateDecl>(OldDecl)) {
12281 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
12282 FunctionTemplateDecl *NewTemplateDecl
12284 assert(NewTemplateDecl && "Template/non-template mismatch");
12285
12286 // The call to MergeFunctionDecl above may have created some state in
12287 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
12288 // can add it as a redeclaration.
12289 NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
12290
12291 NewFD->setPreviousDeclaration(OldFD);
12292 if (NewFD->isCXXClassMember()) {
12293 NewFD->setAccess(OldTemplateDecl->getAccess());
12294 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
12295 }
12296
12297 // If this is an explicit specialization of a member that is a function
12298 // template, mark it as a member specialization.
12299 if (IsMemberSpecialization &&
12300 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
12301 NewTemplateDecl->setMemberSpecialization();
12302 assert(OldTemplateDecl->isMemberSpecialization());
12303 // Explicit specializations of a member template do not inherit deleted
12304 // status from the parent member template that they are specializing.
12305 if (OldFD->isDeleted()) {
12306 // FIXME: This assert will not hold in the presence of modules.
12307 assert(OldFD->getCanonicalDecl() == OldFD);
12308 // FIXME: We need an update record for this AST mutation.
12309 OldFD->setDeletedAsWritten(false);
12310 }
12311 }
12312
12313 } else {
12314 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
12315 auto *OldFD = cast<FunctionDecl>(OldDecl);
12316 // This needs to happen first so that 'inline' propagates.
12317 NewFD->setPreviousDeclaration(OldFD);
12318 if (NewFD->isCXXClassMember())
12319 NewFD->setAccess(OldFD->getAccess());
12320 }
12321 }
12322 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
12323 !NewFD->getAttr<OverloadableAttr>()) {
12324 assert((Previous.empty() ||
12325 llvm::any_of(Previous,
12326 [](const NamedDecl *ND) {
12327 return ND->hasAttr<OverloadableAttr>();
12328 })) &&
12329 "Non-redecls shouldn't happen without overloadable present");
12330
12331 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
12332 const auto *FD = dyn_cast<FunctionDecl>(ND);
12333 return FD && !FD->hasAttr<OverloadableAttr>();
12334 });
12335
12336 if (OtherUnmarkedIter != Previous.end()) {
12337 Diag(NewFD->getLocation(),
12338 diag::err_attribute_overloadable_multiple_unmarked_overloads);
12339 Diag((*OtherUnmarkedIter)->getLocation(),
12340 diag::note_attribute_overloadable_prev_overload)
12341 << false;
12342
12343 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
12344 }
12345 }
12346
12347 if (LangOpts.OpenMP)
12349
12350 if (NewFD->hasAttr<SYCLKernelEntryPointAttr>())
12352
12353 if (NewFD->hasAttr<SYCLExternalAttr>())
12355
12356 // Semantic checking for this function declaration (in isolation).
12357
12358 if (getLangOpts().CPlusPlus) {
12359 // C++-specific checks.
12360 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
12362 } else if (CXXDestructorDecl *Destructor =
12363 dyn_cast<CXXDestructorDecl>(NewFD)) {
12364 // We check here for invalid destructor names.
12365 // If we have a friend destructor declaration that is dependent, we can't
12366 // diagnose right away because cases like this are still valid:
12367 // template <class T> struct A { friend T::X::~Y(); };
12368 // struct B { struct Y { ~Y(); }; using X = Y; };
12369 // template struct A<B>;
12371 !Destructor->getFunctionObjectParameterType()->isDependentType()) {
12372 CanQualType ClassType =
12373 Context.getCanonicalTagType(Destructor->getParent());
12374
12375 DeclarationName Name =
12376 Context.DeclarationNames.getCXXDestructorName(ClassType);
12377 if (NewFD->getDeclName() != Name) {
12378 Diag(NewFD->getLocation(), diag::err_destructor_name);
12379 NewFD->setInvalidDecl();
12380 return Redeclaration;
12381 }
12382 }
12383 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
12384 if (auto *TD = Guide->getDescribedFunctionTemplate())
12386
12387 // A deduction guide is not on the list of entities that can be
12388 // explicitly specialized.
12389 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
12390 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
12391 << /*explicit specialization*/ 1;
12392 }
12393
12394 // Find any virtual functions that this function overrides.
12395 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
12396 if (!Method->isFunctionTemplateSpecialization() &&
12397 !Method->getDescribedFunctionTemplate() &&
12398 Method->isCanonicalDecl()) {
12399 AddOverriddenMethods(Method->getParent(), Method);
12400 }
12401 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
12402 // C++2a [class.virtual]p6
12403 // A virtual method shall not have a requires-clause.
12405 diag::err_constrained_virtual_method);
12406
12407 if (Method->isStatic())
12409 }
12410
12411 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
12412 ActOnConversionDeclarator(Conversion);
12413
12414 // Extra checking for C++ overloaded operators (C++ [over.oper]).
12415 if (NewFD->isOverloadedOperator() &&
12417 NewFD->setInvalidDecl();
12418 return Redeclaration;
12419 }
12420
12421 // Extra checking for C++0x literal operators (C++0x [over.literal]).
12422 if (NewFD->getLiteralIdentifier() &&
12424 NewFD->setInvalidDecl();
12425 return Redeclaration;
12426 }
12427
12428 // In C++, check default arguments now that we have merged decls. Unless
12429 // the lexical context is the class, because in this case this is done
12430 // during delayed parsing anyway.
12431 if (!CurContext->isRecord())
12433
12434 // If this function is declared as being extern "C", then check to see if
12435 // the function returns a UDT (class, struct, or union type) that is not C
12436 // compatible, and if it does, warn the user.
12437 // But, issue any diagnostic on the first declaration only.
12438 if (Previous.empty() && NewFD->isExternC()) {
12439 QualType R = NewFD->getReturnType();
12440 if (R->isIncompleteType() && !R->isVoidType())
12441 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
12442 << NewFD << R;
12443 else if (!R.isPODType(Context) && !R->isVoidType() &&
12445 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
12446 }
12447
12448 // C++1z [dcl.fct]p6:
12449 // [...] whether the function has a non-throwing exception-specification
12450 // [is] part of the function type
12451 //
12452 // This results in an ABI break between C++14 and C++17 for functions whose
12453 // declared type includes an exception-specification in a parameter or
12454 // return type. (Exception specifications on the function itself are OK in
12455 // most cases, and exception specifications are not permitted in most other
12456 // contexts where they could make it into a mangling.)
12457 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
12458 auto HasNoexcept = [&](QualType T) -> bool {
12459 // Strip off declarator chunks that could be between us and a function
12460 // type. We don't need to look far, exception specifications are very
12461 // restricted prior to C++17.
12462 if (auto *RT = T->getAs<ReferenceType>())
12463 T = RT->getPointeeType();
12464 else if (T->isAnyPointerType())
12465 T = T->getPointeeType();
12466 else if (auto *MPT = T->getAs<MemberPointerType>())
12467 T = MPT->getPointeeType();
12468 if (auto *FPT = T->getAs<FunctionProtoType>())
12469 if (FPT->isNothrow())
12470 return true;
12471 return false;
12472 };
12473
12474 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12475 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12476 for (QualType T : FPT->param_types())
12477 AnyNoexcept |= HasNoexcept(T);
12478 if (AnyNoexcept)
12479 Diag(NewFD->getLocation(),
12480 diag::warn_cxx17_compat_exception_spec_in_signature)
12481 << NewFD;
12482 }
12483
12484 if (!Redeclaration && LangOpts.CUDA) {
12485 bool IsKernel = NewFD->hasAttr<CUDAGlobalAttr>();
12486 for (auto *Parm : NewFD->parameters()) {
12487 if (!Parm->getType()->isDependentType() &&
12488 Parm->hasAttr<CUDAGridConstantAttr>() &&
12489 !(IsKernel && Parm->getType().isConstQualified()))
12490 Diag(Parm->getAttr<CUDAGridConstantAttr>()->getLocation(),
12491 diag::err_cuda_grid_constant_not_allowed);
12492 }
12494 }
12495 }
12496
12497 if (DeclIsDefn && Context.getTargetInfo().getTriple().isAArch64())
12499
12500 return Redeclaration;
12501}
12502
12504 // [basic.start.main]p3
12505 // The main function shall not be declared with C linkage-specification.
12506 if (FD->isExternCContext())
12507 Diag(FD->getLocation(), diag::ext_main_invalid_linkage_specification);
12508
12509 // C++11 [basic.start.main]p3:
12510 // A program that [...] declares main to be inline, static or
12511 // constexpr is ill-formed.
12512 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
12513 // appear in a declaration of main.
12514 // static main is not an error under C99, but we should warn about it.
12515 // We accept _Noreturn main as an extension.
12516 if (FD->getStorageClass() == SC_Static)
12518 ? diag::err_static_main : diag::warn_static_main)
12520 if (FD->isInlineSpecified())
12521 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
12523 if (DS.isNoreturnSpecified()) {
12524 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12525 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
12526 Diag(NoreturnLoc, diag::ext_noreturn_main);
12527 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
12528 << FixItHint::CreateRemoval(NoreturnRange);
12529 }
12530 if (FD->isConstexpr()) {
12531 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
12532 << FD->isConsteval()
12535 }
12536
12537 if (getLangOpts().OpenCL) {
12538 Diag(FD->getLocation(), diag::err_opencl_no_main)
12539 << FD->hasAttr<DeviceKernelAttr>();
12540 FD->setInvalidDecl();
12541 return;
12542 }
12543
12544 if (FD->hasAttr<SYCLExternalAttr>()) {
12545 Diag(FD->getLocation(), diag::err_sycl_external_invalid_main)
12546 << FD->getAttr<SYCLExternalAttr>();
12547 FD->setInvalidDecl();
12548 return;
12549 }
12550
12551 // Functions named main in hlsl are default entries, but don't have specific
12552 // signatures they are required to conform to.
12553 if (getLangOpts().HLSL)
12554 return;
12555
12556 QualType T = FD->getType();
12557 assert(T->isFunctionType() && "function decl is not of function type");
12558 const FunctionType* FT = T->castAs<FunctionType>();
12559
12560 // Set default calling convention for main()
12561 if (FT->getCallConv() != CC_C) {
12562 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
12563 FD->setType(QualType(FT, 0));
12564 T = Context.getCanonicalType(FD->getType());
12565 }
12566
12568 // In C with GNU extensions we allow main() to have non-integer return
12569 // type, but we should warn about the extension, and we disable the
12570 // implicit-return-zero rule.
12571
12572 // GCC in C mode accepts qualified 'int'.
12573 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
12574 FD->setHasImplicitReturnZero(true);
12575 else {
12576 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
12577 SourceRange RTRange = FD->getReturnTypeSourceRange();
12578 if (RTRange.isValid())
12579 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
12580 << FixItHint::CreateReplacement(RTRange, "int");
12581 }
12582 } else {
12583 // In C and C++, main magically returns 0 if you fall off the end;
12584 // set the flag which tells us that.
12585 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12586
12587 // All the standards say that main() should return 'int'.
12588 if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
12589 FD->setHasImplicitReturnZero(true);
12590 else {
12591 // Otherwise, this is just a flat-out error.
12592 SourceRange RTRange = FD->getReturnTypeSourceRange();
12593 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
12594 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
12595 : FixItHint());
12596 FD->setInvalidDecl(true);
12597 }
12598
12599 // [basic.start.main]p3:
12600 // A program that declares a function main that belongs to the global scope
12601 // and is attached to a named module is ill-formed.
12602 if (FD->isInNamedModule()) {
12603 const SourceLocation start = FD->getTypeSpecStartLoc();
12604 Diag(start, diag::warn_main_in_named_module)
12605 << FixItHint::CreateInsertion(start, "extern \"C++\" ", true);
12606 }
12607 }
12608
12609 // Treat protoless main() as nullary.
12610 if (isa<FunctionNoProtoType>(FT)) return;
12611
12613 unsigned nparams = FTP->getNumParams();
12614 assert(FD->getNumParams() == nparams);
12615
12616 bool HasExtraParameters = (nparams > 3);
12617
12618 if (FTP->isVariadic()) {
12619 Diag(FD->getLocation(), diag::ext_variadic_main);
12620 // FIXME: if we had information about the location of the ellipsis, we
12621 // could add a FixIt hint to remove it as a parameter.
12622 }
12623
12624 // Darwin passes an undocumented fourth argument of type char**. If
12625 // other platforms start sprouting these, the logic below will start
12626 // getting shifty.
12627 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12628 HasExtraParameters = false;
12629
12630 if (HasExtraParameters) {
12631 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
12632 FD->setInvalidDecl(true);
12633 nparams = 3;
12634 }
12635
12636 // FIXME: a lot of the following diagnostics would be improved
12637 // if we had some location information about types.
12638
12639 QualType CharPP =
12640 Context.getPointerType(Context.getPointerType(Context.CharTy));
12641 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12642
12643 for (unsigned i = 0; i < nparams; ++i) {
12644 QualType AT = FTP->getParamType(i);
12645
12646 bool mismatch = true;
12647
12648 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
12649 mismatch = false;
12650 else if (Expected[i] == CharPP) {
12651 // As an extension, the following forms are okay:
12652 // char const **
12653 // char const * const *
12654 // char * const *
12655
12657 const PointerType* PT;
12658 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
12659 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
12660 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
12661 Context.CharTy)) {
12662 qs.removeConst();
12663 mismatch = !qs.empty();
12664 }
12665 }
12666
12667 if (mismatch) {
12668 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
12669 // TODO: suggest replacing given type with expected type
12670 FD->setInvalidDecl(true);
12671 }
12672 }
12673
12674 if (nparams == 1 && !FD->isInvalidDecl()) {
12675 Diag(FD->getLocation(), diag::warn_main_one_arg);
12676 }
12677
12678 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12679 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12680 FD->setInvalidDecl();
12681 }
12682}
12683
12684static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
12685
12686 // Default calling convention for main and wmain is __cdecl
12687 if (FD->getName() == "main" || FD->getName() == "wmain")
12688 return false;
12689
12690 // Default calling convention for MinGW and Cygwin is __cdecl
12691 const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
12692 if (T.isOSCygMing())
12693 return false;
12694
12695 // Default calling convention for WinMain, wWinMain and DllMain
12696 // is __stdcall on 32 bit Windows
12697 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
12698 return true;
12699
12700 return false;
12701}
12702
12704 QualType T = FD->getType();
12705 assert(T->isFunctionType() && "function decl is not of function type");
12706 const FunctionType *FT = T->castAs<FunctionType>();
12707
12708 // Set an implicit return of 'zero' if the function can return some integral,
12709 // enumeration, pointer or nullptr type.
12713 // DllMain is exempt because a return value of zero means it failed.
12714 if (FD->getName() != "DllMain")
12715 FD->setHasImplicitReturnZero(true);
12716
12717 // Explicitly specified calling conventions are applied to MSVC entry points
12718 if (!hasExplicitCallingConv(T)) {
12719 if (isDefaultStdCall(FD, *this)) {
12720 if (FT->getCallConv() != CC_X86StdCall) {
12721 FT = Context.adjustFunctionType(
12723 FD->setType(QualType(FT, 0));
12724 }
12725 } else if (FT->getCallConv() != CC_C) {
12726 FT = Context.adjustFunctionType(FT,
12728 FD->setType(QualType(FT, 0));
12729 }
12730 }
12731
12732 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12733 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12734 FD->setInvalidDecl();
12735 }
12736}
12737
12739 // FIXME: Need strict checking. In C89, we need to check for
12740 // any assignment, increment, decrement, function-calls, or
12741 // commas outside of a sizeof. In C99, it's the same list,
12742 // except that the aforementioned are allowed in unevaluated
12743 // expressions. Everything else falls under the
12744 // "may accept other forms of constant expressions" exception.
12745 //
12746 // Regular C++ code will not end up here (exceptions: language extensions,
12747 // OpenCL C++ etc), so the constant expression rules there don't matter.
12748 if (Init->isValueDependent()) {
12749 assert(Init->containsErrors() &&
12750 "Dependent code should only occur in error-recovery path.");
12751 return true;
12752 }
12753 const Expr *Culprit;
12754 if (Init->isConstantInitializer(Context, false, &Culprit))
12755 return false;
12756 Diag(Culprit->getExprLoc(), DiagID) << Culprit->getSourceRange();
12757 return true;
12758}
12759
12760namespace {
12761 // Visits an initialization expression to see if OrigDecl is evaluated in
12762 // its own initialization and throws a warning if it does.
12763 class SelfReferenceChecker
12764 : public EvaluatedExprVisitor<SelfReferenceChecker> {
12765 Sema &S;
12766 Decl *OrigDecl;
12767 bool isRecordType;
12768 bool isPODType;
12769 bool isReferenceType;
12770 bool isInCXXOperatorCall;
12771
12772 bool isInitList;
12773 llvm::SmallVector<unsigned, 4> InitFieldIndex;
12774
12775 public:
12777
12778 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
12779 S(S), OrigDecl(OrigDecl) {
12780 isPODType = false;
12781 isRecordType = false;
12782 isReferenceType = false;
12783 isInCXXOperatorCall = false;
12784 isInitList = false;
12785 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
12786 isPODType = VD->getType().isPODType(S.Context);
12787 isRecordType = VD->getType()->isRecordType();
12788 isReferenceType = VD->getType()->isReferenceType();
12789 }
12790 }
12791
12792 // For most expressions, just call the visitor. For initializer lists,
12793 // track the index of the field being initialized since fields are
12794 // initialized in order allowing use of previously initialized fields.
12795 void CheckExpr(Expr *E) {
12796 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
12797 if (!InitList) {
12798 Visit(E);
12799 return;
12800 }
12801
12802 // Track and increment the index here.
12803 isInitList = true;
12804 InitFieldIndex.push_back(0);
12805 for (auto *Child : InitList->children()) {
12806 CheckExpr(cast<Expr>(Child));
12807 ++InitFieldIndex.back();
12808 }
12809 InitFieldIndex.pop_back();
12810 }
12811
12812 // Returns true if MemberExpr is checked and no further checking is needed.
12813 // Returns false if additional checking is required.
12814 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
12815 llvm::SmallVector<FieldDecl*, 4> Fields;
12816 Expr *Base = E;
12817 bool ReferenceField = false;
12818
12819 // Get the field members used.
12820 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12821 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
12822 if (!FD)
12823 return false;
12824 Fields.push_back(FD);
12825 if (FD->getType()->isReferenceType())
12826 ReferenceField = true;
12827 Base = ME->getBase()->IgnoreParenImpCasts();
12828 }
12829
12830 // Keep checking only if the base Decl is the same.
12831 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
12832 if (!DRE || DRE->getDecl() != OrigDecl)
12833 return false;
12834
12835 // A reference field can be bound to an unininitialized field.
12836 if (CheckReference && !ReferenceField)
12837 return true;
12838
12839 // Convert FieldDecls to their index number.
12840 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
12841 for (const FieldDecl *I : llvm::reverse(Fields))
12842 UsedFieldIndex.push_back(I->getFieldIndex());
12843
12844 // See if a warning is needed by checking the first difference in index
12845 // numbers. If field being used has index less than the field being
12846 // initialized, then the use is safe.
12847 for (auto UsedIter = UsedFieldIndex.begin(),
12848 UsedEnd = UsedFieldIndex.end(),
12849 OrigIter = InitFieldIndex.begin(),
12850 OrigEnd = InitFieldIndex.end();
12851 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
12852 if (*UsedIter < *OrigIter)
12853 return true;
12854 if (*UsedIter > *OrigIter)
12855 break;
12856 }
12857
12858 // TODO: Add a different warning which will print the field names.
12859 HandleDeclRefExpr(DRE);
12860 return true;
12861 }
12862
12863 // For most expressions, the cast is directly above the DeclRefExpr.
12864 // For conditional operators, the cast can be outside the conditional
12865 // operator if both expressions are DeclRefExpr's.
12866 void HandleValue(Expr *E) {
12867 E = E->IgnoreParens();
12868 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
12869 HandleDeclRefExpr(DRE);
12870 return;
12871 }
12872
12873 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
12874 Visit(CO->getCond());
12875 HandleValue(CO->getTrueExpr());
12876 HandleValue(CO->getFalseExpr());
12877 return;
12878 }
12879
12880 if (BinaryConditionalOperator *BCO =
12881 dyn_cast<BinaryConditionalOperator>(E)) {
12882 Visit(BCO->getCond());
12883 HandleValue(BCO->getFalseExpr());
12884 return;
12885 }
12886
12887 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
12888 if (Expr *SE = OVE->getSourceExpr())
12889 HandleValue(SE);
12890 return;
12891 }
12892
12893 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12894 if (BO->getOpcode() == BO_Comma) {
12895 Visit(BO->getLHS());
12896 HandleValue(BO->getRHS());
12897 return;
12898 }
12899 }
12900
12901 if (isa<MemberExpr>(E)) {
12902 if (isInitList) {
12903 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
12904 false /*CheckReference*/))
12905 return;
12906 }
12907
12908 Expr *Base = E->IgnoreParenImpCasts();
12909 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12910 // Check for static member variables and don't warn on them.
12911 if (!isa<FieldDecl>(ME->getMemberDecl()))
12912 return;
12913 Base = ME->getBase()->IgnoreParenImpCasts();
12914 }
12915 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
12916 HandleDeclRefExpr(DRE);
12917 return;
12918 }
12919
12920 Visit(E);
12921 }
12922
12923 // Reference types not handled in HandleValue are handled here since all
12924 // uses of references are bad, not just r-value uses.
12925 void VisitDeclRefExpr(DeclRefExpr *E) {
12926 if (isReferenceType)
12927 HandleDeclRefExpr(E);
12928 }
12929
12930 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
12931 if (E->getCastKind() == CK_LValueToRValue) {
12932 HandleValue(E->getSubExpr());
12933 return;
12934 }
12935
12936 Inherited::VisitImplicitCastExpr(E);
12937 }
12938
12939 void VisitMemberExpr(MemberExpr *E) {
12940 if (isInitList) {
12941 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
12942 return;
12943 }
12944
12945 // Don't warn on arrays since they can be treated as pointers.
12946 if (E->getType()->canDecayToPointerType()) return;
12947
12948 // Warn when a non-static method call is followed by non-static member
12949 // field accesses, which is followed by a DeclRefExpr.
12950 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
12951 bool Warn = (MD && !MD->isStatic());
12952 Expr *Base = E->getBase()->IgnoreParenImpCasts();
12953 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12954 if (!isa<FieldDecl>(ME->getMemberDecl()))
12955 Warn = false;
12956 Base = ME->getBase()->IgnoreParenImpCasts();
12957 }
12958
12959 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
12960 if (Warn)
12961 HandleDeclRefExpr(DRE);
12962 return;
12963 }
12964
12965 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
12966 // Visit that expression.
12967 Visit(Base);
12968 }
12969
12970 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
12971 llvm::SaveAndRestore CxxOpCallScope(isInCXXOperatorCall, true);
12972 Expr *Callee = E->getCallee();
12973
12974 if (isa<UnresolvedLookupExpr>(Callee))
12975 return Inherited::VisitCXXOperatorCallExpr(E);
12976
12977 Visit(Callee);
12978 for (auto Arg: E->arguments())
12979 HandleValue(Arg->IgnoreParenImpCasts());
12980 }
12981
12982 void VisitLambdaExpr(LambdaExpr *E) {
12983 if (!isInCXXOperatorCall) {
12984 Inherited::VisitLambdaExpr(E);
12985 return;
12986 }
12987
12988 for (Expr *Init : E->capture_inits())
12989 if (DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(Init))
12990 HandleDeclRefExpr(DRE);
12991 else if (Init)
12992 Visit(Init);
12993 }
12994
12995 void VisitUnaryOperator(UnaryOperator *E) {
12996 // For POD record types, addresses of its own members are well-defined.
12997 if (E->getOpcode() == UO_AddrOf && isRecordType &&
12999 if (!isPODType)
13000 HandleValue(E->getSubExpr());
13001 return;
13002 }
13003
13004 if (E->isIncrementDecrementOp()) {
13005 HandleValue(E->getSubExpr());
13006 return;
13007 }
13008
13009 Inherited::VisitUnaryOperator(E);
13010 }
13011
13012 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
13013
13014 void VisitCXXConstructExpr(CXXConstructExpr *E) {
13015 if (E->getConstructor()->isCopyConstructor()) {
13016 Expr *ArgExpr = E->getArg(0);
13017 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
13018 if (ILE->getNumInits() == 1)
13019 ArgExpr = ILE->getInit(0);
13020 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
13021 if (ICE->getCastKind() == CK_NoOp)
13022 ArgExpr = ICE->getSubExpr();
13023 HandleValue(ArgExpr);
13024 return;
13025 }
13026 Inherited::VisitCXXConstructExpr(E);
13027 }
13028
13029 void VisitCallExpr(CallExpr *E) {
13030 // Treat std::move as a use.
13031 if (E->isCallToStdMove()) {
13032 HandleValue(E->getArg(0));
13033 return;
13034 }
13035
13036 Inherited::VisitCallExpr(E);
13037 }
13038
13039 void VisitBinaryOperator(BinaryOperator *E) {
13040 if (E->isCompoundAssignmentOp()) {
13041 HandleValue(E->getLHS());
13042 Visit(E->getRHS());
13043 return;
13044 }
13045
13046 Inherited::VisitBinaryOperator(E);
13047 }
13048
13049 // A custom visitor for BinaryConditionalOperator is needed because the
13050 // regular visitor would check the condition and true expression separately
13051 // but both point to the same place giving duplicate diagnostics.
13052 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
13053 Visit(E->getCond());
13054 Visit(E->getFalseExpr());
13055 }
13056
13057 void HandleDeclRefExpr(DeclRefExpr *DRE) {
13058 Decl* ReferenceDecl = DRE->getDecl();
13059 if (OrigDecl != ReferenceDecl) return;
13060 unsigned diag;
13061 if (isReferenceType) {
13062 diag = diag::warn_uninit_self_reference_in_reference_init;
13063 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
13064 diag = diag::warn_static_self_reference_in_init;
13065 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
13066 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
13067 DRE->getDecl()->getType()->isRecordType()) {
13068 diag = diag::warn_uninit_self_reference_in_init;
13069 } else {
13070 // Local variables will be handled by the CFG analysis.
13071 return;
13072 }
13073
13074 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
13075 S.PDiag(diag)
13076 << DRE->getDecl() << OrigDecl->getLocation()
13077 << DRE->getSourceRange());
13078 }
13079 };
13080
13081 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
13082 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
13083 bool DirectInit) {
13084 // Parameters arguments are occassionially constructed with itself,
13085 // for instance, in recursive functions. Skip them.
13086 if (isa<ParmVarDecl>(OrigDecl))
13087 return;
13088
13089 E = E->IgnoreParens();
13090
13091 // Skip checking T a = a where T is not a record or reference type.
13092 // Doing so is a way to silence uninitialized warnings.
13093 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
13094 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
13095 if (ICE->getCastKind() == CK_LValueToRValue)
13096 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
13097 if (DRE->getDecl() == OrigDecl)
13098 return;
13099
13100 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
13101 }
13102} // end anonymous namespace
13103
13104namespace {
13105 // Simple wrapper to add the name of a variable or (if no variable is
13106 // available) a DeclarationName into a diagnostic.
13107 struct VarDeclOrName {
13108 VarDecl *VDecl;
13109 DeclarationName Name;
13110
13111 friend const Sema::SemaDiagnosticBuilder &
13112 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
13113 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
13114 }
13115 };
13116} // end anonymous namespace
13117
13120 TypeSourceInfo *TSI,
13121 SourceRange Range, bool DirectInit,
13122 Expr *Init) {
13123 bool IsInitCapture = !VDecl;
13124 assert((!VDecl || !VDecl->isInitCapture()) &&
13125 "init captures are expected to be deduced prior to initialization");
13126
13127 VarDeclOrName VN{VDecl, Name};
13128
13129 DeducedType *Deduced = Type->getContainedDeducedType();
13130 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
13131
13132 // Diagnose auto array declarations in C23, unless it's a supported extension.
13133 if (getLangOpts().C23 && Type->isArrayType() &&
13134 !isa_and_present<StringLiteral, InitListExpr>(Init)) {
13135 Diag(Range.getBegin(), diag::err_auto_not_allowed)
13136 << (int)Deduced->getContainedAutoType()->getKeyword()
13137 << /*in array decl*/ 23 << Range;
13138 return QualType();
13139 }
13140
13141 // C++11 [dcl.spec.auto]p3
13142 if (!Init) {
13143 assert(VDecl && "no init for init capture deduction?");
13144
13145 // Except for class argument deduction, and then for an initializing
13146 // declaration only, i.e. no static at class scope or extern.
13148 VDecl->hasExternalStorage() ||
13149 VDecl->isStaticDataMember()) {
13150 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
13151 << VDecl->getDeclName() << Type;
13152 return QualType();
13153 }
13154 }
13155
13156 ArrayRef<Expr*> DeduceInits;
13157 if (Init)
13158 DeduceInits = Init;
13159
13160 auto *PL = dyn_cast_if_present<ParenListExpr>(Init);
13161 if (DirectInit && PL)
13162 DeduceInits = PL->exprs();
13163
13165 assert(VDecl && "non-auto type for init capture deduction?");
13168 VDecl->getLocation(), DirectInit, Init);
13169 // FIXME: Initialization should not be taking a mutable list of inits.
13170 SmallVector<Expr *, 8> InitsCopy(DeduceInits);
13171 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
13172 InitsCopy);
13173 }
13174
13175 if (DirectInit) {
13176 if (auto *IL = dyn_cast<InitListExpr>(Init))
13177 DeduceInits = IL->inits();
13178 }
13179
13180 // Deduction only works if we have exactly one source expression.
13181 if (DeduceInits.empty()) {
13182 // It isn't possible to write this directly, but it is possible to
13183 // end up in this situation with "auto x(some_pack...);"
13184 Diag(Init->getBeginLoc(), IsInitCapture
13185 ? diag::err_init_capture_no_expression
13186 : diag::err_auto_var_init_no_expression)
13187 << VN << Type << Range;
13188 return QualType();
13189 }
13190
13191 if (DeduceInits.size() > 1) {
13192 Diag(DeduceInits[1]->getBeginLoc(),
13193 IsInitCapture ? diag::err_init_capture_multiple_expressions
13194 : diag::err_auto_var_init_multiple_expressions)
13195 << VN << Type << Range;
13196 return QualType();
13197 }
13198
13199 Expr *DeduceInit = DeduceInits[0];
13200 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
13201 Diag(Init->getBeginLoc(), IsInitCapture
13202 ? diag::err_init_capture_paren_braces
13203 : diag::err_auto_var_init_paren_braces)
13204 << isa<InitListExpr>(Init) << VN << Type << Range;
13205 return QualType();
13206 }
13207
13208 // Expressions default to 'id' when we're in a debugger.
13209 bool DefaultedAnyToId = false;
13210 if (getLangOpts().DebuggerCastResultToId &&
13211 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
13213 if (Result.isInvalid()) {
13214 return QualType();
13215 }
13216 Init = Result.get();
13217 DefaultedAnyToId = true;
13218 }
13219
13220 // C++ [dcl.decomp]p1:
13221 // If the assignment-expression [...] has array type A and no ref-qualifier
13222 // is present, e has type cv A
13223 if (VDecl && isa<DecompositionDecl>(VDecl) &&
13224 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
13225 DeduceInit->getType()->isConstantArrayType())
13226 return Context.getQualifiedType(DeduceInit->getType(),
13227 Type.getQualifiers());
13228
13229 QualType DeducedType;
13230 TemplateDeductionInfo Info(DeduceInit->getExprLoc());
13232 DeduceAutoType(TSI->getTypeLoc(), DeduceInit, DeducedType, Info);
13235 if (!IsInitCapture)
13236 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
13237 else if (isa<InitListExpr>(Init))
13238 Diag(Range.getBegin(),
13239 diag::err_init_capture_deduction_failure_from_init_list)
13240 << VN
13241 << (DeduceInit->getType().isNull() ? TSI->getType()
13242 : DeduceInit->getType())
13243 << DeduceInit->getSourceRange();
13244 else
13245 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
13246 << VN << TSI->getType()
13247 << (DeduceInit->getType().isNull() ? TSI->getType()
13248 : DeduceInit->getType())
13249 << DeduceInit->getSourceRange();
13250 }
13251
13252 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
13253 // 'id' instead of a specific object type prevents most of our usual
13254 // checks.
13255 // We only want to warn outside of template instantiations, though:
13256 // inside a template, the 'id' could have come from a parameter.
13257 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
13258 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
13259 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
13260 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
13261 }
13262
13263 return DeducedType;
13264}
13265
13267 Expr *Init) {
13268 assert(!Init || !Init->containsErrors());
13270 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
13271 VDecl->getSourceRange(), DirectInit, Init);
13272 if (DeducedType.isNull()) {
13273 VDecl->setInvalidDecl();
13274 return true;
13275 }
13276
13277 VDecl->setType(DeducedType);
13278 assert(VDecl->isLinkageValid());
13279
13280 // In ARC, infer lifetime.
13281 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(VDecl))
13282 VDecl->setInvalidDecl();
13283
13284 if (getLangOpts().OpenCL)
13286
13287 if (getLangOpts().HLSL)
13288 HLSL().deduceAddressSpace(VDecl);
13289
13290 // If this is a redeclaration, check that the type we just deduced matches
13291 // the previously declared type.
13292 if (VarDecl *Old = VDecl->getPreviousDecl()) {
13293 // We never need to merge the type, because we cannot form an incomplete
13294 // array of auto, nor deduce such a type.
13295 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
13296 }
13297
13298 // Check the deduced type is valid for a variable declaration.
13300 return VDecl->isInvalidDecl();
13301}
13302
13304 SourceLocation Loc) {
13305 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
13306 Init = EWC->getSubExpr();
13307
13308 if (auto *CE = dyn_cast<ConstantExpr>(Init))
13309 Init = CE->getSubExpr();
13310
13311 QualType InitType = Init->getType();
13314 "shouldn't be called if type doesn't have a non-trivial C struct");
13315 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
13316 for (auto *I : ILE->inits()) {
13317 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
13318 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
13319 continue;
13320 SourceLocation SL = I->getExprLoc();
13321 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
13322 }
13323 return;
13324 }
13325
13328 checkNonTrivialCUnion(InitType, Loc,
13330 NTCUK_Init);
13331 } else {
13332 // Assume all other explicit initializers involving copying some existing
13333 // object.
13334 // TODO: ignore any explicit initializers where we can guarantee
13335 // copy-elision.
13338 NTCUK_Copy);
13339 }
13340}
13341
13342namespace {
13343
13344bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
13345 // Ignore unavailable fields. A field can be marked as unavailable explicitly
13346 // in the source code or implicitly by the compiler if it is in a union
13347 // defined in a system header and has non-trivial ObjC ownership
13348 // qualifications. We don't want those fields to participate in determining
13349 // whether the containing union is non-trivial.
13350 return FD->hasAttr<UnavailableAttr>();
13351}
13352
13353struct DiagNonTrivalCUnionDefaultInitializeVisitor
13354 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13355 void> {
13356 using Super =
13357 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13358 void>;
13359
13360 DiagNonTrivalCUnionDefaultInitializeVisitor(
13361 QualType OrigTy, SourceLocation OrigLoc,
13362 NonTrivialCUnionContext UseContext, Sema &S)
13363 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13364
13365 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
13366 const FieldDecl *FD, bool InNonTrivialUnion) {
13367 if (const auto *AT = S.Context.getAsArrayType(QT))
13368 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13369 InNonTrivialUnion);
13370 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
13371 }
13372
13373 void visitARCStrong(QualType QT, const FieldDecl *FD,
13374 bool InNonTrivialUnion) {
13375 if (InNonTrivialUnion)
13376 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13377 << 1 << 0 << QT << FD->getName();
13378 }
13379
13380 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13381 if (InNonTrivialUnion)
13382 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13383 << 1 << 0 << QT << FD->getName();
13384 }
13385
13386 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13387 const auto *RD = QT->castAsRecordDecl();
13388 if (RD->isUnion()) {
13389 if (OrigLoc.isValid()) {
13390 bool IsUnion = false;
13391 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13392 IsUnion = OrigRD->isUnion();
13393 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13394 << 0 << OrigTy << IsUnion << UseContext;
13395 // Reset OrigLoc so that this diagnostic is emitted only once.
13396 OrigLoc = SourceLocation();
13397 }
13398 InNonTrivialUnion = true;
13399 }
13400
13401 if (InNonTrivialUnion)
13402 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13403 << 0 << 0 << QT.getUnqualifiedType() << "";
13404
13405 for (const FieldDecl *FD : RD->fields())
13406 if (!shouldIgnoreForRecordTriviality(FD))
13407 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13408 }
13409
13410 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13411
13412 // The non-trivial C union type or the struct/union type that contains a
13413 // non-trivial C union.
13414 QualType OrigTy;
13415 SourceLocation OrigLoc;
13416 NonTrivialCUnionContext UseContext;
13417 Sema &S;
13418};
13419
13420struct DiagNonTrivalCUnionDestructedTypeVisitor
13421 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
13422 using Super =
13423 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
13424
13425 DiagNonTrivalCUnionDestructedTypeVisitor(QualType OrigTy,
13426 SourceLocation OrigLoc,
13427 NonTrivialCUnionContext UseContext,
13428 Sema &S)
13429 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13430
13431 void visitWithKind(QualType::DestructionKind DK, QualType QT,
13432 const FieldDecl *FD, bool InNonTrivialUnion) {
13433 if (const auto *AT = S.Context.getAsArrayType(QT))
13434 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13435 InNonTrivialUnion);
13436 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
13437 }
13438
13439 void visitARCStrong(QualType QT, const FieldDecl *FD,
13440 bool InNonTrivialUnion) {
13441 if (InNonTrivialUnion)
13442 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13443 << 1 << 1 << QT << FD->getName();
13444 }
13445
13446 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13447 if (InNonTrivialUnion)
13448 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13449 << 1 << 1 << QT << FD->getName();
13450 }
13451
13452 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13453 const auto *RD = QT->castAsRecordDecl();
13454 if (RD->isUnion()) {
13455 if (OrigLoc.isValid()) {
13456 bool IsUnion = false;
13457 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13458 IsUnion = OrigRD->isUnion();
13459 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13460 << 1 << OrigTy << IsUnion << UseContext;
13461 // Reset OrigLoc so that this diagnostic is emitted only once.
13462 OrigLoc = SourceLocation();
13463 }
13464 InNonTrivialUnion = true;
13465 }
13466
13467 if (InNonTrivialUnion)
13468 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13469 << 0 << 1 << QT.getUnqualifiedType() << "";
13470
13471 for (const FieldDecl *FD : RD->fields())
13472 if (!shouldIgnoreForRecordTriviality(FD))
13473 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13474 }
13475
13476 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13477 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
13478 bool InNonTrivialUnion) {}
13479
13480 // The non-trivial C union type or the struct/union type that contains a
13481 // non-trivial C union.
13482 QualType OrigTy;
13483 SourceLocation OrigLoc;
13484 NonTrivialCUnionContext UseContext;
13485 Sema &S;
13486};
13487
13488struct DiagNonTrivalCUnionCopyVisitor
13489 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
13490 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
13491
13492 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
13493 NonTrivialCUnionContext UseContext, Sema &S)
13494 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13495
13496 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
13497 const FieldDecl *FD, bool InNonTrivialUnion) {
13498 if (const auto *AT = S.Context.getAsArrayType(QT))
13499 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13500 InNonTrivialUnion);
13501 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
13502 }
13503
13504 void visitARCStrong(QualType QT, const FieldDecl *FD,
13505 bool InNonTrivialUnion) {
13506 if (InNonTrivialUnion)
13507 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13508 << 1 << 2 << QT << FD->getName();
13509 }
13510
13511 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13512 if (InNonTrivialUnion)
13513 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13514 << 1 << 2 << QT << FD->getName();
13515 }
13516
13517 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13518 const auto *RD = QT->castAsRecordDecl();
13519 if (RD->isUnion()) {
13520 if (OrigLoc.isValid()) {
13521 bool IsUnion = false;
13522 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13523 IsUnion = OrigRD->isUnion();
13524 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13525 << 2 << OrigTy << IsUnion << UseContext;
13526 // Reset OrigLoc so that this diagnostic is emitted only once.
13527 OrigLoc = SourceLocation();
13528 }
13529 InNonTrivialUnion = true;
13530 }
13531
13532 if (InNonTrivialUnion)
13533 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13534 << 0 << 2 << QT.getUnqualifiedType() << "";
13535
13536 for (const FieldDecl *FD : RD->fields())
13537 if (!shouldIgnoreForRecordTriviality(FD))
13538 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13539 }
13540
13541 void visitPtrAuth(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13542 if (InNonTrivialUnion)
13543 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13544 << 1 << 2 << QT << FD->getName();
13545 }
13546
13547 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13548 const FieldDecl *FD, bool InNonTrivialUnion) {}
13549 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13550 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13551 bool InNonTrivialUnion) {}
13552
13553 // The non-trivial C union type or the struct/union type that contains a
13554 // non-trivial C union.
13555 QualType OrigTy;
13556 SourceLocation OrigLoc;
13557 NonTrivialCUnionContext UseContext;
13558 Sema &S;
13559};
13560
13561} // namespace
13562
13564 NonTrivialCUnionContext UseContext,
13565 unsigned NonTrivialKind) {
13569 "shouldn't be called if type doesn't have a non-trivial C union");
13570
13571 if ((NonTrivialKind & NTCUK_Init) &&
13573 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
13574 .visit(QT, nullptr, false);
13575 if ((NonTrivialKind & NTCUK_Destruct) &&
13577 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
13578 .visit(QT, nullptr, false);
13579 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
13580 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
13581 .visit(QT, nullptr, false);
13582}
13583
13585 const VarDecl *Dcl) {
13586 if (!getLangOpts().CPlusPlus)
13587 return false;
13588
13589 // We only need to warn if the definition is in a header file, so wait to
13590 // diagnose until we've seen the definition.
13591 if (!Dcl->isThisDeclarationADefinition())
13592 return false;
13593
13594 // If an object is defined in a source file, its definition can't get
13595 // duplicated since it will never appear in more than one TU.
13597 return false;
13598
13599 // If the variable we're looking at is a static local, then we actually care
13600 // about the properties of the function containing it.
13601 const ValueDecl *Target = Dcl;
13602 // VarDecls and FunctionDecls have different functions for checking
13603 // inline-ness, and whether they were originally templated, so we have to
13604 // call the appropriate functions manually.
13605 bool TargetIsInline = Dcl->isInline();
13606 bool TargetWasTemplated =
13608
13609 // Update the Target and TargetIsInline property if necessary
13610 if (Dcl->isStaticLocal()) {
13611 const DeclContext *Ctx = Dcl->getDeclContext();
13612 if (!Ctx)
13613 return false;
13614
13615 const FunctionDecl *FunDcl =
13616 dyn_cast_if_present<FunctionDecl>(Ctx->getNonClosureAncestor());
13617 if (!FunDcl)
13618 return false;
13619
13620 Target = FunDcl;
13621 // IsInlined() checks for the C++ inline property
13622 TargetIsInline = FunDcl->isInlined();
13623 TargetWasTemplated =
13625 }
13626
13627 // Non-inline functions/variables can only legally appear in one TU
13628 // unless they were part of a template. Unfortunately, making complex
13629 // template instantiations visible is infeasible in practice, since
13630 // everything the template depends on also has to be visible. To avoid
13631 // giving impractical-to-fix warnings, don't warn if we're inside
13632 // something that was templated, even on inline stuff.
13633 if (!TargetIsInline || TargetWasTemplated)
13634 return false;
13635
13636 // If the object isn't hidden, the dynamic linker will prevent duplication.
13637 clang::LinkageInfo Lnk = Target->getLinkageAndVisibility();
13638
13639 // The target is "hidden" (from the dynamic linker) if:
13640 // 1. On posix, it has hidden visibility, or
13641 // 2. On windows, it has no import/export annotation, and neither does the
13642 // class which directly contains it.
13643 if (Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
13644 if (Target->hasAttr<DLLExportAttr>() || Target->hasAttr<DLLImportAttr>())
13645 return false;
13646
13647 // If the variable isn't directly annotated, check to see if it's a member
13648 // of an annotated class.
13649 const CXXRecordDecl *Ctx =
13650 dyn_cast<CXXRecordDecl>(Target->getDeclContext());
13651 if (Ctx && (Ctx->hasAttr<DLLExportAttr>() || Ctx->hasAttr<DLLImportAttr>()))
13652 return false;
13653
13654 } else if (Lnk.getVisibility() != HiddenVisibility) {
13655 // Posix case
13656 return false;
13657 }
13658
13659 // If the obj doesn't have external linkage, it's supposed to be duplicated.
13661 return false;
13662
13663 return true;
13664}
13665
13666// Determine whether the object seems mutable for the purpose of diagnosing
13667// possible unique object duplication, i.e. non-const-qualified, and
13668// not an always-constant type like a function.
13669// Not perfect: doesn't account for mutable members, for example, or
13670// elements of container types.
13671// For nested pointers, any individual level being non-const is sufficient.
13672static bool looksMutable(QualType T, const ASTContext &Ctx) {
13673 T = T.getNonReferenceType();
13674 if (T->isFunctionType())
13675 return false;
13676 if (!T.isConstant(Ctx))
13677 return true;
13678 if (T->isPointerType())
13679 return looksMutable(T->getPointeeType(), Ctx);
13680 return false;
13681}
13682
13684 // If this object has external linkage and hidden visibility, it might be
13685 // duplicated when built into a shared library, which causes problems if it's
13686 // mutable (since the copies won't be in sync) or its initialization has side
13687 // effects (since it will run once per copy instead of once globally).
13688
13689 // Don't diagnose if we're inside a template, because it's not practical to
13690 // fix the warning in most cases.
13691 if (!VD->isTemplated() &&
13693
13694 QualType Type = VD->getType();
13695 if (looksMutable(Type, VD->getASTContext())) {
13696 Diag(VD->getLocation(), diag::warn_possible_object_duplication_mutable)
13697 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
13698 }
13699
13700 // To keep false positives low, only warn if we're certain that the
13701 // initializer has side effects. Don't warn on operator new, since a mutable
13702 // pointer will trigger the previous warning, and an immutable pointer
13703 // getting duplicated just results in a little extra memory usage.
13704 const Expr *Init = VD->getAnyInitializer();
13705 if (Init &&
13706 Init->HasSideEffects(VD->getASTContext(),
13707 /*IncludePossibleEffects=*/false) &&
13708 !isa<CXXNewExpr>(Init->IgnoreParenImpCasts())) {
13709 Diag(Init->getExprLoc(), diag::warn_possible_object_duplication_init)
13710 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
13711 }
13712 }
13713}
13714
13716 // If there is no declaration, there was an error parsing it. Just ignore
13717 // the initializer.
13718 if (!RealDecl) {
13719 return;
13720 }
13721
13722 if (auto *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
13723 if (!Method->isInvalidDecl()) {
13724 // Pure-specifiers are handled in ActOnPureSpecifier.
13725 Diag(Method->getLocation(), diag::err_member_function_initialization)
13726 << Method->getDeclName() << Init->getSourceRange();
13727 Method->setInvalidDecl();
13728 }
13729 return;
13730 }
13731
13732 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
13733 if (!VDecl) {
13734 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
13735 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
13736 RealDecl->setInvalidDecl();
13737 return;
13738 }
13739
13740 if (VDecl->isInvalidDecl()) {
13741 ExprResult Recovery =
13742 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), {Init});
13743 if (Expr *E = Recovery.get())
13744 VDecl->setInit(E);
13745 return;
13746 }
13747
13748 // WebAssembly tables can't be used to initialise a variable.
13749 if (!Init->getType().isNull() && Init->getType()->isWebAssemblyTableType()) {
13750 Diag(Init->getExprLoc(), diag::err_wasm_table_art) << 0;
13751 VDecl->setInvalidDecl();
13752 return;
13753 }
13754
13755 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
13756 if (VDecl->getType()->isUndeducedType()) {
13757 if (Init->containsErrors()) {
13758 // Invalidate the decl as we don't know the type for recovery-expr yet.
13759 RealDecl->setInvalidDecl();
13760 VDecl->setInit(Init);
13761 return;
13762 }
13763
13765 return;
13766 }
13767
13768 // dllimport cannot be used on variable definitions.
13769 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
13770 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
13771 VDecl->setInvalidDecl();
13772 return;
13773 }
13774
13775 // C99 6.7.8p5. If the declaration of an identifier has block scope, and
13776 // the identifier has external or internal linkage, the declaration shall
13777 // have no initializer for the identifier.
13778 // C++14 [dcl.init]p5 is the same restriction for C++.
13779 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
13780 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
13781 VDecl->setInvalidDecl();
13782 return;
13783 }
13784
13785 if (!VDecl->getType()->isDependentType()) {
13786 // A definition must end up with a complete type, which means it must be
13787 // complete with the restriction that an array type might be completed by
13788 // the initializer; note that later code assumes this restriction.
13789 QualType BaseDeclType = VDecl->getType();
13790 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
13791 BaseDeclType = Array->getElementType();
13792 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
13793 diag::err_typecheck_decl_incomplete_type)) {
13794 RealDecl->setInvalidDecl();
13795 return;
13796 }
13797
13798 // The variable can not have an abstract class type.
13799 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
13800 diag::err_abstract_type_in_decl,
13802 VDecl->setInvalidDecl();
13803 }
13804
13805 // C++ [module.import/6] external definitions are not permitted in header
13806 // units.
13807 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
13808 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
13809 VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() &&
13810 !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(VDecl) &&
13812 Diag(VDecl->getLocation(), diag::err_extern_def_in_header_unit);
13813 VDecl->setInvalidDecl();
13814 }
13815
13816 // If adding the initializer will turn this declaration into a definition,
13817 // and we already have a definition for this variable, diagnose or otherwise
13818 // handle the situation.
13819 if (VarDecl *Def = VDecl->getDefinition())
13820 if (Def != VDecl &&
13821 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
13823 checkVarDeclRedefinition(Def, VDecl))
13824 return;
13825
13826 if (getLangOpts().CPlusPlus) {
13827 // C++ [class.static.data]p4
13828 // If a static data member is of const integral or const
13829 // enumeration type, its declaration in the class definition can
13830 // specify a constant-initializer which shall be an integral
13831 // constant expression (5.19). In that case, the member can appear
13832 // in integral constant expressions. The member shall still be
13833 // defined in a namespace scope if it is used in the program and the
13834 // namespace scope definition shall not contain an initializer.
13835 //
13836 // We already performed a redefinition check above, but for static
13837 // data members we also need to check whether there was an in-class
13838 // declaration with an initializer.
13839 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
13840 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
13841 << VDecl->getDeclName();
13842 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
13843 diag::note_previous_initializer)
13844 << 0;
13845 return;
13846 }
13847
13849 VDecl->setInvalidDecl();
13850 return;
13851 }
13852 }
13853
13854 // If the variable has an initializer and local storage, check whether
13855 // anything jumps over the initialization.
13856 if (VDecl->hasLocalStorage())
13858
13859 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
13860 // a kernel function cannot be initialized."
13861 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
13862 Diag(VDecl->getLocation(), diag::err_local_cant_init);
13863 VDecl->setInvalidDecl();
13864 return;
13865 }
13866
13867 // The LoaderUninitialized attribute acts as a definition (of undef).
13868 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
13869 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
13870 VDecl->setInvalidDecl();
13871 return;
13872 }
13873
13874 if (getLangOpts().HLSL)
13875 if (!HLSL().handleInitialization(VDecl, Init))
13876 return;
13877
13878 // Get the decls type and save a reference for later, since
13879 // CheckInitializerTypes may change it.
13880 QualType DclT = VDecl->getType(), SavT = DclT;
13881
13882 // Expressions default to 'id' when we're in a debugger
13883 // and we are assigning it to a variable of Objective-C pointer type.
13884 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
13885 Init->getType() == Context.UnknownAnyTy) {
13887 if (!Result.isUsable()) {
13888 VDecl->setInvalidDecl();
13889 return;
13890 }
13891 Init = Result.get();
13892 }
13893
13894 // Perform the initialization.
13895 bool InitializedFromParenListExpr = false;
13896 bool IsParenListInit = false;
13897 if (!VDecl->isInvalidDecl()) {
13900 VDecl->getLocation(), DirectInit, Init);
13901
13902 MultiExprArg Args = Init;
13903 if (auto *CXXDirectInit = dyn_cast<ParenListExpr>(Init)) {
13904 Args =
13905 MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
13906 InitializedFromParenListExpr = true;
13907 } else if (auto *CXXDirectInit = dyn_cast<CXXParenListInitExpr>(Init)) {
13908 Args = CXXDirectInit->getInitExprs();
13909 InitializedFromParenListExpr = true;
13910 }
13911
13912 InitializationSequence InitSeq(*this, Entity, Kind, Args,
13913 /*TopLevelOfInitList=*/false,
13914 /*TreatUnavailableAsInvalid=*/false);
13915 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
13916 if (!Result.isUsable()) {
13917 // If the provided initializer fails to initialize the var decl,
13918 // we attach a recovery expr for better recovery.
13919 auto RecoveryExpr =
13920 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
13921 if (RecoveryExpr.get())
13922 VDecl->setInit(RecoveryExpr.get());
13923 // In general, for error recovery purposes, the initializer doesn't play
13924 // part in the valid bit of the declaration. There are a few exceptions:
13925 // 1) if the var decl has a deduced auto type, and the type cannot be
13926 // deduced by an invalid initializer;
13927 // 2) if the var decl is a decomposition decl with a non-deduced type,
13928 // and the initialization fails (e.g. `int [a] = {1, 2};`);
13929 // Case 1) was already handled elsewhere.
13930 if (isa<DecompositionDecl>(VDecl)) // Case 2)
13931 VDecl->setInvalidDecl();
13932 return;
13933 }
13934
13935 Init = Result.getAs<Expr>();
13936 IsParenListInit = !InitSeq.steps().empty() &&
13937 InitSeq.step_begin()->Kind ==
13939 QualType VDeclType = VDecl->getType();
13940 if (!Init->getType().isNull() && !Init->getType()->isDependentType() &&
13941 !VDeclType->isDependentType() &&
13942 Context.getAsIncompleteArrayType(VDeclType) &&
13943 Context.getAsIncompleteArrayType(Init->getType())) {
13944 // Bail out if it is not possible to deduce array size from the
13945 // initializer.
13946 Diag(VDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)
13947 << VDeclType;
13948 VDecl->setInvalidDecl();
13949 return;
13950 }
13951 }
13952
13953 // Check for self-references within variable initializers.
13954 // Variables declared within a function/method body (except for references)
13955 // are handled by a dataflow analysis.
13956 // This is undefined behavior in C++, but valid in C.
13957 if (getLangOpts().CPlusPlus)
13958 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
13959 VDecl->getType()->isReferenceType())
13960 CheckSelfReference(*this, RealDecl, Init, DirectInit);
13961
13962 // If the type changed, it means we had an incomplete type that was
13963 // completed by the initializer. For example:
13964 // int ary[] = { 1, 3, 5 };
13965 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
13966 if (!VDecl->isInvalidDecl() && (DclT != SavT))
13967 VDecl->setType(DclT);
13968
13969 if (!VDecl->isInvalidDecl()) {
13970 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
13971
13972 if (VDecl->hasAttr<BlocksAttr>())
13973 ObjC().checkRetainCycles(VDecl, Init);
13974
13975 // It is safe to assign a weak reference into a strong variable.
13976 // Although this code can still have problems:
13977 // id x = self.weakProp;
13978 // id y = self.weakProp;
13979 // we do not warn to warn spuriously when 'x' and 'y' are on separate
13980 // paths through the function. This should be revisited if
13981 // -Wrepeated-use-of-weak is made flow-sensitive.
13982 if (FunctionScopeInfo *FSI = getCurFunction())
13983 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
13985 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13986 Init->getBeginLoc()))
13987 FSI->markSafeWeakUse(Init);
13988 }
13989
13990 // The initialization is usually a full-expression.
13991 //
13992 // FIXME: If this is a braced initialization of an aggregate, it is not
13993 // an expression, and each individual field initializer is a separate
13994 // full-expression. For instance, in:
13995 //
13996 // struct Temp { ~Temp(); };
13997 // struct S { S(Temp); };
13998 // struct T { S a, b; } t = { Temp(), Temp() }
13999 //
14000 // we should destroy the first Temp before constructing the second.
14003 /*DiscardedValue*/ false, VDecl->isConstexpr());
14004 if (!Result.isUsable()) {
14005 VDecl->setInvalidDecl();
14006 return;
14007 }
14008 Init = Result.get();
14009
14010 // Attach the initializer to the decl.
14011 VDecl->setInit(Init);
14012
14013 if (VDecl->isLocalVarDecl()) {
14014 // Don't check the initializer if the declaration is malformed.
14015 if (VDecl->isInvalidDecl()) {
14016 // do nothing
14017
14018 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
14019 // This is true even in C++ for OpenCL.
14020 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
14022
14023 // Otherwise, C++ does not restrict the initializer.
14024 } else if (getLangOpts().CPlusPlus) {
14025 // do nothing
14026
14027 // C99 6.7.8p4: All the expressions in an initializer for an object that has
14028 // static storage duration shall be constant expressions or string literals.
14029 } else if (VDecl->getStorageClass() == SC_Static) {
14031
14032 // C89 is stricter than C99 for aggregate initializers.
14033 // C89 6.5.7p3: All the expressions [...] in an initializer list
14034 // for an object that has aggregate or union type shall be
14035 // constant expressions.
14036 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
14038 CheckForConstantInitializer(Init, diag::ext_aggregate_init_not_constant);
14039 }
14040
14041 if (auto *E = dyn_cast<ExprWithCleanups>(Init))
14042 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
14043 if (VDecl->hasLocalStorage())
14044 BE->getBlockDecl()->setCanAvoidCopyToHeap();
14045 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
14046 VDecl->getLexicalDeclContext()->isRecord()) {
14047 // This is an in-class initialization for a static data member, e.g.,
14048 //
14049 // struct S {
14050 // static const int value = 17;
14051 // };
14052
14053 // C++ [class.mem]p4:
14054 // A member-declarator can contain a constant-initializer only
14055 // if it declares a static member (9.4) of const integral or
14056 // const enumeration type, see 9.4.2.
14057 //
14058 // C++11 [class.static.data]p3:
14059 // If a non-volatile non-inline const static data member is of integral
14060 // or enumeration type, its declaration in the class definition can
14061 // specify a brace-or-equal-initializer in which every initializer-clause
14062 // that is an assignment-expression is a constant expression. A static
14063 // data member of literal type can be declared in the class definition
14064 // with the constexpr specifier; if so, its declaration shall specify a
14065 // brace-or-equal-initializer in which every initializer-clause that is
14066 // an assignment-expression is a constant expression.
14067
14068 // Do nothing on dependent types.
14069 if (DclT->isDependentType()) {
14070
14071 // Allow any 'static constexpr' members, whether or not they are of literal
14072 // type. We separately check that every constexpr variable is of literal
14073 // type.
14074 } else if (VDecl->isConstexpr()) {
14075
14076 // Require constness.
14077 } else if (!DclT.isConstQualified()) {
14078 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
14079 << Init->getSourceRange();
14080 VDecl->setInvalidDecl();
14081
14082 // We allow integer constant expressions in all cases.
14083 } else if (DclT->isIntegralOrEnumerationType()) {
14085 // In C++11, a non-constexpr const static data member with an
14086 // in-class initializer cannot be volatile.
14087 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
14088
14089 // We allow foldable floating-point constants as an extension.
14090 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
14091 // In C++98, this is a GNU extension. In C++11, it is not, but we support
14092 // it anyway and provide a fixit to add the 'constexpr'.
14093 if (getLangOpts().CPlusPlus11) {
14094 Diag(VDecl->getLocation(),
14095 diag::ext_in_class_initializer_float_type_cxx11)
14096 << DclT << Init->getSourceRange();
14097 Diag(VDecl->getBeginLoc(),
14098 diag::note_in_class_initializer_float_type_cxx11)
14099 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
14100 } else {
14101 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
14102 << DclT << Init->getSourceRange();
14103
14104 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
14105 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
14106 << Init->getSourceRange();
14107 VDecl->setInvalidDecl();
14108 }
14109 }
14110
14111 // Suggest adding 'constexpr' in C++11 for literal types.
14112 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
14113 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
14114 << DclT << Init->getSourceRange()
14115 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
14116 VDecl->setConstexpr(true);
14117
14118 } else {
14119 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
14120 << DclT << Init->getSourceRange();
14121 VDecl->setInvalidDecl();
14122 }
14123 } else if (VDecl->isFileVarDecl()) {
14124 // In C, extern is typically used to avoid tentative definitions when
14125 // declaring variables in headers, but adding an initializer makes it a
14126 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
14127 // In C++, extern is often used to give implicitly static const variables
14128 // external linkage, so don't warn in that case. If selectany is present,
14129 // this might be header code intended for C and C++ inclusion, so apply the
14130 // C++ rules.
14131 if (VDecl->getStorageClass() == SC_Extern &&
14132 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
14133 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
14134 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
14136 Diag(VDecl->getLocation(), diag::warn_extern_init);
14137
14138 // In Microsoft C++ mode, a const variable defined in namespace scope has
14139 // external linkage by default if the variable is declared with
14140 // __declspec(dllexport).
14141 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14143 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
14144 VDecl->setStorageClass(SC_Extern);
14145
14146 // C99 6.7.8p4. All file scoped initializers need to be constant.
14147 // Avoid duplicate diagnostics for constexpr variables.
14148 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
14149 !VDecl->isConstexpr())
14151 }
14152
14153 QualType InitType = Init->getType();
14154 if (!InitType.isNull() &&
14158
14159 // We will represent direct-initialization similarly to copy-initialization:
14160 // int x(1); -as-> int x = 1;
14161 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
14162 //
14163 // Clients that want to distinguish between the two forms, can check for
14164 // direct initializer using VarDecl::getInitStyle().
14165 // A major benefit is that clients that don't particularly care about which
14166 // exactly form was it (like the CodeGen) can handle both cases without
14167 // special case code.
14168
14169 // C++ 8.5p11:
14170 // The form of initialization (using parentheses or '=') matters
14171 // when the entity being initialized has class type.
14172 if (InitializedFromParenListExpr) {
14173 assert(DirectInit && "Call-style initializer must be direct init.");
14174 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
14176 } else if (DirectInit) {
14177 // This must be list-initialization. No other way is direct-initialization.
14179 }
14180
14181 if (LangOpts.OpenMP &&
14182 (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&
14183 VDecl->isFileVarDecl())
14184 DeclsToCheckForDeferredDiags.insert(VDecl);
14186
14187 if (LangOpts.OpenACC && !InitType.isNull())
14188 OpenACC().ActOnVariableInit(VDecl, InitType);
14189}
14190
14192 // Our main concern here is re-establishing invariants like "a
14193 // variable's type is either dependent or complete".
14194 if (!D || D->isInvalidDecl()) return;
14195
14196 VarDecl *VD = dyn_cast<VarDecl>(D);
14197 if (!VD) return;
14198
14199 // Bindings are not usable if we can't make sense of the initializer.
14200 if (auto *DD = dyn_cast<DecompositionDecl>(D))
14201 for (auto *BD : DD->bindings())
14202 BD->setInvalidDecl();
14203
14204 // Auto types are meaningless if we can't make sense of the initializer.
14205 if (VD->getType()->isUndeducedType()) {
14206 D->setInvalidDecl();
14207 return;
14208 }
14209
14210 QualType Ty = VD->getType();
14211 if (Ty->isDependentType()) return;
14212
14213 // Require a complete type.
14215 Context.getBaseElementType(Ty),
14216 diag::err_typecheck_decl_incomplete_type)) {
14217 VD->setInvalidDecl();
14218 return;
14219 }
14220
14221 // Require a non-abstract type.
14222 if (RequireNonAbstractType(VD->getLocation(), Ty,
14223 diag::err_abstract_type_in_decl,
14225 VD->setInvalidDecl();
14226 return;
14227 }
14228
14229 // Don't bother complaining about constructors or destructors,
14230 // though.
14231}
14232
14234 // If there is no declaration, there was an error parsing it. Just ignore it.
14235 if (!RealDecl)
14236 return;
14237
14238 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
14239 QualType Type = Var->getType();
14240
14241 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
14242 if (isa<DecompositionDecl>(RealDecl)) {
14243 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
14244 Var->setInvalidDecl();
14245 return;
14246 }
14247
14248 if (Type->isUndeducedType() &&
14249 DeduceVariableDeclarationType(Var, false, nullptr))
14250 return;
14251
14252 // C++11 [class.static.data]p3: A static data member can be declared with
14253 // the constexpr specifier; if so, its declaration shall specify
14254 // a brace-or-equal-initializer.
14255 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
14256 // the definition of a variable [...] or the declaration of a static data
14257 // member.
14258 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
14259 !Var->isThisDeclarationADemotedDefinition()) {
14260 if (Var->isStaticDataMember()) {
14261 // C++1z removes the relevant rule; the in-class declaration is always
14262 // a definition there.
14263 if (!getLangOpts().CPlusPlus17 &&
14264 !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14265 Diag(Var->getLocation(),
14266 diag::err_constexpr_static_mem_var_requires_init)
14267 << Var;
14268 Var->setInvalidDecl();
14269 return;
14270 }
14271 } else {
14272 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
14273 Var->setInvalidDecl();
14274 return;
14275 }
14276 }
14277
14278 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
14279 // be initialized.
14280 if (!Var->isInvalidDecl() &&
14281 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
14282 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
14283 bool HasConstExprDefaultConstructor = false;
14284 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14285 for (auto *Ctor : RD->ctors()) {
14286 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
14287 Ctor->getMethodQualifiers().getAddressSpace() ==
14289 HasConstExprDefaultConstructor = true;
14290 }
14291 }
14292 }
14293 if (!HasConstExprDefaultConstructor) {
14294 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
14295 Var->setInvalidDecl();
14296 return;
14297 }
14298 }
14299
14300 // HLSL variable with the `vk::constant_id` attribute must be initialized.
14301 if (!Var->isInvalidDecl() && Var->hasAttr<HLSLVkConstantIdAttr>()) {
14302 Diag(Var->getLocation(), diag::err_specialization_const);
14303 Var->setInvalidDecl();
14304 return;
14305 }
14306
14307 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
14308 if (Var->getStorageClass() == SC_Extern) {
14309 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
14310 << Var;
14311 Var->setInvalidDecl();
14312 return;
14313 }
14314 if (RequireCompleteType(Var->getLocation(), Var->getType(),
14315 diag::err_typecheck_decl_incomplete_type)) {
14316 Var->setInvalidDecl();
14317 return;
14318 }
14319 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14320 if (!RD->hasTrivialDefaultConstructor()) {
14321 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
14322 Var->setInvalidDecl();
14323 return;
14324 }
14325 }
14326 // The declaration is uninitialized, no need for further checks.
14327 return;
14328 }
14329
14330 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
14331 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
14332 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
14333 checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
14335 NTCUK_Init);
14336
14337 switch (DefKind) {
14339 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
14340 break;
14341
14342 // We have an out-of-line definition of a static data member
14343 // that has an in-class initializer, so we type-check this like
14344 // a declaration.
14345 //
14346 [[fallthrough]];
14347
14349 // It's only a declaration.
14350
14351 // Block scope. C99 6.7p7: If an identifier for an object is
14352 // declared with no linkage (C99 6.2.2p6), the type for the
14353 // object shall be complete.
14354 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
14355 !Var->hasLinkage() && !Var->isInvalidDecl() &&
14356 RequireCompleteType(Var->getLocation(), Type,
14357 diag::err_typecheck_decl_incomplete_type))
14358 Var->setInvalidDecl();
14359
14360 // Make sure that the type is not abstract.
14361 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14362 RequireNonAbstractType(Var->getLocation(), Type,
14363 diag::err_abstract_type_in_decl,
14365 Var->setInvalidDecl();
14366 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14367 Var->getStorageClass() == SC_PrivateExtern) {
14368 Diag(Var->getLocation(), diag::warn_private_extern);
14369 Diag(Var->getLocation(), diag::note_private_extern);
14370 }
14371
14372 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
14373 !Var->isInvalidDecl())
14374 ExternalDeclarations.push_back(Var);
14375
14376 return;
14377
14379 // File scope. C99 6.9.2p2: A declaration of an identifier for an
14380 // object that has file scope without an initializer, and without a
14381 // storage-class specifier or with the storage-class specifier "static",
14382 // constitutes a tentative definition. Note: A tentative definition with
14383 // external linkage is valid (C99 6.2.2p5).
14384 if (!Var->isInvalidDecl()) {
14385 if (const IncompleteArrayType *ArrayT
14386 = Context.getAsIncompleteArrayType(Type)) {
14388 Var->getLocation(), ArrayT->getElementType(),
14389 diag::err_array_incomplete_or_sizeless_type))
14390 Var->setInvalidDecl();
14391 }
14392 if (Var->getStorageClass() == SC_Static) {
14393 // C99 6.9.2p3: If the declaration of an identifier for an object is
14394 // a tentative definition and has internal linkage (C99 6.2.2p3), the
14395 // declared type shall not be an incomplete type.
14396 // NOTE: code such as the following
14397 // static struct s;
14398 // struct s { int a; };
14399 // is accepted by gcc. Hence here we issue a warning instead of
14400 // an error and we do not invalidate the static declaration.
14401 // NOTE: to avoid multiple warnings, only check the first declaration.
14402 if (Var->isFirstDecl())
14403 RequireCompleteType(Var->getLocation(), Type,
14404 diag::ext_typecheck_decl_incomplete_type,
14405 Type->isArrayType());
14406 }
14407 }
14408
14409 // Record the tentative definition; we're done.
14410 if (!Var->isInvalidDecl())
14411 TentativeDefinitions.push_back(Var);
14412 return;
14413 }
14414
14415 // Provide a specific diagnostic for uninitialized variable definitions
14416 // with incomplete array type, unless it is a global unbounded HLSL resource
14417 // array.
14418 if (Type->isIncompleteArrayType() &&
14419 !(getLangOpts().HLSL && Var->hasGlobalStorage() &&
14421 if (Var->isConstexpr())
14422 Diag(Var->getLocation(), diag::err_constexpr_var_requires_const_init)
14423 << Var;
14424 else
14425 Diag(Var->getLocation(),
14426 diag::err_typecheck_incomplete_array_needs_initializer);
14427 Var->setInvalidDecl();
14428 return;
14429 }
14430
14431 // Provide a specific diagnostic for uninitialized variable
14432 // definitions with reference type.
14433 if (Type->isReferenceType()) {
14434 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
14435 << Var << SourceRange(Var->getLocation(), Var->getLocation());
14436 return;
14437 }
14438
14439 // Do not attempt to type-check the default initializer for a
14440 // variable with dependent type.
14441 if (Type->isDependentType())
14442 return;
14443
14444 if (Var->isInvalidDecl())
14445 return;
14446
14447 if (!Var->hasAttr<AliasAttr>()) {
14448 if (RequireCompleteType(Var->getLocation(),
14449 Context.getBaseElementType(Type),
14450 diag::err_typecheck_decl_incomplete_type)) {
14451 Var->setInvalidDecl();
14452 return;
14453 }
14454 } else {
14455 return;
14456 }
14457
14458 // The variable can not have an abstract class type.
14459 if (RequireNonAbstractType(Var->getLocation(), Type,
14460 diag::err_abstract_type_in_decl,
14462 Var->setInvalidDecl();
14463 return;
14464 }
14465
14466 // In C, if the definition is const-qualified and has no initializer, it
14467 // is left uninitialized unless it has static or thread storage duration.
14468 if (!getLangOpts().CPlusPlus && Type.isConstQualified()) {
14469 unsigned DiagID = diag::warn_default_init_const_unsafe;
14470 if (Var->getStorageDuration() == SD_Static ||
14471 Var->getStorageDuration() == SD_Thread)
14472 DiagID = diag::warn_default_init_const;
14473
14474 bool EmitCppCompat = !Diags.isIgnored(
14475 diag::warn_cxx_compat_hack_fake_diagnostic_do_not_emit,
14476 Var->getLocation());
14477
14478 Diag(Var->getLocation(), DiagID) << Type << EmitCppCompat;
14479 }
14480
14481 // Check for jumps past the implicit initializer. C++0x
14482 // clarifies that this applies to a "variable with automatic
14483 // storage duration", not a "local variable".
14484 // C++11 [stmt.dcl]p3
14485 // A program that jumps from a point where a variable with automatic
14486 // storage duration is not in scope to a point where it is in scope is
14487 // ill-formed unless the variable has scalar type, class type with a
14488 // trivial default constructor and a trivial destructor, a cv-qualified
14489 // version of one of these types, or an array of one of the preceding
14490 // types and is declared without an initializer.
14491 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
14492 if (const auto *CXXRecord =
14493 Context.getBaseElementType(Type)->getAsCXXRecordDecl()) {
14494 // Mark the function (if we're in one) for further checking even if the
14495 // looser rules of C++11 do not require such checks, so that we can
14496 // diagnose incompatibilities with C++98.
14497 if (!CXXRecord->isPOD())
14499 }
14500 }
14501 // In OpenCL, we can't initialize objects in the __local address space,
14502 // even implicitly, so don't synthesize an implicit initializer.
14503 if (getLangOpts().OpenCL &&
14504 Var->getType().getAddressSpace() == LangAS::opencl_local)
14505 return;
14506
14507 // Handle HLSL uninitialized decls
14508 if (getLangOpts().HLSL && HLSL().ActOnUninitializedVarDecl(Var))
14509 return;
14510
14511 // HLSL input variables are expected to be externally initialized, even
14512 // when marked `static`.
14513 if (getLangOpts().HLSL &&
14514 Var->getType().getAddressSpace() == LangAS::hlsl_input)
14515 return;
14516
14517 // C++03 [dcl.init]p9:
14518 // If no initializer is specified for an object, and the
14519 // object is of (possibly cv-qualified) non-POD class type (or
14520 // array thereof), the object shall be default-initialized; if
14521 // the object is of const-qualified type, the underlying class
14522 // type shall have a user-declared default
14523 // constructor. Otherwise, if no initializer is specified for
14524 // a non- static object, the object and its subobjects, if
14525 // any, have an indeterminate initial value); if the object
14526 // or any of its subobjects are of const-qualified type, the
14527 // program is ill-formed.
14528 // C++0x [dcl.init]p11:
14529 // If no initializer is specified for an object, the object is
14530 // default-initialized; [...].
14533 = InitializationKind::CreateDefault(Var->getLocation());
14534
14535 InitializationSequence InitSeq(*this, Entity, Kind, {});
14536 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, {});
14537
14538 if (Init.get()) {
14539 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
14540 // This is important for template substitution.
14541 Var->setInitStyle(VarDecl::CallInit);
14542 } else if (Init.isInvalid()) {
14543 // If default-init fails, attach a recovery-expr initializer to track
14544 // that initialization was attempted and failed.
14545 auto RecoveryExpr =
14546 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
14547 if (RecoveryExpr.get())
14548 Var->setInit(RecoveryExpr.get());
14549 }
14550
14552 }
14553}
14554
14556 // If there is no declaration, there was an error parsing it. Ignore it.
14557 if (!D)
14558 return;
14559
14560 VarDecl *VD = dyn_cast<VarDecl>(D);
14561 if (!VD) {
14562 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
14563 D->setInvalidDecl();
14564 return;
14565 }
14566
14567 VD->setCXXForRangeDecl(true);
14568
14569 // for-range-declaration cannot be given a storage class specifier.
14570 int Error = -1;
14571 switch (VD->getStorageClass()) {
14572 case SC_None:
14573 break;
14574 case SC_Extern:
14575 Error = 0;
14576 break;
14577 case SC_Static:
14578 Error = 1;
14579 break;
14580 case SC_PrivateExtern:
14581 Error = 2;
14582 break;
14583 case SC_Auto:
14584 Error = 3;
14585 break;
14586 case SC_Register:
14587 Error = 4;
14588 break;
14589 }
14590
14591 // for-range-declaration cannot be given a storage class specifier con't.
14592 switch (VD->getTSCSpec()) {
14593 case TSCS_thread_local:
14594 Error = 6;
14595 break;
14596 case TSCS___thread:
14597 case TSCS__Thread_local:
14598 case TSCS_unspecified:
14599 break;
14600 }
14601
14602 if (Error != -1) {
14603 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
14604 << VD << Error;
14605 D->setInvalidDecl();
14606 }
14607}
14608
14610 IdentifierInfo *Ident,
14611 ParsedAttributes &Attrs) {
14612 // C++1y [stmt.iter]p1:
14613 // A range-based for statement of the form
14614 // for ( for-range-identifier : for-range-initializer ) statement
14615 // is equivalent to
14616 // for ( auto&& for-range-identifier : for-range-initializer ) statement
14617 DeclSpec DS(Attrs.getPool().getFactory());
14618
14619 const char *PrevSpec;
14620 unsigned DiagID;
14621 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
14623
14625 D.SetIdentifier(Ident, IdentLoc);
14626 D.takeAttributes(Attrs);
14627
14628 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
14629 IdentLoc);
14630 Decl *Var = ActOnDeclarator(S, D);
14631 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
14633 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
14634 Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
14635 : IdentLoc);
14636}
14637
14639 if (var->isInvalidDecl()) return;
14640
14642
14643 if (getLangOpts().OpenCL) {
14644 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
14645 // initialiser
14646 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
14647 !var->hasInit()) {
14648 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
14649 << 1 /*Init*/;
14650 var->setInvalidDecl();
14651 return;
14652 }
14653 }
14654
14655 // In Objective-C, don't allow jumps past the implicit initialization of a
14656 // local retaining variable.
14657 if (getLangOpts().ObjC &&
14658 var->hasLocalStorage()) {
14659 switch (var->getType().getObjCLifetime()) {
14663 break;
14664
14668 break;
14669 }
14670 }
14671
14672 if (var->hasLocalStorage() &&
14673 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
14675
14676 // Warn about externally-visible variables being defined without a
14677 // prior declaration. We only want to do this for global
14678 // declarations, but we also specifically need to avoid doing it for
14679 // class members because the linkage of an anonymous class can
14680 // change if it's later given a typedef name.
14681 if (var->isThisDeclarationADefinition() &&
14682 var->getDeclContext()->getRedeclContext()->isFileContext() &&
14683 var->isExternallyVisible() && var->hasLinkage() &&
14684 !var->isInline() && !var->getDescribedVarTemplate() &&
14685 var->getStorageClass() != SC_Register &&
14687 !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
14688 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
14689 var->getLocation())) {
14690 // Find a previous declaration that's not a definition.
14691 VarDecl *prev = var->getPreviousDecl();
14692 while (prev && prev->isThisDeclarationADefinition())
14693 prev = prev->getPreviousDecl();
14694
14695 if (!prev) {
14696 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
14697 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14698 << /* variable */ 0;
14699 }
14700 }
14701
14702 // Cache the result of checking for constant initialization.
14703 std::optional<bool> CacheHasConstInit;
14704 const Expr *CacheCulprit = nullptr;
14705 auto checkConstInit = [&]() mutable {
14706 const Expr *Init = var->getInit();
14707 if (Init->isInstantiationDependent())
14708 return true;
14709
14710 if (!CacheHasConstInit)
14711 CacheHasConstInit = var->getInit()->isConstantInitializer(
14712 Context, var->getType()->isReferenceType(), &CacheCulprit);
14713 return *CacheHasConstInit;
14714 };
14715
14716 if (var->getTLSKind() == VarDecl::TLS_Static) {
14717 if (var->getType().isDestructedType()) {
14718 // GNU C++98 edits for __thread, [basic.start.term]p3:
14719 // The type of an object with thread storage duration shall not
14720 // have a non-trivial destructor.
14721 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
14723 Diag(var->getLocation(), diag::note_use_thread_local);
14724 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
14725 if (!checkConstInit()) {
14726 // GNU C++98 edits for __thread, [basic.start.init]p4:
14727 // An object of thread storage duration shall not require dynamic
14728 // initialization.
14729 // FIXME: Need strict checking here.
14730 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
14731 << CacheCulprit->getSourceRange();
14733 Diag(var->getLocation(), diag::note_use_thread_local);
14734 }
14735 }
14736 }
14737
14738
14739 if (!var->getType()->isStructureType() && var->hasInit() &&
14740 isa<InitListExpr>(var->getInit())) {
14741 const auto *ILE = cast<InitListExpr>(var->getInit());
14742 unsigned NumInits = ILE->getNumInits();
14743 if (NumInits > 2)
14744 for (unsigned I = 0; I < NumInits; ++I) {
14745 const auto *Init = ILE->getInit(I);
14746 if (!Init)
14747 break;
14748 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14749 if (!SL)
14750 break;
14751
14752 unsigned NumConcat = SL->getNumConcatenated();
14753 // Diagnose missing comma in string array initialization.
14754 // Do not warn when all the elements in the initializer are concatenated
14755 // together. Do not warn for macros too.
14756 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
14757 bool OnlyOneMissingComma = true;
14758 for (unsigned J = I + 1; J < NumInits; ++J) {
14759 const auto *Init = ILE->getInit(J);
14760 if (!Init)
14761 break;
14762 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14763 if (!SLJ || SLJ->getNumConcatenated() > 1) {
14764 OnlyOneMissingComma = false;
14765 break;
14766 }
14767 }
14768
14769 if (OnlyOneMissingComma) {
14771 for (unsigned i = 0; i < NumConcat - 1; ++i)
14772 Hints.push_back(FixItHint::CreateInsertion(
14773 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
14774
14775 Diag(SL->getStrTokenLoc(1),
14776 diag::warn_concatenated_literal_array_init)
14777 << Hints;
14778 Diag(SL->getBeginLoc(),
14779 diag::note_concatenated_string_literal_silence);
14780 }
14781 // In any case, stop now.
14782 break;
14783 }
14784 }
14785 }
14786
14787
14788 QualType type = var->getType();
14789
14790 if (var->hasAttr<BlocksAttr>())
14792
14793 Expr *Init = var->getInit();
14794 bool GlobalStorage = var->hasGlobalStorage();
14795 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
14796 QualType baseType = Context.getBaseElementType(type);
14797 bool HasConstInit = true;
14798
14799 if (getLangOpts().C23 && var->isConstexpr() && !Init)
14800 Diag(var->getLocation(), diag::err_constexpr_var_requires_const_init)
14801 << var;
14802
14803 // Check whether the initializer is sufficiently constant.
14804 if ((getLangOpts().CPlusPlus || (getLangOpts().C23 && var->isConstexpr())) &&
14805 !type->isDependentType() && Init && !Init->isValueDependent() &&
14806 (GlobalStorage || var->isConstexpr() ||
14807 var->mightBeUsableInConstantExpressions(Context))) {
14808 // If this variable might have a constant initializer or might be usable in
14809 // constant expressions, check whether or not it actually is now. We can't
14810 // do this lazily, because the result might depend on things that change
14811 // later, such as which constexpr functions happen to be defined.
14813 if (!getLangOpts().CPlusPlus11 && !getLangOpts().C23) {
14814 // Prior to C++11, in contexts where a constant initializer is required,
14815 // the set of valid constant initializers is described by syntactic rules
14816 // in [expr.const]p2-6.
14817 // FIXME: Stricter checking for these rules would be useful for constinit /
14818 // -Wglobal-constructors.
14819 HasConstInit = checkConstInit();
14820
14821 // Compute and cache the constant value, and remember that we have a
14822 // constant initializer.
14823 if (HasConstInit) {
14824 if (var->isStaticDataMember() && !var->isInline() &&
14825 var->getLexicalDeclContext()->isRecord() &&
14826 type->isIntegralOrEnumerationType()) {
14827 // In C++98, in-class initialization for a static data member must
14828 // be an integer constant expression.
14829 if (!Init->isIntegerConstantExpr(Context)) {
14830 Diag(Init->getExprLoc(),
14831 diag::ext_in_class_initializer_non_constant)
14832 << Init->getSourceRange();
14833 }
14834 }
14835 (void)var->checkForConstantInitialization(Notes);
14836 Notes.clear();
14837 } else if (CacheCulprit) {
14838 Notes.emplace_back(CacheCulprit->getExprLoc(),
14839 PDiag(diag::note_invalid_subexpr_in_const_expr));
14840 Notes.back().second << CacheCulprit->getSourceRange();
14841 }
14842 } else {
14843 // Evaluate the initializer to see if it's a constant initializer.
14844 HasConstInit = var->checkForConstantInitialization(Notes);
14845 }
14846
14847 if (HasConstInit) {
14848 // FIXME: Consider replacing the initializer with a ConstantExpr.
14849 } else if (var->isConstexpr()) {
14850 SourceLocation DiagLoc = var->getLocation();
14851 // If the note doesn't add any useful information other than a source
14852 // location, fold it into the primary diagnostic.
14853 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14854 diag::note_invalid_subexpr_in_const_expr) {
14855 DiagLoc = Notes[0].first;
14856 Notes.clear();
14857 }
14858 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
14859 << var << Init->getSourceRange();
14860 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
14861 Diag(Notes[I].first, Notes[I].second);
14862 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
14863 auto *Attr = var->getAttr<ConstInitAttr>();
14864 Diag(var->getLocation(), diag::err_require_constant_init_failed)
14865 << Init->getSourceRange();
14866 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
14867 << Attr->getRange() << Attr->isConstinit();
14868 for (auto &it : Notes)
14869 Diag(it.first, it.second);
14870 } else if (var->isStaticDataMember() && !var->isInline() &&
14871 var->getLexicalDeclContext()->isRecord()) {
14872 Diag(var->getLocation(), diag::err_in_class_initializer_non_constant)
14873 << Init->getSourceRange();
14874 for (auto &it : Notes)
14875 Diag(it.first, it.second);
14876 var->setInvalidDecl();
14877 } else if (IsGlobal &&
14878 !getDiagnostics().isIgnored(diag::warn_global_constructor,
14879 var->getLocation())) {
14880 // Warn about globals which don't have a constant initializer. Don't
14881 // warn about globals with a non-trivial destructor because we already
14882 // warned about them.
14883 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
14884 if (!(RD && !RD->hasTrivialDestructor())) {
14885 // checkConstInit() here permits trivial default initialization even in
14886 // C++11 onwards, where such an initializer is not a constant initializer
14887 // but nonetheless doesn't require a global constructor.
14888 if (!checkConstInit())
14889 Diag(var->getLocation(), diag::warn_global_constructor)
14890 << Init->getSourceRange();
14891 }
14892 }
14893 }
14894
14895 // Apply section attributes and pragmas to global variables.
14896 if (GlobalStorage && var->isThisDeclarationADefinition() &&
14898 PragmaStack<StringLiteral *> *Stack = nullptr;
14899 int SectionFlags = ASTContext::PSF_Read;
14900 bool MSVCEnv =
14901 Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment();
14902 std::optional<QualType::NonConstantStorageReason> Reason;
14903 if (HasConstInit &&
14904 !(Reason = var->getType().isNonConstantStorage(Context, true, false))) {
14905 Stack = &ConstSegStack;
14906 } else {
14907 SectionFlags |= ASTContext::PSF_Write;
14908 Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack;
14909 }
14910 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
14911 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
14912 SectionFlags |= ASTContext::PSF_Implicit;
14913 UnifySection(SA->getName(), SectionFlags, var);
14914 } else if (Stack->CurrentValue) {
14915 if (Stack != &ConstSegStack && MSVCEnv &&
14916 ConstSegStack.CurrentValue != ConstSegStack.DefaultValue &&
14917 var->getType().isConstQualified()) {
14918 assert((!Reason || Reason != QualType::NonConstantStorageReason::
14919 NonConstNonReferenceType) &&
14920 "This case should've already been handled elsewhere");
14921 Diag(var->getLocation(), diag::warn_section_msvc_compat)
14922 << var << ConstSegStack.CurrentValue << (int)(!HasConstInit
14924 : *Reason);
14925 }
14926 SectionFlags |= ASTContext::PSF_Implicit;
14927 auto SectionName = Stack->CurrentValue->getString();
14928 var->addAttr(SectionAttr::CreateImplicit(Context, SectionName,
14929 Stack->CurrentPragmaLocation,
14930 SectionAttr::Declspec_allocate));
14931 if (UnifySection(SectionName, SectionFlags, var))
14932 var->dropAttr<SectionAttr>();
14933 }
14934
14935 // Apply the init_seg attribute if this has an initializer. If the
14936 // initializer turns out to not be dynamic, we'll end up ignoring this
14937 // attribute.
14938 if (CurInitSeg && var->getInit())
14939 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
14940 CurInitSegLoc));
14941 }
14942
14943 // All the following checks are C++ only.
14944 if (!getLangOpts().CPlusPlus) {
14945 // If this variable must be emitted, add it as an initializer for the
14946 // current module.
14947 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14948 Context.addModuleInitializer(ModuleScopes.back().Module, var);
14949 return;
14950 }
14951
14953
14954 // Require the destructor.
14955 if (!type->isDependentType())
14956 if (auto *RD = baseType->getAsCXXRecordDecl())
14958
14959 // If this variable must be emitted, add it as an initializer for the current
14960 // module.
14961 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14962 Context.addModuleInitializer(ModuleScopes.back().Module, var);
14963
14964 // Build the bindings if this is a structured binding declaration.
14965 if (auto *DD = dyn_cast<DecompositionDecl>(var))
14967}
14968
14970 assert(VD->isStaticLocal());
14971
14972 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14973
14974 // Find outermost function when VD is in lambda function.
14975 while (FD && !getDLLAttr(FD) &&
14976 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
14977 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
14978 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
14979 }
14980
14981 if (!FD)
14982 return;
14983
14984 // Static locals inherit dll attributes from their function.
14985 if (Attr *A = getDLLAttr(FD)) {
14986 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
14987 NewAttr->setInherited(true);
14988 VD->addAttr(NewAttr);
14989 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
14990 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
14991 NewAttr->setInherited(true);
14992 VD->addAttr(NewAttr);
14993
14994 // Export this function to enforce exporting this static variable even
14995 // if it is not used in this compilation unit.
14996 if (!FD->hasAttr<DLLExportAttr>())
14997 FD->addAttr(NewAttr);
14998
14999 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
15000 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
15001 NewAttr->setInherited(true);
15002 VD->addAttr(NewAttr);
15003 }
15004}
15005
15007 assert(VD->getTLSKind());
15008
15009 // Perform TLS alignment check here after attributes attached to the variable
15010 // which may affect the alignment have been processed. Only perform the check
15011 // if the target has a maximum TLS alignment (zero means no constraints).
15012 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
15013 // Protect the check so that it's not performed on dependent types and
15014 // dependent alignments (we can't determine the alignment in that case).
15015 if (!VD->hasDependentAlignment()) {
15016 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
15017 if (Context.getDeclAlign(VD) > MaxAlignChars) {
15018 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
15019 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
15020 << (unsigned)MaxAlignChars.getQuantity();
15021 }
15022 }
15023 }
15024}
15025
15027 // Note that we are no longer parsing the initializer for this declaration.
15028 ParsingInitForAutoVars.erase(ThisDecl);
15029
15030 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
15031 if (!VD)
15032 return;
15033
15034 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
15036 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
15037 if (PragmaClangBSSSection.Valid)
15038 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
15039 Context, PragmaClangBSSSection.SectionName,
15040 PragmaClangBSSSection.PragmaLocation));
15041 if (PragmaClangDataSection.Valid)
15042 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
15043 Context, PragmaClangDataSection.SectionName,
15044 PragmaClangDataSection.PragmaLocation));
15045 if (PragmaClangRodataSection.Valid)
15046 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
15047 Context, PragmaClangRodataSection.SectionName,
15048 PragmaClangRodataSection.PragmaLocation));
15049 if (PragmaClangRelroSection.Valid)
15050 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
15051 Context, PragmaClangRelroSection.SectionName,
15052 PragmaClangRelroSection.PragmaLocation));
15053 }
15054
15055 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
15056 for (auto *BD : DD->bindings()) {
15058 }
15059 }
15060
15061 CheckInvalidBuiltinCountedByRef(VD->getInit(),
15063
15064 checkAttributesAfterMerging(*this, *VD);
15065
15066 if (VD->isStaticLocal())
15068
15069 if (VD->getTLSKind())
15071
15072 // Perform check for initializers of device-side global variables.
15073 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
15074 // 7.5). We must also apply the same checks to all __shared__
15075 // variables whether they are local or not. CUDA also allows
15076 // constant initializers for __constant__ and __device__ variables.
15077 if (getLangOpts().CUDA)
15079
15080 // Grab the dllimport or dllexport attribute off of the VarDecl.
15081 const InheritableAttr *DLLAttr = getDLLAttr(VD);
15082
15083 // Imported static data members cannot be defined out-of-line.
15084 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
15085 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
15087 // We allow definitions of dllimport class template static data members
15088 // with a warning.
15091 bool IsClassTemplateMember =
15093 Context->getDescribedClassTemplate();
15094
15095 Diag(VD->getLocation(),
15096 IsClassTemplateMember
15097 ? diag::warn_attribute_dllimport_static_field_definition
15098 : diag::err_attribute_dllimport_static_field_definition);
15099 Diag(IA->getLocation(), diag::note_attribute);
15100 if (!IsClassTemplateMember)
15101 VD->setInvalidDecl();
15102 }
15103 }
15104
15105 // dllimport/dllexport variables cannot be thread local, their TLS index
15106 // isn't exported with the variable.
15107 if (DLLAttr && VD->getTLSKind()) {
15108 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
15109 if (F && getDLLAttr(F)) {
15110 assert(VD->isStaticLocal());
15111 // But if this is a static local in a dlimport/dllexport function, the
15112 // function will never be inlined, which means the var would never be
15113 // imported, so having it marked import/export is safe.
15114 } else {
15115 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
15116 << DLLAttr;
15117 VD->setInvalidDecl();
15118 }
15119 }
15120
15121 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
15122 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
15123 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
15124 << Attr;
15125 VD->dropAttr<UsedAttr>();
15126 }
15127 }
15128 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
15129 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
15130 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
15131 << Attr;
15132 VD->dropAttr<RetainAttr>();
15133 }
15134 }
15135
15136 const DeclContext *DC = VD->getDeclContext();
15137 // If there's a #pragma GCC visibility in scope, and this isn't a class
15138 // member, set the visibility of this variable.
15141
15142 // FIXME: Warn on unused var template partial specializations.
15145
15146 // Now we have parsed the initializer and can update the table of magic
15147 // tag values.
15148 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
15150 return;
15151
15152 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
15153 const Expr *MagicValueExpr = VD->getInit();
15154 if (!MagicValueExpr) {
15155 continue;
15156 }
15157 std::optional<llvm::APSInt> MagicValueInt;
15158 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
15159 Diag(I->getRange().getBegin(),
15160 diag::err_type_tag_for_datatype_not_ice)
15161 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15162 continue;
15163 }
15164 if (MagicValueInt->getActiveBits() > 64) {
15165 Diag(I->getRange().getBegin(),
15166 diag::err_type_tag_for_datatype_too_large)
15167 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15168 continue;
15169 }
15170 uint64_t MagicValue = MagicValueInt->getZExtValue();
15171 RegisterTypeTagForDatatype(I->getArgumentKind(),
15172 MagicValue,
15173 I->getMatchingCType(),
15174 I->getLayoutCompatible(),
15175 I->getMustBeNull());
15176 }
15177}
15178
15180 auto *VD = dyn_cast<VarDecl>(DD);
15181 return VD && !VD->getType()->hasAutoForTrailingReturnType();
15182}
15183
15185 ArrayRef<Decl *> Group) {
15187
15188 if (DS.isTypeSpecOwned())
15189 Decls.push_back(DS.getRepAsDecl());
15190
15191 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
15192 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
15193 bool DiagnosedMultipleDecomps = false;
15194 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
15195 bool DiagnosedNonDeducedAuto = false;
15196
15197 for (Decl *D : Group) {
15198 if (!D)
15199 continue;
15200 // Check if the Decl has been declared in '#pragma omp declare target'
15201 // directive and has static storage duration.
15202 if (auto *VD = dyn_cast<VarDecl>(D);
15203 LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&
15204 VD->hasGlobalStorage())
15206 // For declarators, there are some additional syntactic-ish checks we need
15207 // to perform.
15208 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
15209 if (!FirstDeclaratorInGroup)
15210 FirstDeclaratorInGroup = DD;
15211 if (!FirstDecompDeclaratorInGroup)
15212 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
15213 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
15214 !hasDeducedAuto(DD))
15215 FirstNonDeducedAutoInGroup = DD;
15216
15217 if (FirstDeclaratorInGroup != DD) {
15218 // A decomposition declaration cannot be combined with any other
15219 // declaration in the same group.
15220 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
15221 Diag(FirstDecompDeclaratorInGroup->getLocation(),
15222 diag::err_decomp_decl_not_alone)
15223 << FirstDeclaratorInGroup->getSourceRange()
15224 << DD->getSourceRange();
15225 DiagnosedMultipleDecomps = true;
15226 }
15227
15228 // A declarator that uses 'auto' in any way other than to declare a
15229 // variable with a deduced type cannot be combined with any other
15230 // declarator in the same group.
15231 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
15232 Diag(FirstNonDeducedAutoInGroup->getLocation(),
15233 diag::err_auto_non_deduced_not_alone)
15234 << FirstNonDeducedAutoInGroup->getType()
15236 << FirstDeclaratorInGroup->getSourceRange()
15237 << DD->getSourceRange();
15238 DiagnosedNonDeducedAuto = true;
15239 }
15240 }
15241 }
15242
15243 Decls.push_back(D);
15244 }
15245
15247 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
15248 handleTagNumbering(Tag, S);
15249 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
15251 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
15252 }
15253 }
15254
15255 return BuildDeclaratorGroup(Decls);
15256}
15257
15260 // C++14 [dcl.spec.auto]p7: (DR1347)
15261 // If the type that replaces the placeholder type is not the same in each
15262 // deduction, the program is ill-formed.
15263 if (Group.size() > 1) {
15264 QualType Deduced;
15265 VarDecl *DeducedDecl = nullptr;
15266 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
15267 VarDecl *D = dyn_cast<VarDecl>(Group[i]);
15268 if (!D || D->isInvalidDecl())
15269 break;
15270 DeducedType *DT = D->getType()->getContainedDeducedType();
15271 if (!DT || DT->getDeducedType().isNull())
15272 continue;
15273 if (Deduced.isNull()) {
15274 Deduced = DT->getDeducedType();
15275 DeducedDecl = D;
15276 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
15277 auto *AT = dyn_cast<AutoType>(DT);
15278 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
15279 diag::err_auto_different_deductions)
15280 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
15281 << DeducedDecl->getDeclName() << DT->getDeducedType()
15282 << D->getDeclName();
15283 if (DeducedDecl->hasInit())
15284 Dia << DeducedDecl->getInit()->getSourceRange();
15285 if (D->getInit())
15286 Dia << D->getInit()->getSourceRange();
15287 D->setInvalidDecl();
15288 break;
15289 }
15290 }
15291 }
15292
15294
15295 return DeclGroupPtrTy::make(
15296 DeclGroupRef::Create(Context, Group.data(), Group.size()));
15297}
15298
15302
15304 // Don't parse the comment if Doxygen diagnostics are ignored.
15305 if (Group.empty() || !Group[0])
15306 return;
15307
15308 if (Diags.isIgnored(diag::warn_doc_param_not_found,
15309 Group[0]->getLocation()) &&
15310 Diags.isIgnored(diag::warn_unknown_comment_command_name,
15311 Group[0]->getLocation()))
15312 return;
15313
15314 if (Group.size() >= 2) {
15315 // This is a decl group. Normally it will contain only declarations
15316 // produced from declarator list. But in case we have any definitions or
15317 // additional declaration references:
15318 // 'typedef struct S {} S;'
15319 // 'typedef struct S *S;'
15320 // 'struct S *pS;'
15321 // FinalizeDeclaratorGroup adds these as separate declarations.
15322 Decl *MaybeTagDecl = Group[0];
15323 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
15324 Group = Group.slice(1);
15325 }
15326 }
15327
15328 // FIMXE: We assume every Decl in the group is in the same file.
15329 // This is false when preprocessor constructs the group from decls in
15330 // different files (e. g. macros or #include).
15331 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
15332}
15333
15335 // Check that there are no default arguments inside the type of this
15336 // parameter.
15337 if (getLangOpts().CPlusPlus)
15339
15340 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
15341 if (D.getCXXScopeSpec().isSet()) {
15342 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
15343 << D.getCXXScopeSpec().getRange();
15344 }
15345
15346 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
15347 // simple identifier except [...irrelevant cases...].
15348 switch (D.getName().getKind()) {
15350 break;
15351
15359 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
15361 break;
15362
15365 // GetNameForDeclarator would not produce a useful name in this case.
15366 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
15367 break;
15368 }
15369}
15370
15372 // This only matters in C.
15373 if (getLangOpts().CPlusPlus)
15374 return;
15375
15376 // This only matters if the declaration has a type.
15377 const auto *VD = dyn_cast<ValueDecl>(D);
15378 if (!VD)
15379 return;
15380
15381 // Get the type, this only matters for tag types.
15382 QualType QT = VD->getType();
15383 const auto *TD = QT->getAsTagDecl();
15384 if (!TD)
15385 return;
15386
15387 // Check if the tag declaration is lexically declared somewhere different
15388 // from the lexical declaration of the given object, then it will be hidden
15389 // in C++ and we should warn on it.
15390 if (!TD->getLexicalParent()->LexicallyEncloses(D->getLexicalDeclContext())) {
15391 unsigned Kind = TD->isEnum() ? 2 : TD->isUnion() ? 1 : 0;
15392 Diag(D->getLocation(), diag::warn_decl_hidden_in_cpp) << Kind;
15393 Diag(TD->getLocation(), diag::note_declared_at);
15394 }
15395}
15396
15398 SourceLocation ExplicitThisLoc) {
15399 if (!ExplicitThisLoc.isValid())
15400 return;
15401 assert(S.getLangOpts().CPlusPlus &&
15402 "explicit parameter in non-cplusplus mode");
15403 if (!S.getLangOpts().CPlusPlus23)
15404 S.Diag(ExplicitThisLoc, diag::err_cxx20_deducing_this)
15405 << P->getSourceRange();
15406
15407 // C++2b [dcl.fct/7] An explicit object parameter shall not be a function
15408 // parameter pack.
15409 if (P->isParameterPack()) {
15410 S.Diag(P->getBeginLoc(), diag::err_explicit_object_parameter_pack)
15411 << P->getSourceRange();
15412 return;
15413 }
15414 P->setExplicitObjectParameterLoc(ExplicitThisLoc);
15415 if (LambdaScopeInfo *LSI = S.getCurLambda())
15416 LSI->ExplicitObjectParameter = P;
15417}
15418
15420 SourceLocation ExplicitThisLoc) {
15421 const DeclSpec &DS = D.getDeclSpec();
15422
15423 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
15424 // C2y 6.7.7.4p4: A parameter declaration shall not specify a void type,
15425 // except for the special case of a single unnamed parameter of type void
15426 // with no storage class specifier, no type qualifier, and no following
15427 // ellipsis terminator.
15428 // Clang applies the C2y rules for 'register void' in all C language modes,
15429 // same as GCC, because it's questionable what that could possibly mean.
15430
15431 // C++03 [dcl.stc]p2 also permits 'auto'.
15432 StorageClass SC = SC_None;
15434 SC = SC_Register;
15435 // In C++11, the 'register' storage class specifier is deprecated.
15436 // In C++17, it is not allowed, but we tolerate it as an extension.
15437 if (getLangOpts().CPlusPlus11) {
15439 ? diag::ext_register_storage_class
15440 : diag::warn_deprecated_register)
15442 } else if (!getLangOpts().CPlusPlus &&
15444 D.getNumTypeObjects() == 0) {
15446 diag::err_invalid_storage_class_in_func_decl)
15449 }
15450 } else if (getLangOpts().CPlusPlus &&
15452 SC = SC_Auto;
15455 diag::err_invalid_storage_class_in_func_decl);
15457 }
15458
15460 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
15462 if (DS.isInlineSpecified())
15463 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
15464 << getLangOpts().CPlusPlus17;
15465 if (DS.hasConstexprSpecifier())
15466 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
15467 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
15468
15470
15472
15474 QualType parmDeclType = TInfo->getType();
15475
15476 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
15477 const IdentifierInfo *II = D.getIdentifier();
15478 if (II) {
15481 LookupName(R, S);
15482 if (!R.empty()) {
15483 NamedDecl *PrevDecl = *R.begin();
15484 if (R.isSingleResult() && PrevDecl->isTemplateParameter()) {
15485 // Maybe we will complain about the shadowed template parameter.
15487 // Just pretend that we didn't see the previous declaration.
15488 PrevDecl = nullptr;
15489 }
15490 if (PrevDecl && S->isDeclScope(PrevDecl)) {
15491 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
15492 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15493 // Recover by removing the name
15494 II = nullptr;
15495 D.SetIdentifier(nullptr, D.getIdentifierLoc());
15496 D.setInvalidType(true);
15497 }
15498 }
15499 }
15500
15501 // Incomplete resource arrays are not allowed as function parameters in HLSL
15502 if (getLangOpts().HLSL && parmDeclType->isIncompleteArrayType() &&
15503 parmDeclType->isHLSLResourceRecordArray()) {
15505 diag::err_hlsl_incomplete_resource_array_in_function_param);
15506 D.setInvalidType(true);
15507 }
15508
15509 // Temporarily put parameter variables in the translation unit, not
15510 // the enclosing context. This prevents them from accidentally
15511 // looking like class members in C++.
15512 ParmVarDecl *New =
15513 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
15514 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
15515
15516 if (D.isInvalidType())
15517 New->setInvalidDecl();
15518
15519 CheckExplicitObjectParameter(*this, New, ExplicitThisLoc);
15520
15521 assert(S->isFunctionPrototypeScope());
15522 assert(S->getFunctionPrototypeDepth() >= 1);
15523 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
15525
15527
15528 // Add the parameter declaration into this scope.
15529 S->AddDecl(New);
15530 if (II)
15531 IdResolver.AddDecl(New);
15532
15534
15536 Diag(New->getLocation(), diag::err_module_private_local)
15539
15540 if (New->hasAttr<BlocksAttr>()) {
15541 Diag(New->getLocation(), diag::err_block_on_nonlocal);
15542 }
15543
15544 if (getLangOpts().OpenCL)
15546
15547 return New;
15548}
15549
15551 SourceLocation Loc,
15552 QualType T) {
15553 /* FIXME: setting StartLoc == Loc.
15554 Would it be worth to modify callers so as to provide proper source
15555 location for the unnamed parameters, embedding the parameter's type? */
15556 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
15557 T, Context.getTrivialTypeSourceInfo(T, Loc),
15558 SC_None, nullptr);
15559 Param->setImplicit();
15560 return Param;
15561}
15562
15564 // Don't diagnose unused-parameter errors in template instantiations; we
15565 // will already have done so in the template itself.
15567 return;
15568
15569 for (const ParmVarDecl *Parameter : Parameters) {
15570 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
15571 !Parameter->hasAttr<UnusedAttr>() &&
15572 !Parameter->getIdentifier()->isPlaceholder()) {
15573 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
15574 << Parameter->getDeclName();
15575 }
15576 }
15577}
15578
15580 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
15581 if (LangOpts.NumLargeByValueCopy == 0) // No check.
15582 return;
15583
15584 // Warn if the return value is pass-by-value and larger than the specified
15585 // threshold.
15586 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
15587 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
15588 if (Size > LangOpts.NumLargeByValueCopy)
15589 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
15590 }
15591
15592 // Warn if any parameter is pass-by-value and larger than the specified
15593 // threshold.
15594 for (const ParmVarDecl *Parameter : Parameters) {
15595 QualType T = Parameter->getType();
15596 if (T->isDependentType() || !T.isPODType(Context))
15597 continue;
15598 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
15599 if (Size > LangOpts.NumLargeByValueCopy)
15600 Diag(Parameter->getLocation(), diag::warn_parameter_size)
15601 << Parameter << Size;
15602 }
15603}
15604
15606 SourceLocation NameLoc,
15607 const IdentifierInfo *Name, QualType T,
15608 TypeSourceInfo *TSInfo, StorageClass SC) {
15609 // In ARC, infer a lifetime qualifier for appropriate parameter types.
15610 if (getLangOpts().ObjCAutoRefCount &&
15611 T.getObjCLifetime() == Qualifiers::OCL_None &&
15612 T->isObjCLifetimeType()) {
15613
15614 Qualifiers::ObjCLifetime lifetime;
15615
15616 // Special cases for arrays:
15617 // - if it's const, use __unsafe_unretained
15618 // - otherwise, it's an error
15619 if (T->isArrayType()) {
15620 if (!T.isConstQualified()) {
15624 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
15625 else
15626 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
15627 << TSInfo->getTypeLoc().getSourceRange();
15628 }
15630 } else {
15631 lifetime = T->getObjCARCImplicitLifetime();
15632 }
15633 T = Context.getLifetimeQualifiedType(T, lifetime);
15634 }
15635
15636 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
15637 Context.getAdjustedParameterType(T),
15638 TSInfo, SC, nullptr);
15639
15640 // Make a note if we created a new pack in the scope of a lambda, so that
15641 // we know that references to that pack must also be expanded within the
15642 // lambda scope.
15643 if (New->isParameterPack())
15644 if (auto *CSI = getEnclosingLambdaOrBlock())
15645 CSI->LocalPacks.push_back(New);
15646
15647 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
15648 New->getType().hasNonTrivialToPrimitiveCopyCUnion())
15649 checkNonTrivialCUnion(New->getType(), New->getLocation(),
15652
15653 // Parameter declarators cannot be interface types. All ObjC objects are
15654 // passed by reference.
15655 if (T->isObjCObjectType()) {
15656 SourceLocation TypeEndLoc =
15658 Diag(NameLoc,
15659 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
15660 << FixItHint::CreateInsertion(TypeEndLoc, "*");
15661 T = Context.getObjCObjectPointerType(T);
15662 New->setType(T);
15663 }
15664
15665 // __ptrauth is forbidden on parameters.
15666 if (T.getPointerAuth()) {
15667 Diag(NameLoc, diag::err_ptrauth_qualifier_invalid) << T << 1;
15668 New->setInvalidDecl();
15669 }
15670
15671 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
15672 // duration shall not be qualified by an address-space qualifier."
15673 // Since all parameters have automatic store duration, they can not have
15674 // an address space.
15675 if (T.getAddressSpace() != LangAS::Default &&
15676 // OpenCL allows function arguments declared to be an array of a type
15677 // to be qualified with an address space.
15678 !(getLangOpts().OpenCL &&
15679 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&
15680 // WebAssembly allows reference types as parameters. Funcref in particular
15681 // lives in a different address space.
15682 !(T->isFunctionPointerType() &&
15683 T.getAddressSpace() == LangAS::wasm_funcref)) {
15684 Diag(NameLoc, diag::err_arg_with_address_space);
15685 New->setInvalidDecl();
15686 }
15687
15688 // PPC MMA non-pointer types are not allowed as function argument types.
15689 if (Context.getTargetInfo().getTriple().isPPC64() &&
15690 PPC().CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
15691 New->setInvalidDecl();
15692 }
15693
15694 return New;
15695}
15696
15698 SourceLocation LocAfterDecls) {
15700
15701 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
15702 // in the declaration list shall have at least one declarator, those
15703 // declarators shall only declare identifiers from the identifier list, and
15704 // every identifier in the identifier list shall be declared.
15705 //
15706 // C89 3.7.1p5 "If a declarator includes an identifier list, only the
15707 // identifiers it names shall be declared in the declaration list."
15708 //
15709 // This is why we only diagnose in C99 and later. Note, the other conditions
15710 // listed are checked elsewhere.
15711 if (!FTI.hasPrototype) {
15712 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
15713 --i;
15714 if (FTI.Params[i].Param == nullptr) {
15715 if (getLangOpts().C99) {
15716 SmallString<256> Code;
15717 llvm::raw_svector_ostream(Code)
15718 << " int " << FTI.Params[i].Ident->getName() << ";\n";
15719 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
15720 << FTI.Params[i].Ident
15721 << FixItHint::CreateInsertion(LocAfterDecls, Code);
15722 }
15723
15724 // Implicitly declare the argument as type 'int' for lack of a better
15725 // type.
15726 AttributeFactory attrs;
15727 DeclSpec DS(attrs);
15728 const char* PrevSpec; // unused
15729 unsigned DiagID; // unused
15730 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
15731 DiagID, Context.getPrintingPolicy());
15732 // Use the identifier location for the type source range.
15733 DS.SetRangeStart(FTI.Params[i].IdentLoc);
15734 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
15737 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
15738 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
15739 }
15740 }
15741 }
15742}
15743
15744Decl *
15746 MultiTemplateParamsArg TemplateParameterLists,
15747 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
15748 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
15749 assert(D.isFunctionDeclarator() && "Not a function declarator!");
15750 Scope *ParentScope = FnBodyScope->getParent();
15751
15752 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
15753 // we define a non-templated function definition, we will create a declaration
15754 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
15755 // The base function declaration will have the equivalent of an `omp declare
15756 // variant` annotation which specifies the mangled definition as a
15757 // specialization function under the OpenMP context defined as part of the
15758 // `omp begin declare variant`.
15760 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
15762 ParentScope, D, TemplateParameterLists, Bases);
15763
15765 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
15766 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
15767
15768 if (!Bases.empty())
15770 Bases);
15771
15772 return Dcl;
15773}
15774
15776 Consumer.HandleInlineFunctionDefinition(D);
15777}
15778
15780 const FunctionDecl *&PossiblePrototype) {
15781 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
15782 Prev = Prev->getPreviousDecl()) {
15783 // Ignore any declarations that occur in function or method
15784 // scope, because they aren't visible from the header.
15785 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
15786 continue;
15787
15788 PossiblePrototype = Prev;
15789 return Prev->getType()->isFunctionProtoType();
15790 }
15791 return false;
15792}
15793
15794static bool
15796 const FunctionDecl *&PossiblePrototype) {
15797 // Don't warn about invalid declarations.
15798 if (FD->isInvalidDecl())
15799 return false;
15800
15801 // Or declarations that aren't global.
15802 if (!FD->isGlobal())
15803 return false;
15804
15805 // Don't warn about C++ member functions.
15806 if (isa<CXXMethodDecl>(FD))
15807 return false;
15808
15809 // Don't warn about 'main'.
15811 if (IdentifierInfo *II = FD->getIdentifier())
15812 if (II->isStr("main") || II->isStr("efi_main"))
15813 return false;
15814
15815 if (FD->isMSVCRTEntryPoint())
15816 return false;
15817
15818 // Don't warn about inline functions.
15819 if (FD->isInlined())
15820 return false;
15821
15822 // Don't warn about function templates.
15824 return false;
15825
15826 // Don't warn about function template specializations.
15828 return false;
15829
15830 // Don't warn for OpenCL kernels.
15831 if (FD->hasAttr<DeviceKernelAttr>())
15832 return false;
15833
15834 // Don't warn on explicitly deleted functions.
15835 if (FD->isDeleted())
15836 return false;
15837
15838 // Don't warn on implicitly local functions (such as having local-typed
15839 // parameters).
15840 if (!FD->isExternallyVisible())
15841 return false;
15842
15843 // If we were able to find a potential prototype, don't warn.
15844 if (FindPossiblePrototype(FD, PossiblePrototype))
15845 return false;
15846
15847 return true;
15848}
15849
15850void
15852 const FunctionDecl *EffectiveDefinition,
15853 SkipBodyInfo *SkipBody) {
15854 const FunctionDecl *Definition = EffectiveDefinition;
15855 if (!Definition &&
15856 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
15857 return;
15858
15859 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
15860 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
15861 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
15862 // A merged copy of the same function, instantiated as a member of
15863 // the same class, is OK.
15864 if (declaresSameEntity(OrigFD, OrigDef) &&
15865 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
15867 return;
15868 }
15869 }
15870 }
15871
15873 return;
15874
15875 // Don't emit an error when this is redefinition of a typo-corrected
15876 // definition.
15878 return;
15879
15880 bool DefinitionVisible = false;
15881 if (SkipBody && isRedefinitionAllowedFor(Definition, DefinitionVisible) &&
15882 (Definition->getFormalLinkage() == Linkage::Internal ||
15883 Definition->isInlined() || Definition->getDescribedFunctionTemplate() ||
15884 Definition->getNumTemplateParameterLists())) {
15885 SkipBody->ShouldSkip = true;
15886 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
15887 if (!DefinitionVisible) {
15888 if (auto *TD = Definition->getDescribedFunctionTemplate())
15891 }
15892 return;
15893 }
15894
15895 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
15896 Definition->getStorageClass() == SC_Extern)
15897 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
15898 << FD << getLangOpts().CPlusPlus;
15899 else
15900 Diag(FD->getLocation(), diag::err_redefinition) << FD;
15901
15902 Diag(Definition->getLocation(), diag::note_previous_definition);
15903 FD->setInvalidDecl();
15904}
15905
15907 CXXRecordDecl *LambdaClass = CallOperator->getParent();
15908
15910 LSI->CallOperator = CallOperator;
15911 LSI->Lambda = LambdaClass;
15912 LSI->ReturnType = CallOperator->getReturnType();
15913 // When this function is called in situation where the context of the call
15914 // operator is not entered, we set AfterParameterList to false, so that
15915 // `tryCaptureVariable` finds explicit captures in the appropriate context.
15916 // There is also at least a situation as in FinishTemplateArgumentDeduction(),
15917 // where we would set the CurContext to the lambda operator before
15918 // substituting into it. In this case the flag needs to be true such that
15919 // tryCaptureVariable can correctly handle potential captures thereof.
15920 LSI->AfterParameterList = CurContext == CallOperator;
15921
15922 // GLTemplateParameterList is necessary for getCurGenericLambda() which is
15923 // used at the point of dealing with potential captures.
15924 //
15925 // We don't use LambdaClass->isGenericLambda() because this value doesn't
15926 // flip for instantiated generic lambdas, where no FunctionTemplateDecls are
15927 // associated. (Technically, we could recover that list from their
15928 // instantiation patterns, but for now, the GLTemplateParameterList seems
15929 // unnecessary in these cases.)
15930 if (FunctionTemplateDecl *FTD = CallOperator->getDescribedFunctionTemplate())
15931 LSI->GLTemplateParameterList = FTD->getTemplateParameters();
15932 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
15933
15934 if (LCD == LCD_None)
15936 else if (LCD == LCD_ByCopy)
15938 else if (LCD == LCD_ByRef)
15940 DeclarationNameInfo DNI = CallOperator->getNameInfo();
15941
15943 LSI->Mutable = !CallOperator->isConst();
15944 if (CallOperator->isExplicitObjectMemberFunction())
15945 LSI->ExplicitObjectParameter = CallOperator->getParamDecl(0);
15946
15947 // Add the captures to the LSI so they can be noted as already
15948 // captured within tryCaptureVar.
15949 auto I = LambdaClass->field_begin();
15950 for (const auto &C : LambdaClass->captures()) {
15951 if (C.capturesVariable()) {
15952 ValueDecl *VD = C.getCapturedVar();
15953 if (VD->isInitCapture())
15954 CurrentInstantiationScope->InstantiatedLocal(VD, VD);
15955 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
15956 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
15957 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
15958 /*EllipsisLoc*/C.isPackExpansion()
15959 ? C.getEllipsisLoc() : SourceLocation(),
15960 I->getType(), /*Invalid*/false);
15961
15962 } else if (C.capturesThis()) {
15963 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
15964 C.getCaptureKind() == LCK_StarThis);
15965 } else {
15966 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
15967 I->getType());
15968 }
15969 ++I;
15970 }
15971 return LSI;
15972}
15973
15975 SkipBodyInfo *SkipBody,
15976 FnBodyKind BodyKind) {
15977 if (!D) {
15978 // Parsing the function declaration failed in some way. Push on a fake scope
15979 // anyway so we can try to parse the function body.
15982 return D;
15983 }
15984
15985 FunctionDecl *FD = nullptr;
15986
15987 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
15988 FD = FunTmpl->getTemplatedDecl();
15989 else
15990 FD = cast<FunctionDecl>(D);
15991
15992 // Do not push if it is a lambda because one is already pushed when building
15993 // the lambda in ActOnStartOfLambdaDefinition().
15994 if (!isLambdaCallOperator(FD))
15996 FD);
15997
15998 // Check for defining attributes before the check for redefinition.
15999 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
16000 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
16001 FD->dropAttr<AliasAttr>();
16002 FD->setInvalidDecl();
16003 }
16004 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
16005 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
16006 FD->dropAttr<IFuncAttr>();
16007 FD->setInvalidDecl();
16008 }
16009 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
16010 if (Context.getTargetInfo().getTriple().isAArch64() &&
16011 !Context.getTargetInfo().hasFeature("fmv") &&
16012 !Attr->isDefaultVersion()) {
16013 // If function multi versioning disabled skip parsing function body
16014 // defined with non-default target_version attribute
16015 if (SkipBody)
16016 SkipBody->ShouldSkip = true;
16017 return nullptr;
16018 }
16019 }
16020
16021 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
16022 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
16023 Ctor->isDefaultConstructor() &&
16024 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
16025 // If this is an MS ABI dllexport default constructor, instantiate any
16026 // default arguments.
16028 }
16029 }
16030
16031 // See if this is a redefinition. If 'will have body' (or similar) is already
16032 // set, then these checks were already performed when it was set.
16033 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
16035 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
16036
16037 // If we're skipping the body, we're done. Don't enter the scope.
16038 if (SkipBody && SkipBody->ShouldSkip)
16039 return D;
16040 }
16041
16042 // Mark this function as "will have a body eventually". This lets users to
16043 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
16044 // this function.
16045 FD->setWillHaveBody();
16046
16047 // If we are instantiating a generic lambda call operator, push
16048 // a LambdaScopeInfo onto the function stack. But use the information
16049 // that's already been calculated (ActOnLambdaExpr) to prime the current
16050 // LambdaScopeInfo.
16051 // When the template operator is being specialized, the LambdaScopeInfo,
16052 // has to be properly restored so that tryCaptureVariable doesn't try
16053 // and capture any new variables. In addition when calculating potential
16054 // captures during transformation of nested lambdas, it is necessary to
16055 // have the LSI properly restored.
16057 // C++2c 7.5.5.2p17 A member of a closure type shall not be explicitly
16058 // instantiated, explicitly specialized.
16061 Diag(FD->getLocation(), diag::err_lambda_explicit_spec);
16062 FD->setInvalidDecl();
16064 } else {
16065 assert(inTemplateInstantiation() &&
16066 "There should be an active template instantiation on the stack "
16067 "when instantiating a generic lambda!");
16069 }
16070 } else {
16071 // Enter a new function scope
16073 }
16074
16075 // Builtin functions cannot be defined.
16076 if (unsigned BuiltinID = FD->getBuiltinID()) {
16077 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
16078 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
16079 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
16080 FD->setInvalidDecl();
16081 }
16082 }
16083
16084 // The return type of a function definition must be complete (C99 6.9.1p3).
16085 // C++23 [dcl.fct.def.general]/p2
16086 // The type of [...] the return for a function definition
16087 // shall not be a (possibly cv-qualified) class type that is incomplete
16088 // or abstract within the function body unless the function is deleted.
16089 QualType ResultType = FD->getReturnType();
16090 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
16091 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
16092 (RequireCompleteType(FD->getLocation(), ResultType,
16093 diag::err_func_def_incomplete_result) ||
16095 diag::err_abstract_type_in_decl,
16097 FD->setInvalidDecl();
16098
16099 if (FnBodyScope)
16100 PushDeclContext(FnBodyScope, FD);
16101
16102 // Check the validity of our function parameters
16103 if (BodyKind != FnBodyKind::Delete)
16105 /*CheckParameterNames=*/true);
16106
16107 // Add non-parameter declarations already in the function to the current
16108 // scope.
16109 if (FnBodyScope) {
16110 for (Decl *NPD : FD->decls()) {
16111 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
16112 if (!NonParmDecl)
16113 continue;
16114 assert(!isa<ParmVarDecl>(NonParmDecl) &&
16115 "parameters should not be in newly created FD yet");
16116
16117 // If the decl has a name, make it accessible in the current scope.
16118 if (NonParmDecl->getDeclName())
16119 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
16120
16121 // Similarly, dive into enums and fish their constants out, making them
16122 // accessible in this scope.
16123 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
16124 for (auto *EI : ED->enumerators())
16125 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
16126 }
16127 }
16128 }
16129
16130 // Introduce our parameters into the function scope
16131 for (auto *Param : FD->parameters()) {
16132 Param->setOwningFunction(FD);
16133
16134 // If this has an identifier, add it to the scope stack.
16135 if (Param->getIdentifier() && FnBodyScope) {
16136 CheckShadow(FnBodyScope, Param);
16137
16138 PushOnScopeChains(Param, FnBodyScope);
16139 }
16140 }
16141
16142 // C++ [module.import/6] external definitions are not permitted in header
16143 // units. Deleted and Defaulted functions are implicitly inline (but the
16144 // inline state is not set at this point, so check the BodyKind explicitly).
16145 // FIXME: Consider an alternate location for the test where the inlined()
16146 // state is complete.
16147 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
16148 !FD->isInvalidDecl() && !FD->isInlined() &&
16149 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
16150 FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() &&
16151 !FD->isTemplateInstantiation()) {
16152 assert(FD->isThisDeclarationADefinition());
16153 Diag(FD->getLocation(), diag::err_extern_def_in_header_unit);
16154 FD->setInvalidDecl();
16155 }
16156
16157 // Ensure that the function's exception specification is instantiated.
16158 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
16160
16161 // dllimport cannot be applied to non-inline function definitions.
16162 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
16163 !FD->isTemplateInstantiation()) {
16164 assert(!FD->hasAttr<DLLExportAttr>());
16165 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
16166 FD->setInvalidDecl();
16167 return D;
16168 }
16169
16170 // Some function attributes (like OptimizeNoneAttr) need actions before
16171 // parsing body started.
16173
16174 // We want to attach documentation to original Decl (which might be
16175 // a function template).
16177 if (getCurLexicalContext()->isObjCContainer() &&
16178 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
16179 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
16180 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
16181
16183
16184 return D;
16185}
16186
16188 if (!FD || FD->isInvalidDecl())
16189 return;
16190 if (auto *TD = dyn_cast<FunctionTemplateDecl>(FD))
16191 FD = TD->getTemplatedDecl();
16192 if (FD && FD->hasAttr<OptimizeNoneAttr>()) {
16195 CurFPFeatures.applyChanges(FPO);
16196 FpPragmaStack.CurrentValue =
16197 CurFPFeatures.getChangesFrom(FPOptions(LangOpts));
16198 }
16199}
16200
16202 ReturnStmt **Returns = Scope->Returns.data();
16203
16204 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
16205 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
16206 if (!NRVOCandidate->isNRVOVariable()) {
16207 Diag(Returns[I]->getRetValue()->getExprLoc(),
16208 diag::warn_not_eliding_copy_on_return);
16209 Returns[I]->setNRVOCandidate(nullptr);
16210 }
16211 }
16212 }
16213}
16214
16216 // We can't delay parsing the body of a constexpr function template (yet).
16218 return false;
16219
16220 // We can't delay parsing the body of a function template with a deduced
16221 // return type (yet).
16222 if (D.getDeclSpec().hasAutoTypeSpec()) {
16223 // If the placeholder introduces a non-deduced trailing return type,
16224 // we can still delay parsing it.
16225 if (D.getNumTypeObjects()) {
16226 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
16227 if (Outer.Kind == DeclaratorChunk::Function &&
16228 Outer.Fun.hasTrailingReturnType()) {
16229 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
16230 return Ty.isNull() || !Ty->isUndeducedType();
16231 }
16232 }
16233 return false;
16234 }
16235
16236 return true;
16237}
16238
16240 // We cannot skip the body of a function (or function template) which is
16241 // constexpr, since we may need to evaluate its body in order to parse the
16242 // rest of the file.
16243 // We cannot skip the body of a function with an undeduced return type,
16244 // because any callers of that function need to know the type.
16245 if (const FunctionDecl *FD = D->getAsFunction()) {
16246 if (FD->isConstexpr())
16247 return false;
16248 // We can't simply call Type::isUndeducedType here, because inside template
16249 // auto can be deduced to a dependent type, which is not considered
16250 // "undeduced".
16251 if (FD->getReturnType()->getContainedDeducedType())
16252 return false;
16253 }
16254 return Consumer.shouldSkipFunctionBody(D);
16255}
16256
16258 if (!Decl)
16259 return nullptr;
16260 if (FunctionDecl *FD = Decl->getAsFunction())
16261 FD->setHasSkippedBody();
16262 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
16263 MD->setHasSkippedBody();
16264 return Decl;
16265}
16266
16267/// RAII object that pops an ExpressionEvaluationContext when exiting a function
16268/// body.
16270public:
16271 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
16273 if (!IsLambda)
16274 S.PopExpressionEvaluationContext();
16275 }
16276
16277private:
16278 Sema &S;
16279 bool IsLambda = false;
16280};
16281
16283 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
16284
16285 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
16286 auto [It, Inserted] = EscapeInfo.try_emplace(BD);
16287 if (!Inserted)
16288 return It->second;
16289
16290 bool R = false;
16291 const BlockDecl *CurBD = BD;
16292
16293 do {
16294 R = !CurBD->doesNotEscape();
16295 if (R)
16296 break;
16297 CurBD = CurBD->getParent()->getInnermostBlockDecl();
16298 } while (CurBD);
16299
16300 return It->second = R;
16301 };
16302
16303 // If the location where 'self' is implicitly retained is inside a escaping
16304 // block, emit a diagnostic.
16305 for (const std::pair<SourceLocation, const BlockDecl *> &P :
16307 if (IsOrNestedInEscapingBlock(P.second))
16308 S.Diag(P.first, diag::warn_implicitly_retains_self)
16309 << FixItHint::CreateInsertion(P.first, "self->");
16310}
16311
16312static bool methodHasName(const FunctionDecl *FD, StringRef Name) {
16313 return isa<CXXMethodDecl>(FD) && FD->param_empty() &&
16314 FD->getDeclName().isIdentifier() && FD->getName() == Name;
16315}
16316
16318 return methodHasName(FD, "get_return_object");
16319}
16320
16322 return FD->isStatic() &&
16323 methodHasName(FD, "get_return_object_on_allocation_failure");
16324}
16325
16328 if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>())
16329 return;
16330 // Allow some_promise_type::get_return_object().
16332 return;
16333 if (!FD->hasAttr<CoroWrapperAttr>())
16334 Diag(FD->getLocation(), diag::err_coroutine_return_type) << RD;
16335}
16336
16337Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, bool IsInstantiation,
16338 bool RetainFunctionScopeInfo) {
16340 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
16341
16342 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
16343 FD->addAttr(StrictFPAttr::CreateImplicit(Context));
16344
16345 SourceLocation AnalysisLoc;
16346 if (Body)
16347 AnalysisLoc = Body->getEndLoc();
16348 else if (FD)
16349 AnalysisLoc = FD->getEndLoc();
16351 AnalysisWarnings.getPolicyInEffectAt(AnalysisLoc);
16352 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
16353
16354 // If we skip function body, we can't tell if a function is a coroutine.
16355 if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) {
16356 if (FSI->isCoroutine())
16358 else
16360 }
16361
16362 // Diagnose invalid SYCL kernel entry point function declarations
16363 // and build SYCLKernelCallStmts for valid ones.
16364 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLKernelEntryPointAttr>()) {
16365 SYCLKernelEntryPointAttr *SKEPAttr =
16366 FD->getAttr<SYCLKernelEntryPointAttr>();
16367 if (FD->isDefaulted()) {
16368 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16369 << SKEPAttr << /*defaulted function*/ 3;
16370 SKEPAttr->setInvalidAttr();
16371 } else if (FD->isDeleted()) {
16372 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16373 << SKEPAttr << /*deleted function*/ 2;
16374 SKEPAttr->setInvalidAttr();
16375 } else if (FSI->isCoroutine()) {
16376 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16377 << SKEPAttr << /*coroutine*/ 7;
16378 SKEPAttr->setInvalidAttr();
16379 } else if (Body && isa<CXXTryStmt>(Body)) {
16380 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16381 << SKEPAttr << /*function defined with a function try block*/ 8;
16382 SKEPAttr->setInvalidAttr();
16383 }
16384
16385 if (Body && !FD->isTemplated() && !SKEPAttr->isInvalidAttr()) {
16386 StmtResult SR =
16388 if (SR.isInvalid())
16389 return nullptr;
16390 Body = SR.get();
16391 }
16392 }
16393
16394 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLExternalAttr>()) {
16395 SYCLExternalAttr *SEAttr = FD->getAttr<SYCLExternalAttr>();
16396 if (FD->isDeletedAsWritten())
16397 Diag(SEAttr->getLocation(),
16398 diag::err_sycl_external_invalid_deleted_function)
16399 << SEAttr;
16400 }
16401
16402 {
16403 // Do not call PopExpressionEvaluationContext() if it is a lambda because
16404 // one is already popped when finishing the lambda in BuildLambdaExpr().
16405 // This is meant to pop the context added in ActOnStartOfFunctionDef().
16406 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
16407 if (FD) {
16408 // The function body and the DefaultedOrDeletedInfo, if present, use
16409 // the same storage; don't overwrite the latter if the former is null
16410 // (the body is initialised to null anyway, so even if the latter isn't
16411 // present, this would still be a no-op).
16412 if (Body)
16413 FD->setBody(Body);
16414 FD->setWillHaveBody(false);
16415
16416 if (getLangOpts().CPlusPlus14) {
16417 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
16418 FD->getReturnType()->isUndeducedType()) {
16419 // For a function with a deduced result type to return void,
16420 // the result type as written must be 'auto' or 'decltype(auto)',
16421 // possibly cv-qualified or constrained, but not ref-qualified.
16422 if (!FD->getReturnType()->getAs<AutoType>()) {
16423 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
16424 << FD->getReturnType();
16425 FD->setInvalidDecl();
16426 } else {
16427 // Falling off the end of the function is the same as 'return;'.
16428 Expr *Dummy = nullptr;
16430 FD, dcl->getLocation(), Dummy,
16431 FD->getReturnType()->getAs<AutoType>()))
16432 FD->setInvalidDecl();
16433 }
16434 }
16435 } else if (getLangOpts().CPlusPlus && isLambdaCallOperator(FD)) {
16436 // In C++11, we don't use 'auto' deduction rules for lambda call
16437 // operators because we don't support return type deduction.
16438 auto *LSI = getCurLambda();
16439 if (LSI->HasImplicitReturnType) {
16441
16442 // C++11 [expr.prim.lambda]p4:
16443 // [...] if there are no return statements in the compound-statement
16444 // [the deduced type is] the type void
16445 QualType RetType =
16446 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
16447
16448 // Update the return type to the deduced type.
16449 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
16450 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
16451 Proto->getExtProtoInfo()));
16452 }
16453 }
16454
16455 // If the function implicitly returns zero (like 'main') or is naked,
16456 // don't complain about missing return statements.
16457 // Clang implicitly returns 0 in C89 mode, but that's considered an
16458 // extension. The check is necessary to ensure the expected extension
16459 // warning is emitted in C89 mode.
16460 if ((FD->hasImplicitReturnZero() &&
16461 (getLangOpts().CPlusPlus || getLangOpts().C99 || !FD->isMain())) ||
16462 FD->hasAttr<NakedAttr>())
16464
16465 // MSVC permits the use of pure specifier (=0) on function definition,
16466 // defined at class scope, warn about this non-standard construct.
16467 if (getLangOpts().MicrosoftExt && FD->isPureVirtual() &&
16468 !FD->isOutOfLine())
16469 Diag(FD->getLocation(), diag::ext_pure_function_definition);
16470
16471 if (!FD->isInvalidDecl()) {
16472 // Don't diagnose unused parameters of defaulted, deleted or naked
16473 // functions.
16474 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
16475 !FD->hasAttr<NakedAttr>())
16478 FD->getReturnType(), FD);
16479
16480 // If this is a structor, we need a vtable.
16481 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
16482 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
16483 else if (CXXDestructorDecl *Destructor =
16484 dyn_cast<CXXDestructorDecl>(FD))
16485 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
16486
16487 // Try to apply the named return value optimization. We have to check
16488 // if we can do this here because lambdas keep return statements around
16489 // to deduce an implicit return type.
16490 if (FD->getReturnType()->isRecordType() &&
16492 computeNRVO(Body, FSI);
16493 }
16494
16495 // GNU warning -Wmissing-prototypes:
16496 // Warn if a global function is defined without a previous
16497 // prototype declaration. This warning is issued even if the
16498 // definition itself provides a prototype. The aim is to detect
16499 // global functions that fail to be declared in header files.
16500 const FunctionDecl *PossiblePrototype = nullptr;
16501 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
16502 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
16503
16504 if (PossiblePrototype) {
16505 // We found a declaration that is not a prototype,
16506 // but that could be a zero-parameter prototype
16507 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
16508 TypeLoc TL = TI->getTypeLoc();
16510 Diag(PossiblePrototype->getLocation(),
16511 diag::note_declaration_not_a_prototype)
16512 << (FD->getNumParams() != 0)
16514 FTL.getRParenLoc(), "void")
16515 : FixItHint{});
16516 }
16517 } else {
16518 // Returns true if the token beginning at this Loc is `const`.
16519 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
16520 const LangOptions &LangOpts) {
16521 FileIDAndOffset LocInfo = SM.getDecomposedLoc(Loc);
16522 if (LocInfo.first.isInvalid())
16523 return false;
16524
16525 bool Invalid = false;
16526 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
16527 if (Invalid)
16528 return false;
16529
16530 if (LocInfo.second > Buffer.size())
16531 return false;
16532
16533 const char *LexStart = Buffer.data() + LocInfo.second;
16534 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
16535
16536 return StartTok.consume_front("const") &&
16537 (StartTok.empty() || isWhitespace(StartTok[0]) ||
16538 StartTok.starts_with("/*") || StartTok.starts_with("//"));
16539 };
16540
16541 auto findBeginLoc = [&]() {
16542 // If the return type has `const` qualifier, we want to insert
16543 // `static` before `const` (and not before the typename).
16544 if ((FD->getReturnType()->isAnyPointerType() &&
16547 // But only do this if we can determine where the `const` is.
16548
16549 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
16550 getLangOpts()))
16551
16552 return FD->getBeginLoc();
16553 }
16554 return FD->getTypeSpecStartLoc();
16555 };
16557 diag::note_static_for_internal_linkage)
16558 << /* function */ 1
16559 << (FD->getStorageClass() == SC_None
16560 ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
16561 : FixItHint{});
16562 }
16563 }
16564
16565 // We might not have found a prototype because we didn't wish to warn on
16566 // the lack of a missing prototype. Try again without the checks for
16567 // whether we want to warn on the missing prototype.
16568 if (!PossiblePrototype)
16569 (void)FindPossiblePrototype(FD, PossiblePrototype);
16570
16571 // If the function being defined does not have a prototype, then we may
16572 // need to diagnose it as changing behavior in C23 because we now know
16573 // whether the function accepts arguments or not. This only handles the
16574 // case where the definition has no prototype but does have parameters
16575 // and either there is no previous potential prototype, or the previous
16576 // potential prototype also has no actual prototype. This handles cases
16577 // like:
16578 // void f(); void f(a) int a; {}
16579 // void g(a) int a; {}
16580 // See MergeFunctionDecl() for other cases of the behavior change
16581 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
16582 // type without a prototype.
16583 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
16584 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
16585 !PossiblePrototype->isImplicit()))) {
16586 // The function definition has parameters, so this will change behavior
16587 // in C23. If there is a possible prototype, it comes before the
16588 // function definition.
16589 // FIXME: The declaration may have already been diagnosed as being
16590 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
16591 // there's no way to test for the "changes behavior" condition in
16592 // SemaType.cpp when forming the declaration's function type. So, we do
16593 // this awkward dance instead.
16594 //
16595 // If we have a possible prototype and it declares a function with a
16596 // prototype, we don't want to diagnose it; if we have a possible
16597 // prototype and it has no prototype, it may have already been
16598 // diagnosed in SemaType.cpp as deprecated depending on whether
16599 // -Wstrict-prototypes is enabled. If we already warned about it being
16600 // deprecated, add a note that it also changes behavior. If we didn't
16601 // warn about it being deprecated (because the diagnostic is not
16602 // enabled), warn now that it is deprecated and changes behavior.
16603
16604 // This K&R C function definition definitely changes behavior in C23,
16605 // so diagnose it.
16606 Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
16607 << /*definition*/ 1 << /* not supported in C23 */ 0;
16608
16609 // If we have a possible prototype for the function which is a user-
16610 // visible declaration, we already tested that it has no prototype.
16611 // This will change behavior in C23. This gets a warning rather than a
16612 // note because it's the same behavior-changing problem as with the
16613 // definition.
16614 if (PossiblePrototype)
16615 Diag(PossiblePrototype->getLocation(),
16616 diag::warn_non_prototype_changes_behavior)
16617 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
16618 << /*definition*/ 1;
16619 }
16620
16621 // Warn on CPUDispatch with an actual body.
16622 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
16623 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
16624 if (!CmpndBody->body_empty())
16625 Diag(CmpndBody->body_front()->getBeginLoc(),
16626 diag::warn_dispatch_body_ignored);
16627
16628 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
16629 const CXXMethodDecl *KeyFunction;
16630 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
16631 MD->isVirtual() &&
16632 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
16633 MD == KeyFunction->getCanonicalDecl()) {
16634 // Update the key-function state if necessary for this ABI.
16635 if (FD->isInlined() &&
16636 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
16637 Context.setNonKeyFunction(MD);
16638
16639 // If the newly-chosen key function is already defined, then we
16640 // need to mark the vtable as used retroactively.
16641 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
16642 const FunctionDecl *Definition;
16643 if (KeyFunction && KeyFunction->isDefined(Definition))
16644 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
16645 } else {
16646 // We just defined they key function; mark the vtable as used.
16647 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
16648 }
16649 }
16650 }
16651
16652 assert((FD == getCurFunctionDecl(/*AllowLambdas=*/true)) &&
16653 "Function parsing confused");
16654 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
16655 assert(MD == getCurMethodDecl() && "Method parsing confused");
16656 MD->setBody(Body);
16657 if (!MD->isInvalidDecl()) {
16659 MD->getReturnType(), MD);
16660
16661 if (Body)
16662 computeNRVO(Body, FSI);
16663 }
16664 if (FSI->ObjCShouldCallSuper) {
16665 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
16666 << MD->getSelector().getAsString();
16667 FSI->ObjCShouldCallSuper = false;
16668 }
16670 const ObjCMethodDecl *InitMethod = nullptr;
16671 bool isDesignated =
16672 MD->isDesignatedInitializerForTheInterface(&InitMethod);
16673 assert(isDesignated && InitMethod);
16674 (void)isDesignated;
16675
16676 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
16677 auto IFace = MD->getClassInterface();
16678 if (!IFace)
16679 return false;
16680 auto SuperD = IFace->getSuperClass();
16681 if (!SuperD)
16682 return false;
16683 return SuperD->getIdentifier() ==
16684 ObjC().NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
16685 };
16686 // Don't issue this warning for unavailable inits or direct subclasses
16687 // of NSObject.
16688 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
16689 Diag(MD->getLocation(),
16690 diag::warn_objc_designated_init_missing_super_call);
16691 Diag(InitMethod->getLocation(),
16692 diag::note_objc_designated_init_marked_here);
16693 }
16695 }
16696 if (FSI->ObjCWarnForNoInitDelegation) {
16697 // Don't issue this warning for unavailable inits.
16698 if (!MD->isUnavailable())
16699 Diag(MD->getLocation(),
16700 diag::warn_objc_secondary_init_missing_init_call);
16701 FSI->ObjCWarnForNoInitDelegation = false;
16702 }
16703
16705 } else {
16706 // Parsing the function declaration failed in some way. Pop the fake scope
16707 // we pushed on.
16708 PopFunctionScopeInfo(ActivePolicy, dcl);
16709 return nullptr;
16710 }
16711
16712 if (Body && FSI->HasPotentialAvailabilityViolations)
16714
16715 assert(!FSI->ObjCShouldCallSuper &&
16716 "This should only be set for ObjC methods, which should have been "
16717 "handled in the block above.");
16718
16719 // Verify and clean out per-function state.
16720 if (Body && (!FD || !FD->isDefaulted())) {
16721 // C++ constructors that have function-try-blocks can't have return
16722 // statements in the handlers of that block. (C++ [except.handle]p14)
16723 // Verify this.
16724 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
16726
16727 // Verify that gotos and switch cases don't jump into scopes illegally.
16728 if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
16730
16731 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
16732 if (!Destructor->getParent()->isDependentType())
16734
16736 Destructor->getParent());
16737 }
16738
16739 // If any errors have occurred, clear out any temporaries that may have
16740 // been leftover. This ensures that these temporaries won't be picked up
16741 // for deletion in some later function.
16744 getDiagnostics().getSuppressAllDiagnostics()) {
16746 }
16748 // Since the body is valid, issue any analysis-based warnings that are
16749 // enabled.
16750 ActivePolicy = &WP;
16751 }
16752
16753 if (!IsInstantiation && FD &&
16754 (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) &&
16755 !FD->isInvalidDecl() &&
16757 FD->setInvalidDecl();
16758
16759 if (FD && FD->hasAttr<NakedAttr>()) {
16760 for (const Stmt *S : Body->children()) {
16761 // Allow local register variables without initializer as they don't
16762 // require prologue.
16763 bool RegisterVariables = false;
16764 if (auto *DS = dyn_cast<DeclStmt>(S)) {
16765 for (const auto *Decl : DS->decls()) {
16766 if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
16767 RegisterVariables =
16768 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
16769 if (!RegisterVariables)
16770 break;
16771 }
16772 }
16773 }
16774 if (RegisterVariables)
16775 continue;
16776 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
16777 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
16778 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
16779 FD->setInvalidDecl();
16780 break;
16781 }
16782 }
16783 }
16784
16785 assert(ExprCleanupObjects.size() ==
16786 ExprEvalContexts.back().NumCleanupObjects &&
16787 "Leftover temporaries in function");
16788 assert(!Cleanup.exprNeedsCleanups() &&
16789 "Unaccounted cleanups in function");
16790 assert(MaybeODRUseExprs.empty() &&
16791 "Leftover expressions for odr-use checking");
16792 }
16793 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
16794 // the declaration context below. Otherwise, we're unable to transform
16795 // 'this' expressions when transforming immediate context functions.
16796
16797 if (FD)
16799
16800 if (!IsInstantiation)
16802
16803 if (!RetainFunctionScopeInfo)
16804 PopFunctionScopeInfo(ActivePolicy, dcl);
16805 // If any errors have occurred, clear out any temporaries that may have
16806 // been leftover. This ensures that these temporaries won't be picked up for
16807 // deletion in some later function.
16810 }
16811
16812 if (FD && (LangOpts.isTargetDevice() || LangOpts.CUDA ||
16813 (LangOpts.OpenMP && !LangOpts.OMPTargetTriples.empty()))) {
16814 auto ES = getEmissionStatus(FD);
16818 }
16819
16820 if (FD && !FD->isDeleted())
16821 checkTypeSupport(FD->getType(), FD->getLocation(), FD);
16822
16823 return dcl;
16824}
16825
16826/// When we finish delayed parsing of an attribute, we must attach it to the
16827/// relevant Decl.
16829 ParsedAttributes &Attrs) {
16830 // Always attach attributes to the underlying decl.
16831 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
16832 D = TD->getTemplatedDecl();
16833 ProcessDeclAttributeList(S, D, Attrs);
16834 ProcessAPINotes(D);
16835
16836 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
16837 if (Method->isStatic())
16839}
16840
16842 IdentifierInfo &II, Scope *S) {
16843 // It is not valid to implicitly define a function in C23.
16844 assert(LangOpts.implicitFunctionsAllowed() &&
16845 "Implicit function declarations aren't allowed in this language mode");
16846
16847 // Find the scope in which the identifier is injected and the corresponding
16848 // DeclContext.
16849 // FIXME: C89 does not say what happens if there is no enclosing block scope.
16850 // In that case, we inject the declaration into the translation unit scope
16851 // instead.
16852 Scope *BlockScope = S;
16853 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
16854 BlockScope = BlockScope->getParent();
16855
16856 // Loop until we find a DeclContext that is either a function/method or the
16857 // translation unit, which are the only two valid places to implicitly define
16858 // a function. This avoids accidentally defining the function within a tag
16859 // declaration, for example.
16860 Scope *ContextScope = BlockScope;
16861 while (!ContextScope->getEntity() ||
16862 (!ContextScope->getEntity()->isFunctionOrMethod() &&
16863 !ContextScope->getEntity()->isTranslationUnit()))
16864 ContextScope = ContextScope->getParent();
16865 ContextRAII SavedContext(*this, ContextScope->getEntity());
16866
16867 // Before we produce a declaration for an implicitly defined
16868 // function, see whether there was a locally-scoped declaration of
16869 // this name as a function or variable. If so, use that
16870 // (non-visible) declaration, and complain about it.
16871 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
16872 if (ExternCPrev) {
16873 // We still need to inject the function into the enclosing block scope so
16874 // that later (non-call) uses can see it.
16875 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
16876
16877 // C89 footnote 38:
16878 // If in fact it is not defined as having type "function returning int",
16879 // the behavior is undefined.
16880 if (!isa<FunctionDecl>(ExternCPrev) ||
16881 !Context.typesAreCompatible(
16882 cast<FunctionDecl>(ExternCPrev)->getType(),
16883 Context.getFunctionNoProtoType(Context.IntTy))) {
16884 Diag(Loc, diag::ext_use_out_of_scope_declaration)
16885 << ExternCPrev << !getLangOpts().C99;
16886 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
16887 return ExternCPrev;
16888 }
16889 }
16890
16891 // Extension in C99 (defaults to error). Legal in C89, but warn about it.
16892 unsigned diag_id;
16893 if (II.getName().starts_with("__builtin_"))
16894 diag_id = diag::warn_builtin_unknown;
16895 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
16896 else if (getLangOpts().C99)
16897 diag_id = diag::ext_implicit_function_decl_c99;
16898 else
16899 diag_id = diag::warn_implicit_function_decl;
16900
16901 TypoCorrection Corrected;
16902 // Because typo correction is expensive, only do it if the implicit
16903 // function declaration is going to be treated as an error.
16904 //
16905 // Perform the correction before issuing the main diagnostic, as some
16906 // consumers use typo-correction callbacks to enhance the main diagnostic.
16907 if (S && !ExternCPrev &&
16908 (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {
16910 Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
16911 S, nullptr, CCC, CorrectTypoKind::NonError);
16912 }
16913
16914 Diag(Loc, diag_id) << &II;
16915 if (Corrected) {
16916 // If the correction is going to suggest an implicitly defined function,
16917 // skip the correction as not being a particularly good idea.
16918 bool Diagnose = true;
16919 if (const auto *D = Corrected.getCorrectionDecl())
16920 Diagnose = !D->isImplicit();
16921 if (Diagnose)
16922 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
16923 /*ErrorRecovery*/ false);
16924 }
16925
16926 // If we found a prior declaration of this function, don't bother building
16927 // another one. We've already pushed that one into scope, so there's nothing
16928 // more to do.
16929 if (ExternCPrev)
16930 return ExternCPrev;
16931
16932 // Set a Declarator for the implicit definition: int foo();
16933 const char *Dummy;
16934 AttributeFactory attrFactory;
16935 DeclSpec DS(attrFactory);
16936 unsigned DiagID;
16937 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
16938 Context.getPrintingPolicy());
16939 (void)Error; // Silence warning.
16940 assert(!Error && "Error setting up implicit decl!");
16941 SourceLocation NoLoc;
16943 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
16944 /*IsAmbiguous=*/false,
16945 /*LParenLoc=*/NoLoc,
16946 /*Params=*/nullptr,
16947 /*NumParams=*/0,
16948 /*EllipsisLoc=*/NoLoc,
16949 /*RParenLoc=*/NoLoc,
16950 /*RefQualifierIsLvalueRef=*/true,
16951 /*RefQualifierLoc=*/NoLoc,
16952 /*MutableLoc=*/NoLoc, EST_None,
16953 /*ESpecRange=*/SourceRange(),
16954 /*Exceptions=*/nullptr,
16955 /*ExceptionRanges=*/nullptr,
16956 /*NumExceptions=*/0,
16957 /*NoexceptExpr=*/nullptr,
16958 /*ExceptionSpecTokens=*/nullptr,
16959 /*DeclsInPrototype=*/{}, Loc, Loc,
16960 D),
16961 std::move(DS.getAttributes()), SourceLocation());
16962 D.SetIdentifier(&II, Loc);
16963
16964 // Insert this function into the enclosing block scope.
16965 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
16966 FD->setImplicit();
16967
16969
16970 return FD;
16971}
16972
16974 FunctionDecl *FD) {
16975 if (FD->isInvalidDecl())
16976 return;
16977
16978 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
16979 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
16980 return;
16981
16982 UnsignedOrNone AlignmentParam = std::nullopt;
16983 bool IsNothrow = false;
16984 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
16985 return;
16986
16987 // C++2a [basic.stc.dynamic.allocation]p4:
16988 // An allocation function that has a non-throwing exception specification
16989 // indicates failure by returning a null pointer value. Any other allocation
16990 // function never returns a null pointer value and indicates failure only by
16991 // throwing an exception [...]
16992 //
16993 // However, -fcheck-new invalidates this possible assumption, so don't add
16994 // NonNull when that is enabled.
16995 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&
16996 !getLangOpts().CheckNew)
16997 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
16998
16999 // C++2a [basic.stc.dynamic.allocation]p2:
17000 // An allocation function attempts to allocate the requested amount of
17001 // storage. [...] If the request succeeds, the value returned by a
17002 // replaceable allocation function is a [...] pointer value p0 different
17003 // from any previously returned value p1 [...]
17004 //
17005 // However, this particular information is being added in codegen,
17006 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
17007
17008 // C++2a [basic.stc.dynamic.allocation]p2:
17009 // An allocation function attempts to allocate the requested amount of
17010 // storage. If it is successful, it returns the address of the start of a
17011 // block of storage whose length in bytes is at least as large as the
17012 // requested size.
17013 if (!FD->hasAttr<AllocSizeAttr>()) {
17014 FD->addAttr(AllocSizeAttr::CreateImplicit(
17015 Context, /*ElemSizeParam=*/ParamIdx(1, FD),
17016 /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
17017 }
17018
17019 // C++2a [basic.stc.dynamic.allocation]p3:
17020 // For an allocation function [...], the pointer returned on a successful
17021 // call shall represent the address of storage that is aligned as follows:
17022 // (3.1) If the allocation function takes an argument of type
17023 // std​::​align_­val_­t, the storage will have the alignment
17024 // specified by the value of this argument.
17025 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
17026 FD->addAttr(AllocAlignAttr::CreateImplicit(
17027 Context, ParamIdx(*AlignmentParam, FD), FD->getLocation()));
17028 }
17029
17030 // FIXME:
17031 // C++2a [basic.stc.dynamic.allocation]p3:
17032 // For an allocation function [...], the pointer returned on a successful
17033 // call shall represent the address of storage that is aligned as follows:
17034 // (3.2) Otherwise, if the allocation function is named operator new[],
17035 // the storage is aligned for any object that does not have
17036 // new-extended alignment ([basic.align]) and is no larger than the
17037 // requested size.
17038 // (3.3) Otherwise, the storage is aligned for any object that does not
17039 // have new-extended alignment and is of the requested size.
17040}
17041
17043 if (FD->isInvalidDecl())
17044 return;
17045
17046 // If this is a built-in function, map its builtin attributes to
17047 // actual attributes.
17048 if (unsigned BuiltinID = FD->getBuiltinID()) {
17049 // Handle printf-formatting attributes.
17050 unsigned FormatIdx;
17051 bool HasVAListArg;
17052 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
17053 if (!FD->hasAttr<FormatAttr>()) {
17054 const char *fmt = "printf";
17055 unsigned int NumParams = FD->getNumParams();
17056 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
17057 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
17058 fmt = "NSString";
17059 FD->addAttr(FormatAttr::CreateImplicit(Context,
17060 &Context.Idents.get(fmt),
17061 FormatIdx+1,
17062 HasVAListArg ? 0 : FormatIdx+2,
17063 FD->getLocation()));
17064 }
17065 }
17066 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
17067 HasVAListArg)) {
17068 if (!FD->hasAttr<FormatAttr>())
17069 FD->addAttr(FormatAttr::CreateImplicit(Context,
17070 &Context.Idents.get("scanf"),
17071 FormatIdx+1,
17072 HasVAListArg ? 0 : FormatIdx+2,
17073 FD->getLocation()));
17074 }
17075
17076 // Handle automatically recognized callbacks.
17077 SmallVector<int, 4> Encoding;
17078 if (!FD->hasAttr<CallbackAttr>() &&
17079 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
17080 FD->addAttr(CallbackAttr::CreateImplicit(
17081 Context, Encoding.data(), Encoding.size(), FD->getLocation()));
17082
17083 // Mark const if we don't care about errno and/or floating point exceptions
17084 // that are the only thing preventing the function from being const. This
17085 // allows IRgen to use LLVM intrinsics for such functions.
17086 bool NoExceptions =
17088 bool ConstWithoutErrnoAndExceptions =
17089 Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(BuiltinID);
17090 bool ConstWithoutExceptions =
17091 Context.BuiltinInfo.isConstWithoutExceptions(BuiltinID);
17092 if (!FD->hasAttr<ConstAttr>() &&
17093 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
17094 (!ConstWithoutErrnoAndExceptions ||
17095 (!getLangOpts().MathErrno && NoExceptions)) &&
17096 (!ConstWithoutExceptions || NoExceptions))
17097 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
17098
17099 // We make "fma" on GNU or Windows const because we know it does not set
17100 // errno in those environments even though it could set errno based on the
17101 // C standard.
17102 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
17103 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
17104 !FD->hasAttr<ConstAttr>()) {
17105 switch (BuiltinID) {
17106 case Builtin::BI__builtin_fma:
17107 case Builtin::BI__builtin_fmaf:
17108 case Builtin::BI__builtin_fmal:
17109 case Builtin::BIfma:
17110 case Builtin::BIfmaf:
17111 case Builtin::BIfmal:
17112 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
17113 break;
17114 default:
17115 break;
17116 }
17117 }
17118
17119 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
17120 !FD->hasAttr<ReturnsTwiceAttr>())
17121 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
17122 FD->getLocation()));
17123 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
17124 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
17125 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
17126 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
17127 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
17128 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
17129 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
17130 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
17131 // Add the appropriate attribute, depending on the CUDA compilation mode
17132 // and which target the builtin belongs to. For example, during host
17133 // compilation, aux builtins are __device__, while the rest are __host__.
17134 if (getLangOpts().CUDAIsDevice !=
17135 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
17136 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
17137 else
17138 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
17139 }
17140
17141 // Add known guaranteed alignment for allocation functions.
17142 switch (BuiltinID) {
17143 case Builtin::BImemalign:
17144 case Builtin::BIaligned_alloc:
17145 if (!FD->hasAttr<AllocAlignAttr>())
17146 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
17147 FD->getLocation()));
17148 break;
17149 default:
17150 break;
17151 }
17152
17153 // Add allocsize attribute for allocation functions.
17154 switch (BuiltinID) {
17155 case Builtin::BIcalloc:
17156 FD->addAttr(AllocSizeAttr::CreateImplicit(
17157 Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
17158 break;
17159 case Builtin::BImemalign:
17160 case Builtin::BIaligned_alloc:
17161 case Builtin::BIrealloc:
17162 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
17163 ParamIdx(), FD->getLocation()));
17164 break;
17165 case Builtin::BImalloc:
17166 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
17167 ParamIdx(), FD->getLocation()));
17168 break;
17169 default:
17170 break;
17171 }
17172 }
17173
17178
17179 // If C++ exceptions are enabled but we are told extern "C" functions cannot
17180 // throw, add an implicit nothrow attribute to any extern "C" function we come
17181 // across.
17182 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
17183 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
17184 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
17185 if (!FPT || FPT->getExceptionSpecType() == EST_None)
17186 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
17187 }
17188
17189 IdentifierInfo *Name = FD->getIdentifier();
17190 if (!Name)
17191 return;
17194 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
17196 // Okay: this could be a libc/libm/Objective-C function we know
17197 // about.
17198 } else
17199 return;
17200
17201 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
17202 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
17203 // target-specific builtins, perhaps?
17204 if (!FD->hasAttr<FormatAttr>())
17205 FD->addAttr(FormatAttr::CreateImplicit(Context,
17206 &Context.Idents.get("printf"), 2,
17207 Name->isStr("vasprintf") ? 0 : 3,
17208 FD->getLocation()));
17209 }
17210
17211 if (Name->isStr("__CFStringMakeConstantString")) {
17212 // We already have a __builtin___CFStringMakeConstantString,
17213 // but builds that use -fno-constant-cfstrings don't go through that.
17214 if (!FD->hasAttr<FormatArgAttr>())
17215 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
17216 FD->getLocation()));
17217 }
17218}
17219
17221 TypeSourceInfo *TInfo) {
17222 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
17223 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
17224
17225 if (!TInfo) {
17226 assert(D.isInvalidType() && "no declarator info for valid type");
17227 TInfo = Context.getTrivialTypeSourceInfo(T);
17228 }
17229
17230 // Scope manipulation handled by caller.
17231 TypedefDecl *NewTD =
17233 D.getIdentifierLoc(), D.getIdentifier(), TInfo);
17234
17235 // Bail out immediately if we have an invalid declaration.
17236 if (D.isInvalidType()) {
17237 NewTD->setInvalidDecl();
17238 return NewTD;
17239 }
17240
17242 if (CurContext->isFunctionOrMethod())
17243 Diag(NewTD->getLocation(), diag::err_module_private_local)
17244 << 2 << NewTD
17248 else
17249 NewTD->setModulePrivate();
17250 }
17251
17252 // C++ [dcl.typedef]p8:
17253 // If the typedef declaration defines an unnamed class (or
17254 // enum), the first typedef-name declared by the declaration
17255 // to be that class type (or enum type) is used to denote the
17256 // class type (or enum type) for linkage purposes only.
17257 // We need to check whether the type was declared in the declaration.
17258 switch (D.getDeclSpec().getTypeSpecType()) {
17259 case TST_enum:
17260 case TST_struct:
17261 case TST_interface:
17262 case TST_union:
17263 case TST_class: {
17264 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
17265 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
17266 break;
17267 }
17268
17269 default:
17270 break;
17271 }
17272
17273 return NewTD;
17274}
17275
17277 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
17278 QualType T = TI->getType();
17279
17280 if (T->isDependentType())
17281 return false;
17282
17283 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17284 // integral type; any cv-qualification is ignored.
17285 // C23 6.7.3.3p5: The underlying type of the enumeration is the unqualified,
17286 // non-atomic version of the type specified by the type specifiers in the
17287 // specifier qualifier list.
17288 // Because of how odd C's rule is, we'll let the user know that operations
17289 // involving the enumeration type will be non-atomic.
17290 if (T->isAtomicType())
17291 Diag(UnderlyingLoc, diag::warn_atomic_stripped_in_enum);
17292
17293 Qualifiers Q = T.getQualifiers();
17294 std::optional<unsigned> QualSelect;
17295 if (Q.hasConst() && Q.hasVolatile())
17296 QualSelect = diag::CVQualList::Both;
17297 else if (Q.hasConst())
17298 QualSelect = diag::CVQualList::Const;
17299 else if (Q.hasVolatile())
17300 QualSelect = diag::CVQualList::Volatile;
17301
17302 if (QualSelect)
17303 Diag(UnderlyingLoc, diag::warn_cv_stripped_in_enum) << *QualSelect;
17304
17305 T = T.getAtomicUnqualifiedType();
17306
17307 // This doesn't use 'isIntegralType' despite the error message mentioning
17308 // integral type because isIntegralType would also allow enum types in C.
17309 if (const BuiltinType *BT = T->getAs<BuiltinType>())
17310 if (BT->isInteger())
17311 return false;
17312
17313 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying)
17314 << T << T->isBitIntType();
17315}
17316
17318 QualType EnumUnderlyingTy, bool IsFixed,
17319 const EnumDecl *Prev) {
17320 if (IsScoped != Prev->isScoped()) {
17321 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
17322 << Prev->isScoped();
17323 Diag(Prev->getLocation(), diag::note_previous_declaration);
17324 return true;
17325 }
17326
17327 if (IsFixed && Prev->isFixed()) {
17328 if (!EnumUnderlyingTy->isDependentType() &&
17329 !Prev->getIntegerType()->isDependentType() &&
17330 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
17331 Prev->getIntegerType())) {
17332 // TODO: Highlight the underlying type of the redeclaration.
17333 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
17334 << EnumUnderlyingTy << Prev->getIntegerType();
17335 Diag(Prev->getLocation(), diag::note_previous_declaration)
17336 << Prev->getIntegerTypeRange();
17337 return true;
17338 }
17339 } else if (IsFixed != Prev->isFixed()) {
17340 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
17341 << Prev->isFixed();
17342 Diag(Prev->getLocation(), diag::note_previous_declaration);
17343 return true;
17344 }
17345
17346 return false;
17347}
17348
17349/// Get diagnostic %select index for tag kind for
17350/// redeclaration diagnostic message.
17351/// WARNING: Indexes apply to particular diagnostics only!
17352///
17353/// \returns diagnostic %select index.
17355 switch (Tag) {
17357 return 0;
17359 return 1;
17360 case TagTypeKind::Class:
17361 return 2;
17362 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
17363 }
17364}
17365
17366/// Determine if tag kind is a class-key compatible with
17367/// class for redeclaration (class, struct, or __interface).
17368///
17369/// \returns true iff the tag kind is compatible.
17371{
17372 return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class ||
17374}
17375
17377 if (isa<TypedefDecl>(PrevDecl))
17378 return NonTagKind::Typedef;
17379 else if (isa<TypeAliasDecl>(PrevDecl))
17380 return NonTagKind::TypeAlias;
17381 else if (isa<ClassTemplateDecl>(PrevDecl))
17382 return NonTagKind::Template;
17383 else if (isa<TypeAliasTemplateDecl>(PrevDecl))
17385 else if (isa<TemplateTemplateParmDecl>(PrevDecl))
17387 switch (TTK) {
17390 case TagTypeKind::Class:
17391 return getLangOpts().CPlusPlus ? NonTagKind::NonClass
17393 case TagTypeKind::Union:
17394 return NonTagKind::NonUnion;
17395 case TagTypeKind::Enum:
17396 return NonTagKind::NonEnum;
17397 }
17398 llvm_unreachable("invalid TTK");
17399}
17400
17402 TagTypeKind NewTag, bool isDefinition,
17403 SourceLocation NewTagLoc,
17404 const IdentifierInfo *Name) {
17405 // C++ [dcl.type.elab]p3:
17406 // The class-key or enum keyword present in the
17407 // elaborated-type-specifier shall agree in kind with the
17408 // declaration to which the name in the elaborated-type-specifier
17409 // refers. This rule also applies to the form of
17410 // elaborated-type-specifier that declares a class-name or
17411 // friend class since it can be construed as referring to the
17412 // definition of the class. Thus, in any
17413 // elaborated-type-specifier, the enum keyword shall be used to
17414 // refer to an enumeration (7.2), the union class-key shall be
17415 // used to refer to a union (clause 9), and either the class or
17416 // struct class-key shall be used to refer to a class (clause 9)
17417 // declared using the class or struct class-key.
17418 TagTypeKind OldTag = Previous->getTagKind();
17419 if (OldTag != NewTag &&
17421 return false;
17422
17423 // Tags are compatible, but we might still want to warn on mismatched tags.
17424 // Non-class tags can't be mismatched at this point.
17426 return true;
17427
17428 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
17429 // by our warning analysis. We don't want to warn about mismatches with (eg)
17430 // declarations in system headers that are designed to be specialized, but if
17431 // a user asks us to warn, we should warn if their code contains mismatched
17432 // declarations.
17433 auto IsIgnoredLoc = [&](SourceLocation Loc) {
17434 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
17435 Loc);
17436 };
17437 if (IsIgnoredLoc(NewTagLoc))
17438 return true;
17439
17440 auto IsIgnored = [&](const TagDecl *Tag) {
17441 return IsIgnoredLoc(Tag->getLocation());
17442 };
17443 while (IsIgnored(Previous)) {
17444 Previous = Previous->getPreviousDecl();
17445 if (!Previous)
17446 return true;
17447 OldTag = Previous->getTagKind();
17448 }
17449
17450 bool isTemplate = false;
17451 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
17452 isTemplate = Record->getDescribedClassTemplate();
17453
17455 if (OldTag != NewTag) {
17456 // In a template instantiation, do not offer fix-its for tag mismatches
17457 // since they usually mess up the template instead of fixing the problem.
17458 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
17460 << getRedeclDiagFromTagKind(OldTag);
17461 // FIXME: Note previous location?
17462 }
17463 return true;
17464 }
17465
17466 if (isDefinition) {
17467 // On definitions, check all previous tags and issue a fix-it for each
17468 // one that doesn't match the current tag.
17469 if (Previous->getDefinition()) {
17470 // Don't suggest fix-its for redefinitions.
17471 return true;
17472 }
17473
17474 bool previousMismatch = false;
17475 for (const TagDecl *I : Previous->redecls()) {
17476 if (I->getTagKind() != NewTag) {
17477 // Ignore previous declarations for which the warning was disabled.
17478 if (IsIgnored(I))
17479 continue;
17480
17481 if (!previousMismatch) {
17482 previousMismatch = true;
17483 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
17485 << getRedeclDiagFromTagKind(I->getTagKind());
17486 }
17487 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
17489 << FixItHint::CreateReplacement(I->getInnerLocStart(),
17491 }
17492 }
17493 return true;
17494 }
17495
17496 // Identify the prevailing tag kind: this is the kind of the definition (if
17497 // there is a non-ignored definition), or otherwise the kind of the prior
17498 // (non-ignored) declaration.
17499 const TagDecl *PrevDef = Previous->getDefinition();
17500 if (PrevDef && IsIgnored(PrevDef))
17501 PrevDef = nullptr;
17502 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
17503 if (Redecl->getTagKind() != NewTag) {
17504 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
17506 << getRedeclDiagFromTagKind(OldTag);
17507 Diag(Redecl->getLocation(), diag::note_previous_use);
17508
17509 // If there is a previous definition, suggest a fix-it.
17510 if (PrevDef) {
17511 Diag(NewTagLoc, diag::note_struct_class_suggestion)
17515 }
17516 }
17517
17518 return true;
17519}
17520
17521/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
17522/// from an outer enclosing namespace or file scope inside a friend declaration.
17523/// This should provide the commented out code in the following snippet:
17524/// namespace N {
17525/// struct X;
17526/// namespace M {
17527/// struct Y { friend struct /*N::*/ X; };
17528/// }
17529/// }
17531 SourceLocation NameLoc) {
17532 // While the decl is in a namespace, do repeated lookup of that name and see
17533 // if we get the same namespace back. If we do not, continue until
17534 // translation unit scope, at which point we have a fully qualified NNS.
17537 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
17538 // This tag should be declared in a namespace, which can only be enclosed by
17539 // other namespaces. Bail if there's an anonymous namespace in the chain.
17540 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
17541 if (!Namespace || Namespace->isAnonymousNamespace())
17542 return FixItHint();
17543 IdentifierInfo *II = Namespace->getIdentifier();
17544 Namespaces.push_back(II);
17545 NamedDecl *Lookup = SemaRef.LookupSingleName(
17546 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
17547 if (Lookup == Namespace)
17548 break;
17549 }
17550
17551 // Once we have all the namespaces, reverse them to go outermost first, and
17552 // build an NNS.
17553 SmallString<64> Insertion;
17554 llvm::raw_svector_ostream OS(Insertion);
17555 if (DC->isTranslationUnit())
17556 OS << "::";
17557 std::reverse(Namespaces.begin(), Namespaces.end());
17558 for (auto *II : Namespaces)
17559 OS << II->getName() << "::";
17560 return FixItHint::CreateInsertion(NameLoc, Insertion);
17561}
17562
17563/// Determine whether a tag originally declared in context \p OldDC can
17564/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
17565/// found a declaration in \p OldDC as a previous decl, perhaps through a
17566/// using-declaration).
17568 DeclContext *NewDC) {
17569 OldDC = OldDC->getRedeclContext();
17570 NewDC = NewDC->getRedeclContext();
17571
17572 if (OldDC->Equals(NewDC))
17573 return true;
17574
17575 // In MSVC mode, we allow a redeclaration if the contexts are related (either
17576 // encloses the other).
17577 if (S.getLangOpts().MSVCCompat &&
17578 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
17579 return true;
17580
17581 return false;
17582}
17583
17585Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
17586 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17587 const ParsedAttributesView &Attrs, AccessSpecifier AS,
17588 SourceLocation ModulePrivateLoc,
17589 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
17590 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
17591 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
17592 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
17593 OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
17594 // If this is not a definition, it must have a name.
17595 IdentifierInfo *OrigName = Name;
17596 assert((Name != nullptr || TUK == TagUseKind::Definition) &&
17597 "Nameless record must be a definition!");
17598 assert(TemplateParameterLists.size() == 0 || TUK != TagUseKind::Reference);
17599
17600 OwnedDecl = false;
17602 bool ScopedEnum = ScopedEnumKWLoc.isValid();
17603
17604 // FIXME: Check member specializations more carefully.
17605 bool isMemberSpecialization = false;
17606 bool IsInjectedClassName = false;
17607 bool Invalid = false;
17608
17609 // We only need to do this matching if we have template parameters
17610 // or a scope specifier, which also conveniently avoids this work
17611 // for non-C++ cases.
17612 if (TemplateParameterLists.size() > 0 ||
17613 (SS.isNotEmpty() && TUK != TagUseKind::Reference)) {
17614 TemplateParameterList *TemplateParams =
17616 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
17617 TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);
17618
17619 // C++23 [dcl.type.elab] p2:
17620 // If an elaborated-type-specifier is the sole constituent of a
17621 // declaration, the declaration is ill-formed unless it is an explicit
17622 // specialization, an explicit instantiation or it has one of the
17623 // following forms: [...]
17624 // C++23 [dcl.enum] p1:
17625 // If the enum-head-name of an opaque-enum-declaration contains a
17626 // nested-name-specifier, the declaration shall be an explicit
17627 // specialization.
17628 //
17629 // FIXME: Class template partial specializations can be forward declared
17630 // per CWG2213, but the resolution failed to allow qualified forward
17631 // declarations. This is almost certainly unintentional, so we allow them.
17632 if (TUK == TagUseKind::Declaration && SS.isNotEmpty() &&
17633 !isMemberSpecialization)
17634 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
17636
17637 if (TemplateParams) {
17638 if (Kind == TagTypeKind::Enum) {
17639 Diag(KWLoc, diag::err_enum_template);
17640 return true;
17641 }
17642
17643 if (TemplateParams->size() > 0) {
17644 // This is a declaration or definition of a class template (which may
17645 // be a member of another template).
17646
17647 if (Invalid)
17648 return true;
17649
17650 OwnedDecl = false;
17652 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
17653 AS, ModulePrivateLoc,
17654 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
17655 TemplateParameterLists.data(), SkipBody);
17656 return Result.get();
17657 } else {
17658 // The "template<>" header is extraneous.
17659 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
17660 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
17661 isMemberSpecialization = true;
17662 }
17663 }
17664
17665 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
17666 CheckTemplateDeclScope(S, TemplateParameterLists.back()))
17667 return true;
17668 }
17669
17670 if (TUK == TagUseKind::Friend && Kind == TagTypeKind::Enum) {
17671 // C++23 [dcl.type.elab]p4:
17672 // If an elaborated-type-specifier appears with the friend specifier as
17673 // an entire member-declaration, the member-declaration shall have one
17674 // of the following forms:
17675 // friend class-key nested-name-specifier(opt) identifier ;
17676 // friend class-key simple-template-id ;
17677 // friend class-key nested-name-specifier template(opt)
17678 // simple-template-id ;
17679 //
17680 // Since enum is not a class-key, so declarations like "friend enum E;"
17681 // are ill-formed. Although CWG2363 reaffirms that such declarations are
17682 // invalid, most implementations accept so we issue a pedantic warning.
17683 Diag(KWLoc, diag::ext_enum_friend) << FixItHint::CreateRemoval(
17684 ScopedEnum ? SourceRange(KWLoc, ScopedEnumKWLoc) : KWLoc);
17685 assert(ScopedEnum || !ScopedEnumUsesClassTag);
17686 Diag(KWLoc, diag::note_enum_friend)
17687 << (ScopedEnum + ScopedEnumUsesClassTag);
17688 }
17689
17690 // Figure out the underlying type if this a enum declaration. We need to do
17691 // this early, because it's needed to detect if this is an incompatible
17692 // redeclaration.
17693 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
17694 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
17695
17696 if (Kind == TagTypeKind::Enum) {
17697 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
17698 // No underlying type explicitly specified, or we failed to parse the
17699 // type, default to int.
17700 EnumUnderlying = Context.IntTy.getTypePtr();
17701 } else if (UnderlyingType.get()) {
17702 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17703 // integral type; any cv-qualification is ignored.
17704 // C23 6.7.3.3p5: The underlying type of the enumeration is the
17705 // unqualified, non-atomic version of the type specified by the type
17706 // specifiers in the specifier qualifier list.
17707 TypeSourceInfo *TI = nullptr;
17708 GetTypeFromParser(UnderlyingType.get(), &TI);
17709 EnumUnderlying = TI;
17710
17712 // Recover by falling back to int.
17713 EnumUnderlying = Context.IntTy.getTypePtr();
17714
17717 EnumUnderlying = Context.IntTy.getTypePtr();
17718
17719 // If the underlying type is atomic, we need to adjust the type before
17720 // continuing. This only happens in the case we stored a TypeSourceInfo
17721 // into EnumUnderlying because the other cases are error recovery up to
17722 // this point. But because it's not possible to gin up a TypeSourceInfo
17723 // for a non-atomic type from an atomic one, we'll store into the Type
17724 // field instead. FIXME: it would be nice to have an easy way to get a
17725 // derived TypeSourceInfo which strips qualifiers including the weird
17726 // ones like _Atomic where it forms a different type.
17727 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying);
17728 TI && TI->getType()->isAtomicType())
17729 EnumUnderlying = TI->getType().getAtomicUnqualifiedType().getTypePtr();
17730
17731 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
17732 // For MSVC ABI compatibility, unfixed enums must use an underlying type
17733 // of 'int'. However, if this is an unfixed forward declaration, don't set
17734 // the underlying type unless the user enables -fms-compatibility. This
17735 // makes unfixed forward declared enums incomplete and is more conforming.
17736 if (TUK == TagUseKind::Definition || getLangOpts().MSVCCompat)
17737 EnumUnderlying = Context.IntTy.getTypePtr();
17738 }
17739 }
17740
17741 DeclContext *SearchDC = CurContext;
17742 DeclContext *DC = CurContext;
17743 bool isStdBadAlloc = false;
17744 bool isStdAlignValT = false;
17745
17747 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference)
17749
17750 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
17751 /// implemented asks for structural equivalence checking, the returned decl
17752 /// here is passed back to the parser, allowing the tag body to be parsed.
17753 auto createTagFromNewDecl = [&]() -> TagDecl * {
17754 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
17755 // If there is an identifier, use the location of the identifier as the
17756 // location of the decl, otherwise use the location of the struct/union
17757 // keyword.
17758 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
17759 TagDecl *New = nullptr;
17760
17761 if (Kind == TagTypeKind::Enum) {
17762 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
17763 ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
17764 // If this is an undefined enum, bail.
17765 if (TUK != TagUseKind::Definition && !Invalid)
17766 return nullptr;
17767 if (EnumUnderlying) {
17769 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying))
17771 else
17772 ED->setIntegerType(QualType(cast<const Type *>(EnumUnderlying), 0));
17773 QualType EnumTy = ED->getIntegerType();
17774 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
17775 ? Context.getPromotedIntegerType(EnumTy)
17776 : EnumTy);
17777 }
17778 } else { // struct/union
17779 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17780 nullptr);
17781 }
17782
17783 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
17784 // Add alignment attributes if necessary; these attributes are checked
17785 // when the ASTContext lays out the structure.
17786 //
17787 // It is important for implementing the correct semantics that this
17788 // happen here (in ActOnTag). The #pragma pack stack is
17789 // maintained as a result of parser callbacks which can occur at
17790 // many points during the parsing of a struct declaration (because
17791 // the #pragma tokens are effectively skipped over during the
17792 // parsing of the struct).
17793 if (TUK == TagUseKind::Definition &&
17794 (!SkipBody || !SkipBody->ShouldSkip)) {
17795 if (LangOpts.HLSL)
17796 RD->addAttr(PackedAttr::CreateImplicit(Context));
17799 }
17800 }
17801 New->setLexicalDeclContext(CurContext);
17802 return New;
17803 };
17804
17805 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
17806 if (Name && SS.isNotEmpty()) {
17807 // We have a nested-name tag ('struct foo::bar').
17808
17809 // Check for invalid 'foo::'.
17810 if (SS.isInvalid()) {
17811 Name = nullptr;
17812 goto CreateNewDecl;
17813 }
17814
17815 // If this is a friend or a reference to a class in a dependent
17816 // context, don't try to make a decl for it.
17817 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
17818 DC = computeDeclContext(SS, false);
17819 if (!DC) {
17820 IsDependent = true;
17821 return true;
17822 }
17823 } else {
17824 DC = computeDeclContext(SS, true);
17825 if (!DC) {
17826 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
17827 << SS.getRange();
17828 return true;
17829 }
17830 }
17831
17832 if (RequireCompleteDeclContext(SS, DC))
17833 return true;
17834
17835 SearchDC = DC;
17836 // Look-up name inside 'foo::'.
17838
17839 if (Previous.isAmbiguous())
17840 return true;
17841
17842 if (Previous.empty()) {
17843 // Name lookup did not find anything. However, if the
17844 // nested-name-specifier refers to the current instantiation,
17845 // and that current instantiation has any dependent base
17846 // classes, we might find something at instantiation time: treat
17847 // this as a dependent elaborated-type-specifier.
17848 // But this only makes any sense for reference-like lookups.
17849 if (Previous.wasNotFoundInCurrentInstantiation() &&
17850 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)) {
17851 IsDependent = true;
17852 return true;
17853 }
17854
17855 // A tag 'foo::bar' must already exist.
17856 Diag(NameLoc, diag::err_not_tag_in_scope)
17857 << Kind << Name << DC << SS.getRange();
17858 Name = nullptr;
17859 Invalid = true;
17860 goto CreateNewDecl;
17861 }
17862 } else if (Name) {
17863 // C++14 [class.mem]p14:
17864 // If T is the name of a class, then each of the following shall have a
17865 // name different from T:
17866 // -- every member of class T that is itself a type
17867 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
17868 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
17869 return true;
17870
17871 // If this is a named struct, check to see if there was a previous forward
17872 // declaration or definition.
17873 // FIXME: We're looking into outer scopes here, even when we
17874 // shouldn't be. Doing so can result in ambiguities that we
17875 // shouldn't be diagnosing.
17876 LookupName(Previous, S);
17877
17878 // When declaring or defining a tag, ignore ambiguities introduced
17879 // by types using'ed into this scope.
17880 if (Previous.isAmbiguous() &&
17882 LookupResult::Filter F = Previous.makeFilter();
17883 while (F.hasNext()) {
17884 NamedDecl *ND = F.next();
17885 if (!ND->getDeclContext()->getRedeclContext()->Equals(
17886 SearchDC->getRedeclContext()))
17887 F.erase();
17888 }
17889 F.done();
17890 }
17891
17892 // C++11 [namespace.memdef]p3:
17893 // If the name in a friend declaration is neither qualified nor
17894 // a template-id and the declaration is a function or an
17895 // elaborated-type-specifier, the lookup to determine whether
17896 // the entity has been previously declared shall not consider
17897 // any scopes outside the innermost enclosing namespace.
17898 //
17899 // MSVC doesn't implement the above rule for types, so a friend tag
17900 // declaration may be a redeclaration of a type declared in an enclosing
17901 // scope. They do implement this rule for friend functions.
17902 //
17903 // Does it matter that this should be by scope instead of by
17904 // semantic context?
17905 if (!Previous.empty() && TUK == TagUseKind::Friend) {
17906 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
17907 LookupResult::Filter F = Previous.makeFilter();
17908 bool FriendSawTagOutsideEnclosingNamespace = false;
17909 while (F.hasNext()) {
17910 NamedDecl *ND = F.next();
17912 if (DC->isFileContext() &&
17913 !EnclosingNS->Encloses(ND->getDeclContext())) {
17914 if (getLangOpts().MSVCCompat)
17915 FriendSawTagOutsideEnclosingNamespace = true;
17916 else
17917 F.erase();
17918 }
17919 }
17920 F.done();
17921
17922 // Diagnose this MSVC extension in the easy case where lookup would have
17923 // unambiguously found something outside the enclosing namespace.
17924 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
17925 NamedDecl *ND = Previous.getFoundDecl();
17926 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
17927 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
17928 }
17929 }
17930
17931 // Note: there used to be some attempt at recovery here.
17932 if (Previous.isAmbiguous())
17933 return true;
17934
17935 if (!getLangOpts().CPlusPlus && TUK != TagUseKind::Reference) {
17936 // FIXME: This makes sure that we ignore the contexts associated
17937 // with C structs, unions, and enums when looking for a matching
17938 // tag declaration or definition. See the similar lookup tweak
17939 // in Sema::LookupName; is there a better way to deal with this?
17941 SearchDC = SearchDC->getParent();
17942 } else if (getLangOpts().CPlusPlus) {
17943 // Inside ObjCContainer want to keep it as a lexical decl context but go
17944 // past it (most often to TranslationUnit) to find the semantic decl
17945 // context.
17946 while (isa<ObjCContainerDecl>(SearchDC))
17947 SearchDC = SearchDC->getParent();
17948 }
17949 } else if (getLangOpts().CPlusPlus) {
17950 // Don't use ObjCContainerDecl as the semantic decl context for anonymous
17951 // TagDecl the same way as we skip it for named TagDecl.
17952 while (isa<ObjCContainerDecl>(SearchDC))
17953 SearchDC = SearchDC->getParent();
17954 }
17955
17956 if (Previous.isSingleResult() &&
17957 Previous.getFoundDecl()->isTemplateParameter()) {
17958 // Maybe we will complain about the shadowed template parameter.
17959 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
17960 // Just pretend that we didn't see the previous declaration.
17961 Previous.clear();
17962 }
17963
17964 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
17965 DC->Equals(getStdNamespace())) {
17966 if (Name->isStr("bad_alloc")) {
17967 // This is a declaration of or a reference to "std::bad_alloc".
17968 isStdBadAlloc = true;
17969
17970 // If std::bad_alloc has been implicitly declared (but made invisible to
17971 // name lookup), fill in this implicit declaration as the previous
17972 // declaration, so that the declarations get chained appropriately.
17973 if (Previous.empty() && StdBadAlloc)
17974 Previous.addDecl(getStdBadAlloc());
17975 } else if (Name->isStr("align_val_t")) {
17976 isStdAlignValT = true;
17977 if (Previous.empty() && StdAlignValT)
17978 Previous.addDecl(getStdAlignValT());
17979 }
17980 }
17981
17982 // If we didn't find a previous declaration, and this is a reference
17983 // (or friend reference), move to the correct scope. In C++, we
17984 // also need to do a redeclaration lookup there, just in case
17985 // there's a shadow friend decl.
17986 if (Name && Previous.empty() &&
17987 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
17988 IsTemplateParamOrArg)) {
17989 if (Invalid) goto CreateNewDecl;
17990 assert(SS.isEmpty());
17991
17992 if (TUK == TagUseKind::Reference || IsTemplateParamOrArg) {
17993 // C++ [basic.scope.pdecl]p5:
17994 // -- for an elaborated-type-specifier of the form
17995 //
17996 // class-key identifier
17997 //
17998 // if the elaborated-type-specifier is used in the
17999 // decl-specifier-seq or parameter-declaration-clause of a
18000 // function defined in namespace scope, the identifier is
18001 // declared as a class-name in the namespace that contains
18002 // the declaration; otherwise, except as a friend
18003 // declaration, the identifier is declared in the smallest
18004 // non-class, non-function-prototype scope that contains the
18005 // declaration.
18006 //
18007 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
18008 // C structs and unions.
18009 //
18010 // It is an error in C++ to declare (rather than define) an enum
18011 // type, including via an elaborated type specifier. We'll
18012 // diagnose that later; for now, declare the enum in the same
18013 // scope as we would have picked for any other tag type.
18014 //
18015 // GNU C also supports this behavior as part of its incomplete
18016 // enum types extension, while GNU C++ does not.
18017 //
18018 // Find the context where we'll be declaring the tag.
18019 // FIXME: We would like to maintain the current DeclContext as the
18020 // lexical context,
18021 SearchDC = getTagInjectionContext(SearchDC);
18022
18023 // Find the scope where we'll be declaring the tag.
18025 } else {
18026 assert(TUK == TagUseKind::Friend);
18027 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(SearchDC);
18028
18029 // C++ [namespace.memdef]p3:
18030 // If a friend declaration in a non-local class first declares a
18031 // class or function, the friend class or function is a member of
18032 // the innermost enclosing namespace.
18033 SearchDC = RD->isLocalClass() ? RD->isLocalClass()
18034 : SearchDC->getEnclosingNamespaceContext();
18035 }
18036
18037 // In C++, we need to do a redeclaration lookup to properly
18038 // diagnose some problems.
18039 // FIXME: redeclaration lookup is also used (with and without C++) to find a
18040 // hidden declaration so that we don't get ambiguity errors when using a
18041 // type declared by an elaborated-type-specifier. In C that is not correct
18042 // and we should instead merge compatible types found by lookup.
18043 if (getLangOpts().CPlusPlus) {
18044 // FIXME: This can perform qualified lookups into function contexts,
18045 // which are meaningless.
18046 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18047 LookupQualifiedName(Previous, SearchDC);
18048 } else {
18049 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18050 LookupName(Previous, S);
18051 }
18052 }
18053
18054 // If we have a known previous declaration to use, then use it.
18055 if (Previous.empty() && SkipBody && SkipBody->Previous)
18056 Previous.addDecl(SkipBody->Previous);
18057
18058 if (!Previous.empty()) {
18059 NamedDecl *PrevDecl = Previous.getFoundDecl();
18060 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
18061
18062 // It's okay to have a tag decl in the same scope as a typedef
18063 // which hides a tag decl in the same scope. Finding this
18064 // with a redeclaration lookup can only actually happen in C++.
18065 //
18066 // This is also okay for elaborated-type-specifiers, which is
18067 // technically forbidden by the current standard but which is
18068 // okay according to the likely resolution of an open issue;
18069 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
18070 if (getLangOpts().CPlusPlus) {
18071 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
18072 if (TagDecl *Tag = TD->getUnderlyingType()->getAsTagDecl()) {
18073 if (Tag->getDeclName() == Name &&
18074 Tag->getDeclContext()->getRedeclContext()
18075 ->Equals(TD->getDeclContext()->getRedeclContext())) {
18076 PrevDecl = Tag;
18077 Previous.clear();
18078 Previous.addDecl(Tag);
18079 Previous.resolveKind();
18080 }
18081 }
18082 } else if (auto *RD = dyn_cast<CXXRecordDecl>(PrevDecl);
18083 TUK == TagUseKind::Reference && RD &&
18084 RD->isInjectedClassName()) {
18085 // If lookup found the injected class name, the previous declaration is
18086 // the class being injected into.
18087 PrevDecl = cast<TagDecl>(RD->getDeclContext());
18088 Previous.clear();
18089 Previous.addDecl(PrevDecl);
18090 Previous.resolveKind();
18091 IsInjectedClassName = true;
18092 }
18093 }
18094
18095 // If this is a redeclaration of a using shadow declaration, it must
18096 // declare a tag in the same context. In MSVC mode, we allow a
18097 // redefinition if either context is within the other.
18098 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
18099 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
18100 if (SS.isEmpty() && TUK != TagUseKind::Reference &&
18101 TUK != TagUseKind::Friend &&
18102 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
18103 !(OldTag && isAcceptableTagRedeclContext(
18104 *this, OldTag->getDeclContext(), SearchDC))) {
18105 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
18106 Diag(Shadow->getTargetDecl()->getLocation(),
18107 diag::note_using_decl_target);
18108 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
18109 << 0;
18110 // Recover by ignoring the old declaration.
18111 Previous.clear();
18112 goto CreateNewDecl;
18113 }
18114 }
18115
18116 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
18117 // If this is a use of a previous tag, or if the tag is already declared
18118 // in the same scope (so that the definition/declaration completes or
18119 // rementions the tag), reuse the decl.
18120 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
18121 isDeclInScope(DirectPrevDecl, SearchDC, S,
18122 SS.isNotEmpty() || isMemberSpecialization)) {
18123 // Make sure that this wasn't declared as an enum and now used as a
18124 // struct or something similar.
18125 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
18126 TUK == TagUseKind::Definition, KWLoc,
18127 Name)) {
18128 bool SafeToContinue =
18129 (PrevTagDecl->getTagKind() != TagTypeKind::Enum &&
18130 Kind != TagTypeKind::Enum);
18131 if (SafeToContinue)
18132 Diag(KWLoc, diag::err_use_with_wrong_tag)
18133 << Name
18135 PrevTagDecl->getKindName());
18136 else
18137 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
18138 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
18139
18140 if (SafeToContinue)
18141 Kind = PrevTagDecl->getTagKind();
18142 else {
18143 // Recover by making this an anonymous redefinition.
18144 Name = nullptr;
18145 Previous.clear();
18146 Invalid = true;
18147 }
18148 }
18149
18150 if (Kind == TagTypeKind::Enum &&
18151 PrevTagDecl->getTagKind() == TagTypeKind::Enum) {
18152 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
18153 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)
18154 return PrevTagDecl;
18155
18156 QualType EnumUnderlyingTy;
18157 if (TypeSourceInfo *TI =
18158 dyn_cast_if_present<TypeSourceInfo *>(EnumUnderlying))
18159 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
18160 else if (const Type *T =
18161 dyn_cast_if_present<const Type *>(EnumUnderlying))
18162 EnumUnderlyingTy = QualType(T, 0);
18163
18164 // All conflicts with previous declarations are recovered by
18165 // returning the previous declaration, unless this is a definition,
18166 // in which case we want the caller to bail out.
18167 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
18168 ScopedEnum, EnumUnderlyingTy,
18169 IsFixed, PrevEnum))
18170 return TUK == TagUseKind::Declaration ? PrevTagDecl : nullptr;
18171 }
18172
18173 // C++11 [class.mem]p1:
18174 // A member shall not be declared twice in the member-specification,
18175 // except that a nested class or member class template can be declared
18176 // and then later defined.
18177 if (TUK == TagUseKind::Declaration && PrevDecl->isCXXClassMember() &&
18178 S->isDeclScope(PrevDecl)) {
18179 Diag(NameLoc, diag::ext_member_redeclared);
18180 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
18181 }
18182
18183 if (!Invalid) {
18184 // If this is a use, just return the declaration we found, unless
18185 // we have attributes.
18186 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18187 if (!Attrs.empty()) {
18188 // FIXME: Diagnose these attributes. For now, we create a new
18189 // declaration to hold them.
18190 } else if (TUK == TagUseKind::Reference &&
18191 (PrevTagDecl->getFriendObjectKind() ==
18193 PrevDecl->getOwningModule() != getCurrentModule()) &&
18194 SS.isEmpty()) {
18195 // This declaration is a reference to an existing entity, but
18196 // has different visibility from that entity: it either makes
18197 // a friend visible or it makes a type visible in a new module.
18198 // In either case, create a new declaration. We only do this if
18199 // the declaration would have meant the same thing if no prior
18200 // declaration were found, that is, if it was found in the same
18201 // scope where we would have injected a declaration.
18202 if (!getTagInjectionContext(CurContext)->getRedeclContext()
18203 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
18204 return PrevTagDecl;
18205 // This is in the injected scope, create a new declaration in
18206 // that scope.
18208 } else {
18209 return PrevTagDecl;
18210 }
18211 }
18212
18213 // Diagnose attempts to redefine a tag.
18214 if (TUK == TagUseKind::Definition) {
18215 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
18216 // If the type is currently being defined, complain
18217 // about a nested redefinition.
18218 if (Def->isBeingDefined()) {
18219 Diag(NameLoc, diag::err_nested_redefinition) << Name;
18220 Diag(PrevTagDecl->getLocation(),
18221 diag::note_previous_definition);
18222 Name = nullptr;
18223 Previous.clear();
18224 Invalid = true;
18225 } else {
18226 // If we're defining a specialization and the previous
18227 // definition is from an implicit instantiation, don't emit an
18228 // error here; we'll catch this in the general case below.
18229 bool IsExplicitSpecializationAfterInstantiation = false;
18230 if (isMemberSpecialization) {
18231 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
18232 IsExplicitSpecializationAfterInstantiation =
18233 RD->getTemplateSpecializationKind() !=
18235 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
18236 IsExplicitSpecializationAfterInstantiation =
18237 ED->getTemplateSpecializationKind() !=
18239 }
18240
18241 // Note that clang allows ODR-like semantics for ObjC/C, i.e.,
18242 // do not keep more that one definition around (merge them).
18243 // However, ensure the decl passes the structural compatibility
18244 // check in C11 6.2.7/1 (or 6.1.2.6/1 in C89).
18245 NamedDecl *Hidden = nullptr;
18246 bool HiddenDefVisible = false;
18247 if (SkipBody &&
18248 (isRedefinitionAllowedFor(Def, &Hidden, HiddenDefVisible) ||
18249 getLangOpts().C23)) {
18250 // There is a definition of this tag, but it is not visible.
18251 // We explicitly make use of C++'s one definition rule here,
18252 // and assume that this definition is identical to the hidden
18253 // one we already have. Make the existing definition visible
18254 // and use it in place of this one.
18255 if (!getLangOpts().CPlusPlus) {
18256 // Postpone making the old definition visible until after we
18257 // complete parsing the new one and do the structural
18258 // comparison.
18259 SkipBody->CheckSameAsPrevious = true;
18260 SkipBody->New = createTagFromNewDecl();
18261 SkipBody->Previous = Def;
18262
18263 ProcessDeclAttributeList(S, SkipBody->New, Attrs);
18264 return Def;
18265 }
18266
18267 SkipBody->ShouldSkip = true;
18268 SkipBody->Previous = Def;
18269 if (!HiddenDefVisible && Hidden)
18271 // Carry on and handle it like a normal definition. We'll
18272 // skip starting the definition later.
18273
18274 } else if (!IsExplicitSpecializationAfterInstantiation) {
18275 // A redeclaration in function prototype scope in C isn't
18276 // visible elsewhere, so merely issue a warning.
18277 if (!getLangOpts().CPlusPlus &&
18279 Diag(NameLoc, diag::warn_redefinition_in_param_list)
18280 << Name;
18281 else
18282 Diag(NameLoc, diag::err_redefinition) << Name;
18284 NameLoc.isValid() ? NameLoc : KWLoc);
18285 // If this is a redefinition, recover by making this
18286 // struct be anonymous, which will make any later
18287 // references get the previous definition.
18288 Name = nullptr;
18289 Previous.clear();
18290 Invalid = true;
18291 }
18292 }
18293 }
18294
18295 // Okay, this is definition of a previously declared or referenced
18296 // tag. We're going to create a new Decl for it.
18297 }
18298
18299 // Okay, we're going to make a redeclaration. If this is some kind
18300 // of reference, make sure we build the redeclaration in the same DC
18301 // as the original, and ignore the current access specifier.
18302 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
18303 SearchDC = PrevTagDecl->getDeclContext();
18304 AS = AS_none;
18305 }
18306 }
18307 // If we get here we have (another) forward declaration or we
18308 // have a definition. Just create a new decl.
18309
18310 } else {
18311 // If we get here, this is a definition of a new tag type in a nested
18312 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
18313 // new decl/type. We set PrevDecl to NULL so that the entities
18314 // have distinct types.
18315 Previous.clear();
18316 }
18317 // If we get here, we're going to create a new Decl. If PrevDecl
18318 // is non-NULL, it's a definition of the tag declared by
18319 // PrevDecl. If it's NULL, we have a new definition.
18320
18321 // Otherwise, PrevDecl is not a tag, but was found with tag
18322 // lookup. This is only actually possible in C++, where a few
18323 // things like templates still live in the tag namespace.
18324 } else {
18325 // Use a better diagnostic if an elaborated-type-specifier
18326 // found the wrong kind of type on the first
18327 // (non-redeclaration) lookup.
18328 if ((TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) &&
18329 !Previous.isForRedeclaration()) {
18330 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
18331 Diag(NameLoc, diag::err_tag_reference_non_tag)
18332 << PrevDecl << NTK << Kind;
18333 Diag(PrevDecl->getLocation(), diag::note_declared_at);
18334 Invalid = true;
18335
18336 // Otherwise, only diagnose if the declaration is in scope.
18337 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
18338 SS.isNotEmpty() || isMemberSpecialization)) {
18339 // do nothing
18340
18341 // Diagnose implicit declarations introduced by elaborated types.
18342 } else if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18343 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
18344 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
18345 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
18346 Invalid = true;
18347
18348 // Otherwise it's a declaration. Call out a particularly common
18349 // case here.
18350 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
18351 unsigned Kind = 0;
18352 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
18353 Diag(NameLoc, diag::err_tag_definition_of_typedef)
18354 << Name << Kind << TND->getUnderlyingType();
18355 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
18356 Invalid = true;
18357
18358 // Otherwise, diagnose.
18359 } else {
18360 // The tag name clashes with something else in the target scope,
18361 // issue an error and recover by making this tag be anonymous.
18362 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
18363 notePreviousDefinition(PrevDecl, NameLoc);
18364 Name = nullptr;
18365 Invalid = true;
18366 }
18367
18368 // The existing declaration isn't relevant to us; we're in a
18369 // new scope, so clear out the previous declaration.
18370 Previous.clear();
18371 }
18372 }
18373
18374CreateNewDecl:
18375
18376 TagDecl *PrevDecl = nullptr;
18377 if (Previous.isSingleResult())
18378 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
18379
18380 // If there is an identifier, use the location of the identifier as the
18381 // location of the decl, otherwise use the location of the struct/union
18382 // keyword.
18383 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
18384
18385 // Otherwise, create a new declaration. If there is a previous
18386 // declaration of the same entity, the two will be linked via
18387 // PrevDecl.
18388 TagDecl *New;
18389
18390 if (Kind == TagTypeKind::Enum) {
18391 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18392 // enum X { A, B, C } D; D should chain to X.
18393 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
18394 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
18395 ScopedEnumUsesClassTag, IsFixed);
18396
18397 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
18399
18400 // If this is an undefined enum, warn.
18401 if (TUK != TagUseKind::Definition && !Invalid) {
18402 TagDecl *Def;
18403 if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
18404 // C++0x: 7.2p2: opaque-enum-declaration.
18405 // Conflicts are diagnosed above. Do nothing.
18406 }
18407 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
18408 Diag(Loc, diag::ext_forward_ref_enum_def)
18409 << New;
18410 Diag(Def->getLocation(), diag::note_previous_definition);
18411 } else {
18412 unsigned DiagID = diag::ext_forward_ref_enum;
18413 if (getLangOpts().MSVCCompat)
18414 DiagID = diag::ext_ms_forward_ref_enum;
18415 else if (getLangOpts().CPlusPlus)
18416 DiagID = diag::err_forward_ref_enum;
18417 Diag(Loc, DiagID);
18418 }
18419 }
18420
18421 if (EnumUnderlying) {
18423 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying))
18425 else
18426 ED->setIntegerType(QualType(cast<const Type *>(EnumUnderlying), 0));
18427 QualType EnumTy = ED->getIntegerType();
18428 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
18429 ? Context.getPromotedIntegerType(EnumTy)
18430 : EnumTy);
18431 assert(ED->isComplete() && "enum with type should be complete");
18432 }
18433 } else {
18434 // struct/union/class
18435
18436 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18437 // struct X { int A; } D; D should chain to X.
18438 if (getLangOpts().CPlusPlus) {
18439 // FIXME: Look for a way to use RecordDecl for simple structs.
18440 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
18441 cast_or_null<CXXRecordDecl>(PrevDecl));
18442
18443 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
18445 } else
18446 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
18447 cast_or_null<RecordDecl>(PrevDecl));
18448 }
18449
18450 // Only C23 and later allow defining new types in 'offsetof()'.
18451 if (OOK != OffsetOfKind::Outside && TUK == TagUseKind::Definition &&
18453 Diag(New->getLocation(), diag::ext_type_defined_in_offsetof)
18454 << (OOK == OffsetOfKind::Macro) << New->getSourceRange();
18455
18456 // C++11 [dcl.type]p3:
18457 // A type-specifier-seq shall not define a class or enumeration [...].
18458 if (!Invalid && getLangOpts().CPlusPlus &&
18459 (IsTypeSpecifier || IsTemplateParamOrArg) &&
18460 TUK == TagUseKind::Definition) {
18461 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
18462 << Context.getCanonicalTagType(New);
18463 Invalid = true;
18464 }
18465
18467 DC->getDeclKind() == Decl::Enum) {
18468 Diag(New->getLocation(), diag::err_type_defined_in_enum)
18469 << Context.getCanonicalTagType(New);
18470 Invalid = true;
18471 }
18472
18473 // Maybe add qualifier info.
18474 if (SS.isNotEmpty()) {
18475 if (SS.isSet()) {
18476 // If this is either a declaration or a definition, check the
18477 // nested-name-specifier against the current context.
18478 if ((TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration) &&
18479 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
18480 /*TemplateId=*/nullptr,
18481 isMemberSpecialization))
18482 Invalid = true;
18483
18484 New->setQualifierInfo(SS.getWithLocInContext(Context));
18485 if (TemplateParameterLists.size() > 0) {
18486 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
18487 }
18488 }
18489 else
18490 Invalid = true;
18491 }
18492
18493 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
18494 // Add alignment attributes if necessary; these attributes are checked when
18495 // the ASTContext lays out the structure.
18496 //
18497 // It is important for implementing the correct semantics that this
18498 // happen here (in ActOnTag). The #pragma pack stack is
18499 // maintained as a result of parser callbacks which can occur at
18500 // many points during the parsing of a struct declaration (because
18501 // the #pragma tokens are effectively skipped over during the
18502 // parsing of the struct).
18503 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
18504 if (LangOpts.HLSL)
18505 RD->addAttr(PackedAttr::CreateImplicit(Context));
18508 }
18509 }
18510
18511 if (ModulePrivateLoc.isValid()) {
18512 if (isMemberSpecialization)
18513 Diag(New->getLocation(), diag::err_module_private_specialization)
18514 << 2
18515 << FixItHint::CreateRemoval(ModulePrivateLoc);
18516 // __module_private__ does not apply to local classes. However, we only
18517 // diagnose this as an error when the declaration specifiers are
18518 // freestanding. Here, we just ignore the __module_private__.
18519 else if (!SearchDC->isFunctionOrMethod())
18520 New->setModulePrivate();
18521 }
18522
18523 // If this is a specialization of a member class (of a class template),
18524 // check the specialization.
18525 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
18526 Invalid = true;
18527
18528 // If we're declaring or defining a tag in function prototype scope in C,
18529 // note that this type can only be used within the function and add it to
18530 // the list of decls to inject into the function definition scope. However,
18531 // in C23 and later, while the type is only visible within the function, the
18532 // function can be called with a compatible type defined in the same TU, so
18533 // we silence the diagnostic in C23 and up. This matches the behavior of GCC.
18534 if ((Name || Kind == TagTypeKind::Enum) &&
18535 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
18536 if (getLangOpts().CPlusPlus) {
18537 // C++ [dcl.fct]p6:
18538 // Types shall not be defined in return or parameter types.
18539 if (TUK == TagUseKind::Definition && !IsTypeSpecifier) {
18540 Diag(Loc, diag::err_type_defined_in_param_type)
18541 << Name;
18542 Invalid = true;
18543 }
18544 if (TUK == TagUseKind::Declaration)
18545 Invalid = true;
18546 } else if (!PrevDecl) {
18547 // In C23 mode, if the declaration is complete, we do not want to
18548 // diagnose.
18549 if (!getLangOpts().C23 || TUK != TagUseKind::Definition)
18550 Diag(Loc, diag::warn_decl_in_param_list)
18551 << Context.getCanonicalTagType(New);
18552 }
18553 }
18554
18555 if (Invalid)
18556 New->setInvalidDecl();
18557
18558 // Set the lexical context. If the tag has a C++ scope specifier, the
18559 // lexical context will be different from the semantic context.
18560 New->setLexicalDeclContext(CurContext);
18561
18562 // Mark this as a friend decl if applicable.
18563 // In Microsoft mode, a friend declaration also acts as a forward
18564 // declaration so we always pass true to setObjectOfFriendDecl to make
18565 // the tag name visible.
18566 if (TUK == TagUseKind::Friend)
18567 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
18568
18569 // Set the access specifier.
18570 if (!Invalid && SearchDC->isRecord())
18571 SetMemberAccessSpecifier(New, PrevDecl, AS);
18572
18573 if (PrevDecl)
18575
18576 if (TUK == TagUseKind::Definition) {
18577 if (!SkipBody || !SkipBody->ShouldSkip) {
18578 New->startDefinition();
18579 } else {
18580 New->setCompleteDefinition();
18581 New->demoteThisDefinitionToDeclaration();
18582 }
18583 }
18584
18585 ProcessDeclAttributeList(S, New, Attrs);
18587
18588 // If this has an identifier, add it to the scope stack.
18589 if (TUK == TagUseKind::Friend || IsInjectedClassName) {
18590 // We might be replacing an existing declaration in the lookup tables;
18591 // if so, borrow its access specifier.
18592 if (PrevDecl)
18593 New->setAccess(PrevDecl->getAccess());
18594
18595 DeclContext *DC = New->getDeclContext()->getRedeclContext();
18597 if (Name) // can be null along some error paths
18598 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18599 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
18600 } else if (Name) {
18601 S = getNonFieldDeclScope(S);
18602 PushOnScopeChains(New, S, true);
18603 } else {
18604 CurContext->addDecl(New);
18605 }
18606
18607 // If this is the C FILE type, notify the AST context.
18608 if (IdentifierInfo *II = New->getIdentifier())
18609 if (!New->isInvalidDecl() &&
18610 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
18611 II->isStr("FILE"))
18612 Context.setFILEDecl(New);
18613
18614 if (PrevDecl)
18615 mergeDeclAttributes(New, PrevDecl);
18616
18617 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) {
18620 }
18621
18622 // If there's a #pragma GCC visibility in scope, set the visibility of this
18623 // record.
18625
18626 // If this is not a definition, process API notes for it now.
18627 if (TUK != TagUseKind::Definition)
18629
18630 if (isMemberSpecialization && !New->isInvalidDecl())
18632
18633 OwnedDecl = true;
18634 // In C++, don't return an invalid declaration. We can't recover well from
18635 // the cases where we make the type anonymous.
18636 if (Invalid && getLangOpts().CPlusPlus) {
18637 if (New->isBeingDefined())
18638 if (auto RD = dyn_cast<RecordDecl>(New))
18639 RD->completeDefinition();
18640 return true;
18641 } else if (SkipBody && SkipBody->ShouldSkip) {
18642 return SkipBody->Previous;
18643 } else {
18644 return New;
18645 }
18646}
18647
18650 TagDecl *Tag = cast<TagDecl>(TagD);
18651
18652 // Enter the tag context.
18653 PushDeclContext(S, Tag);
18654
18656
18657 // If there's a #pragma GCC visibility in scope, set the visibility of this
18658 // record.
18660}
18661
18663 SkipBodyInfo &SkipBody) {
18664 if (!hasStructuralCompatLayout(Prev, SkipBody.New))
18665 return false;
18666
18667 // Make the previous decl visible.
18669 CleanupMergedEnum(S, SkipBody.New);
18670 return true;
18671}
18672
18674 Scope *S, Decl *TagD, SourceLocation FinalLoc, bool IsFinalSpelledSealed,
18675 bool IsAbstract, SourceLocation TriviallyRelocatable,
18676 SourceLocation Replaceable, SourceLocation LBraceLoc) {
18679
18680 FieldCollector->StartClass();
18681
18682 if (!Record->getIdentifier())
18683 return;
18684
18685 if (IsAbstract)
18686 Record->markAbstract();
18687
18688 if (FinalLoc.isValid()) {
18689 Record->addAttr(FinalAttr::Create(Context, FinalLoc,
18690 IsFinalSpelledSealed
18691 ? FinalAttr::Keyword_sealed
18692 : FinalAttr::Keyword_final));
18693 }
18694
18695 if (TriviallyRelocatable.isValid())
18696 Record->addAttr(
18697 TriviallyRelocatableAttr::Create(Context, TriviallyRelocatable));
18698
18699 if (Replaceable.isValid())
18700 Record->addAttr(ReplaceableAttr::Create(Context, Replaceable));
18701
18702 // C++ [class]p2:
18703 // [...] The class-name is also inserted into the scope of the
18704 // class itself; this is known as the injected-class-name. For
18705 // purposes of access checking, the injected-class-name is treated
18706 // as if it were a public member name.
18707 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
18708 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
18709 Record->getLocation(), Record->getIdentifier());
18710 InjectedClassName->setImplicit();
18711 InjectedClassName->setAccess(AS_public);
18712 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
18713 InjectedClassName->setDescribedClassTemplate(Template);
18714
18715 PushOnScopeChains(InjectedClassName, S);
18716 assert(InjectedClassName->isInjectedClassName() &&
18717 "Broken injected-class-name");
18718}
18719
18721 SourceRange BraceRange) {
18723 TagDecl *Tag = cast<TagDecl>(TagD);
18724 Tag->setBraceRange(BraceRange);
18725
18726 // Make sure we "complete" the definition even it is invalid.
18727 if (Tag->isBeingDefined()) {
18728 assert(Tag->isInvalidDecl() && "We should already have completed it");
18729 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
18730 RD->completeDefinition();
18731 }
18732
18733 if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
18734 FieldCollector->FinishClass();
18735 if (RD->hasAttr<SYCLSpecialClassAttr>()) {
18736 auto *Def = RD->getDefinition();
18737 assert(Def && "The record is expected to have a completed definition");
18738 unsigned NumInitMethods = 0;
18739 for (auto *Method : Def->methods()) {
18740 if (!Method->getIdentifier())
18741 continue;
18742 if (Method->getName() == "__init")
18743 NumInitMethods++;
18744 }
18745 if (NumInitMethods > 1 || !Def->hasInitMethod())
18746 Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
18747 }
18748
18749 // If we're defining a dynamic class in a module interface unit, we always
18750 // need to produce the vtable for it, even if the vtable is not used in the
18751 // current TU.
18752 //
18753 // The case where the current class is not dynamic is handled in
18754 // MarkVTableUsed.
18755 if (getCurrentModule() && getCurrentModule()->isInterfaceOrPartition())
18756 MarkVTableUsed(RD->getLocation(), RD, /*DefinitionRequired=*/true);
18757 }
18758
18759 // Exit this scope of this tag's definition.
18761
18762 if (getCurLexicalContext()->isObjCContainer() &&
18763 Tag->getDeclContext()->isFileContext())
18764 Tag->setTopLevelDeclInObjCContainer();
18765
18766 // Notify the consumer that we've defined a tag.
18767 if (!Tag->isInvalidDecl())
18768 Consumer.HandleTagDeclDefinition(Tag);
18769
18770 // Clangs implementation of #pragma align(packed) differs in bitfield layout
18771 // from XLs and instead matches the XL #pragma pack(1) behavior.
18772 if (Context.getTargetInfo().getTriple().isOSAIX() &&
18773 AlignPackStack.hasValue()) {
18774 AlignPackInfo APInfo = AlignPackStack.CurrentValue;
18775 // Only diagnose #pragma align(packed).
18776 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
18777 return;
18778 const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
18779 if (!RD)
18780 return;
18781 // Only warn if there is at least 1 bitfield member.
18782 if (llvm::any_of(RD->fields(),
18783 [](const FieldDecl *FD) { return FD->isBitField(); }))
18784 Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
18785 }
18786}
18787
18790 TagDecl *Tag = cast<TagDecl>(TagD);
18791 Tag->setInvalidDecl();
18792
18793 // Make sure we "complete" the definition even it is invalid.
18794 if (Tag->isBeingDefined()) {
18795 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
18796 RD->completeDefinition();
18797 }
18798
18799 // We're undoing ActOnTagStartDefinition here, not
18800 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
18801 // the FieldCollector.
18802
18804}
18805
18806// Note that FieldName may be null for anonymous bitfields.
18808 const IdentifierInfo *FieldName,
18809 QualType FieldTy, bool IsMsStruct,
18810 Expr *BitWidth) {
18811 assert(BitWidth);
18812 if (BitWidth->containsErrors())
18813 return ExprError();
18814
18815 // C99 6.7.2.1p4 - verify the field type.
18816 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
18817 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
18818 // Handle incomplete and sizeless types with a specific error.
18819 if (RequireCompleteSizedType(FieldLoc, FieldTy,
18820 diag::err_field_incomplete_or_sizeless))
18821 return ExprError();
18822 if (FieldName)
18823 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
18824 << FieldName << FieldTy << BitWidth->getSourceRange();
18825 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
18826 << FieldTy << BitWidth->getSourceRange();
18828 return ExprError();
18829
18830 // If the bit-width is type- or value-dependent, don't try to check
18831 // it now.
18832 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
18833 return BitWidth;
18834
18835 llvm::APSInt Value;
18836 ExprResult ICE =
18838 if (ICE.isInvalid())
18839 return ICE;
18840 BitWidth = ICE.get();
18841
18842 // Zero-width bitfield is ok for anonymous field.
18843 if (Value == 0 && FieldName)
18844 return Diag(FieldLoc, diag::err_bitfield_has_zero_width)
18845 << FieldName << BitWidth->getSourceRange();
18846
18847 if (Value.isSigned() && Value.isNegative()) {
18848 if (FieldName)
18849 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
18850 << FieldName << toString(Value, 10);
18851 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
18852 << toString(Value, 10);
18853 }
18854
18855 // The size of the bit-field must not exceed our maximum permitted object
18856 // size.
18857 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
18858 return Diag(FieldLoc, diag::err_bitfield_too_wide)
18859 << !FieldName << FieldName << toString(Value, 10);
18860 }
18861
18862 if (!FieldTy->isDependentType()) {
18863 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
18864 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
18865 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
18866
18867 // Over-wide bitfields are an error in C or when using the MSVC bitfield
18868 // ABI.
18869 bool CStdConstraintViolation =
18870 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
18871 bool MSBitfieldViolation =
18872 Value.ugt(TypeStorageSize) &&
18873 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
18874 if (CStdConstraintViolation || MSBitfieldViolation) {
18875 unsigned DiagWidth =
18876 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
18877 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
18878 << (bool)FieldName << FieldName << toString(Value, 10)
18879 << !CStdConstraintViolation << DiagWidth;
18880 }
18881
18882 // Warn on types where the user might conceivably expect to get all
18883 // specified bits as value bits: that's all integral types other than
18884 // 'bool'.
18885 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
18886 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
18887 << FieldName << toString(Value, 10)
18888 << (unsigned)TypeWidth;
18889 }
18890 }
18891
18892 if (isa<ConstantExpr>(BitWidth))
18893 return BitWidth;
18894 return ConstantExpr::Create(getASTContext(), BitWidth, APValue{Value});
18895}
18896
18898 Declarator &D, Expr *BitfieldWidth) {
18899 FieldDecl *Res = HandleField(S, cast_if_present<RecordDecl>(TagD), DeclStart,
18900 D, BitfieldWidth,
18901 /*InitStyle=*/ICIS_NoInit, AS_public);
18902 return Res;
18903}
18904
18906 SourceLocation DeclStart,
18907 Declarator &D, Expr *BitWidth,
18908 InClassInitStyle InitStyle,
18909 AccessSpecifier AS) {
18910 if (D.isDecompositionDeclarator()) {
18912 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
18913 << Decomp.getSourceRange();
18914 return nullptr;
18915 }
18916
18917 const IdentifierInfo *II = D.getIdentifier();
18918 SourceLocation Loc = DeclStart;
18919 if (II) Loc = D.getIdentifierLoc();
18920
18922 QualType T = TInfo->getType();
18923 if (getLangOpts().CPlusPlus) {
18925
18928 D.setInvalidType();
18929 T = Context.IntTy;
18930 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
18931 }
18932 }
18933
18935
18937 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
18938 << getLangOpts().CPlusPlus17;
18941 diag::err_invalid_thread)
18943
18944 // Check to see if this name was declared as a member previously
18945 NamedDecl *PrevDecl = nullptr;
18946 LookupResult Previous(*this, II, Loc, LookupMemberName,
18948 LookupName(Previous, S);
18949 switch (Previous.getResultKind()) {
18952 PrevDecl = Previous.getAsSingle<NamedDecl>();
18953 break;
18954
18956 PrevDecl = Previous.getRepresentativeDecl();
18957 break;
18958
18962 break;
18963 }
18964 Previous.suppressDiagnostics();
18965
18966 if (PrevDecl && PrevDecl->isTemplateParameter()) {
18967 // Maybe we will complain about the shadowed template parameter.
18969 // Just pretend that we didn't see the previous declaration.
18970 PrevDecl = nullptr;
18971 }
18972
18973 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
18974 PrevDecl = nullptr;
18975
18976 bool Mutable
18977 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
18978 SourceLocation TSSL = D.getBeginLoc();
18979 FieldDecl *NewFD
18980 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
18981 TSSL, AS, PrevDecl, &D);
18982
18983 if (NewFD->isInvalidDecl())
18984 Record->setInvalidDecl();
18985
18987 NewFD->setModulePrivate();
18988
18989 if (NewFD->isInvalidDecl() && PrevDecl) {
18990 // Don't introduce NewFD into scope; there's already something
18991 // with the same name in the same scope.
18992 } else if (II) {
18993 PushOnScopeChains(NewFD, S);
18994 } else
18995 Record->addDecl(NewFD);
18996
18997 return NewFD;
18998}
18999
19001 TypeSourceInfo *TInfo,
19003 bool Mutable, Expr *BitWidth,
19004 InClassInitStyle InitStyle,
19005 SourceLocation TSSL,
19006 AccessSpecifier AS, NamedDecl *PrevDecl,
19007 Declarator *D) {
19008 const IdentifierInfo *II = Name.getAsIdentifierInfo();
19009 bool InvalidDecl = false;
19010 if (D) InvalidDecl = D->isInvalidType();
19011
19012 // If we receive a broken type, recover by assuming 'int' and
19013 // marking this declaration as invalid.
19014 if (T.isNull() || T->containsErrors()) {
19015 InvalidDecl = true;
19016 T = Context.IntTy;
19017 }
19018
19019 QualType EltTy = Context.getBaseElementType(T);
19020 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
19021 bool isIncomplete =
19022 LangOpts.HLSL // HLSL allows sizeless builtin types
19023 ? RequireCompleteType(Loc, EltTy, diag::err_incomplete_type)
19024 : RequireCompleteSizedType(Loc, EltTy,
19025 diag::err_field_incomplete_or_sizeless);
19026 if (isIncomplete) {
19027 // Fields of incomplete type force their record to be invalid.
19028 Record->setInvalidDecl();
19029 InvalidDecl = true;
19030 } else {
19031 NamedDecl *Def;
19032 EltTy->isIncompleteType(&Def);
19033 if (Def && Def->isInvalidDecl()) {
19034 Record->setInvalidDecl();
19035 InvalidDecl = true;
19036 }
19037 }
19038 }
19039
19040 // TR 18037 does not allow fields to be declared with address space
19041 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
19042 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
19043 Diag(Loc, diag::err_field_with_address_space);
19044 Record->setInvalidDecl();
19045 InvalidDecl = true;
19046 }
19047
19048 if (LangOpts.OpenCL) {
19049 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
19050 // used as structure or union field: image, sampler, event or block types.
19051 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
19052 T->isBlockPointerType()) {
19053 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
19054 Record->setInvalidDecl();
19055 InvalidDecl = true;
19056 }
19057 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
19058 // is enabled.
19059 if (BitWidth && !getOpenCLOptions().isAvailableOption(
19060 "__cl_clang_bitfields", LangOpts)) {
19061 Diag(Loc, diag::err_opencl_bitfields);
19062 InvalidDecl = true;
19063 }
19064 }
19065
19066 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
19067 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
19068 T.hasQualifiers()) {
19069 InvalidDecl = true;
19070 Diag(Loc, diag::err_anon_bitfield_qualifiers);
19071 }
19072
19073 // C99 6.7.2.1p8: A member of a structure or union may have any type other
19074 // than a variably modified type.
19075 if (!InvalidDecl && T->isVariablyModifiedType()) {
19077 TInfo, T, Loc, diag::err_typecheck_field_variable_size))
19078 InvalidDecl = true;
19079 }
19080
19081 // Fields can not have abstract class types
19082 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
19083 diag::err_abstract_type_in_decl,
19085 InvalidDecl = true;
19086
19087 if (InvalidDecl)
19088 BitWidth = nullptr;
19089 // If this is declared as a bit-field, check the bit-field.
19090 if (BitWidth) {
19091 BitWidth =
19092 VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get();
19093 if (!BitWidth) {
19094 InvalidDecl = true;
19095 BitWidth = nullptr;
19096 }
19097 }
19098
19099 // Check that 'mutable' is consistent with the type of the declaration.
19100 if (!InvalidDecl && Mutable) {
19101 unsigned DiagID = 0;
19102 if (T->isReferenceType())
19103 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
19104 : diag::err_mutable_reference;
19105 else if (T.isConstQualified())
19106 DiagID = diag::err_mutable_const;
19107
19108 if (DiagID) {
19109 SourceLocation ErrLoc = Loc;
19110 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
19111 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
19112 Diag(ErrLoc, DiagID);
19113 if (DiagID != diag::ext_mutable_reference) {
19114 Mutable = false;
19115 InvalidDecl = true;
19116 }
19117 }
19118 }
19119
19120 // C++11 [class.union]p8 (DR1460):
19121 // At most one variant member of a union may have a
19122 // brace-or-equal-initializer.
19123 if (InitStyle != ICIS_NoInit)
19125
19126 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
19127 BitWidth, Mutable, InitStyle);
19128 if (InvalidDecl)
19129 NewFD->setInvalidDecl();
19130
19131 if (!InvalidDecl)
19133
19134 if (PrevDecl && !isa<TagDecl>(PrevDecl) &&
19135 !PrevDecl->isPlaceholderVar(getLangOpts())) {
19136 Diag(Loc, diag::err_duplicate_member) << II;
19137 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
19138 NewFD->setInvalidDecl();
19139 }
19140
19141 if (!InvalidDecl && getLangOpts().CPlusPlus) {
19142 if (Record->isUnion()) {
19143 if (const auto *RD = EltTy->getAsCXXRecordDecl();
19144 RD && (RD->isBeingDefined() || RD->isCompleteDefinition())) {
19145
19146 // C++ [class.union]p1: An object of a class with a non-trivial
19147 // constructor, a non-trivial copy constructor, a non-trivial
19148 // destructor, or a non-trivial copy assignment operator
19149 // cannot be a member of a union, nor can an array of such
19150 // objects.
19151 if (CheckNontrivialField(NewFD))
19152 NewFD->setInvalidDecl();
19153 }
19154
19155 // C++ [class.union]p1: If a union contains a member of reference type,
19156 // the program is ill-formed, except when compiling with MSVC extensions
19157 // enabled.
19158 if (EltTy->isReferenceType()) {
19159 const bool HaveMSExt =
19160 getLangOpts().MicrosoftExt &&
19162
19163 Diag(NewFD->getLocation(),
19164 HaveMSExt ? diag::ext_union_member_of_reference_type
19165 : diag::err_union_member_of_reference_type)
19166 << NewFD->getDeclName() << EltTy;
19167 if (!HaveMSExt)
19168 NewFD->setInvalidDecl();
19169 }
19170 }
19171 }
19172
19173 // FIXME: We need to pass in the attributes given an AST
19174 // representation, not a parser representation.
19175 if (D) {
19176 // FIXME: The current scope is almost... but not entirely... correct here.
19177 ProcessDeclAttributes(getCurScope(), NewFD, *D);
19178
19179 if (NewFD->hasAttrs())
19181 }
19182
19183 // In auto-retain/release, infer strong retension for fields of
19184 // retainable type.
19185 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewFD))
19186 NewFD->setInvalidDecl();
19187
19188 if (T.isObjCGCWeak())
19189 Diag(Loc, diag::warn_attribute_weak_on_field);
19190
19191 // PPC MMA non-pointer types are not allowed as field types.
19192 if (Context.getTargetInfo().getTriple().isPPC64() &&
19193 PPC().CheckPPCMMAType(T, NewFD->getLocation()))
19194 NewFD->setInvalidDecl();
19195
19196 NewFD->setAccess(AS);
19197 return NewFD;
19198}
19199
19201 assert(FD);
19202 assert(getLangOpts().CPlusPlus && "valid check only for C++");
19203
19204 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
19205 return false;
19206
19207 QualType EltTy = Context.getBaseElementType(FD->getType());
19208 if (const auto *RDecl = EltTy->getAsCXXRecordDecl();
19209 RDecl && (RDecl->isBeingDefined() || RDecl->isCompleteDefinition())) {
19210 // We check for copy constructors before constructors
19211 // because otherwise we'll never get complaints about
19212 // copy constructors.
19213
19215 // We're required to check for any non-trivial constructors. Since the
19216 // implicit default constructor is suppressed if there are any
19217 // user-declared constructors, we just need to check that there is a
19218 // trivial default constructor and a trivial copy constructor. (We don't
19219 // worry about move constructors here, since this is a C++98 check.)
19220 if (RDecl->hasNonTrivialCopyConstructor())
19222 else if (!RDecl->hasTrivialDefaultConstructor())
19224 else if (RDecl->hasNonTrivialCopyAssignment())
19226 else if (RDecl->hasNonTrivialDestructor())
19228
19229 if (member != CXXSpecialMemberKind::Invalid) {
19230 if (!getLangOpts().CPlusPlus11 && getLangOpts().ObjCAutoRefCount &&
19231 RDecl->hasObjectMember()) {
19232 // Objective-C++ ARC: it is an error to have a non-trivial field of
19233 // a union. However, system headers in Objective-C programs
19234 // occasionally have Objective-C lifetime objects within unions,
19235 // and rather than cause the program to fail, we make those
19236 // members unavailable.
19237 SourceLocation Loc = FD->getLocation();
19238 if (getSourceManager().isInSystemHeader(Loc)) {
19239 if (!FD->hasAttr<UnavailableAttr>())
19240 FD->addAttr(UnavailableAttr::CreateImplicit(
19241 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
19242 return false;
19243 }
19244 }
19245
19246 Diag(FD->getLocation(),
19248 ? diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member
19249 : diag::err_illegal_union_or_anon_struct_member)
19250 << FD->getParent()->isUnion() << FD->getDeclName() << member;
19251 DiagnoseNontrivial(RDecl, member);
19252 return !getLangOpts().CPlusPlus11;
19253 }
19254 }
19255
19256 return false;
19257}
19258
19260 SmallVectorImpl<Decl *> &AllIvarDecls) {
19261 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
19262 return;
19263
19264 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
19265 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
19266
19267 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField())
19268 return;
19269 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
19270 if (!ID) {
19271 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
19272 if (!CD->IsClassExtension())
19273 return;
19274 }
19275 // No need to add this to end of @implementation.
19276 else
19277 return;
19278 }
19279 // All conditions are met. Add a new bitfield to the tail end of ivars.
19280 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
19281 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
19282 Expr *BitWidth =
19283 ConstantExpr::Create(Context, BW, APValue(llvm::APSInt(Zero)));
19284
19285 Ivar = ObjCIvarDecl::Create(
19286 Context, cast<ObjCContainerDecl>(CurContext), DeclLoc, DeclLoc, nullptr,
19287 Context.CharTy, Context.getTrivialTypeSourceInfo(Context.CharTy, DeclLoc),
19288 ObjCIvarDecl::Private, BitWidth, true);
19289 AllIvarDecls.push_back(Ivar);
19290}
19291
19292/// [class.dtor]p4:
19293/// At the end of the definition of a class, overload resolution is
19294/// performed among the prospective destructors declared in that class with
19295/// an empty argument list to select the destructor for the class, also
19296/// known as the selected destructor.
19297///
19298/// We do the overload resolution here, then mark the selected constructor in the AST.
19299/// Later CXXRecordDecl::getDestructor() will return the selected constructor.
19301 if (!Record->hasUserDeclaredDestructor()) {
19302 return;
19303 }
19304
19305 SourceLocation Loc = Record->getLocation();
19307
19308 for (auto *Decl : Record->decls()) {
19309 if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {
19310 if (DD->isInvalidDecl())
19311 continue;
19312 S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},
19313 OCS);
19314 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
19315 }
19316 }
19317
19318 if (OCS.empty()) {
19319 return;
19320 }
19322 unsigned Msg = 0;
19323 OverloadCandidateDisplayKind DisplayKind;
19324
19325 switch (OCS.BestViableFunction(S, Loc, Best)) {
19326 case OR_Success:
19327 case OR_Deleted:
19328 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function));
19329 break;
19330
19331 case OR_Ambiguous:
19332 Msg = diag::err_ambiguous_destructor;
19333 DisplayKind = OCD_AmbiguousCandidates;
19334 break;
19335
19337 Msg = diag::err_no_viable_destructor;
19338 DisplayKind = OCD_AllCandidates;
19339 break;
19340 }
19341
19342 if (Msg) {
19343 // OpenCL have got their own thing going with destructors. It's slightly broken,
19344 // but we allow it.
19345 if (!S.LangOpts.OpenCL) {
19346 PartialDiagnostic Diag = S.PDiag(Msg) << Record;
19347 OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {});
19348 Record->setInvalidDecl();
19349 }
19350 // It's a bit hacky: At this point we've raised an error but we want the
19351 // rest of the compiler to continue somehow working. However almost
19352 // everything we'll try to do with the class will depend on there being a
19353 // destructor. So let's pretend the first one is selected and hope for the
19354 // best.
19355 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function));
19356 }
19357}
19358
19359/// [class.mem.special]p5
19360/// Two special member functions are of the same kind if:
19361/// - they are both default constructors,
19362/// - they are both copy or move constructors with the same first parameter
19363/// type, or
19364/// - they are both copy or move assignment operators with the same first
19365/// parameter type and the same cv-qualifiers and ref-qualifier, if any.
19367 CXXMethodDecl *M1,
19368 CXXMethodDecl *M2,
19370 // We don't want to compare templates to non-templates: See
19371 // https://github.com/llvm/llvm-project/issues/59206
19373 return bool(M1->getDescribedFunctionTemplate()) ==
19375 // FIXME: better resolve CWG
19376 // https://cplusplus.github.io/CWG/issues/2787.html
19377 if (!Context.hasSameType(M1->getNonObjectParameter(0)->getType(),
19378 M2->getNonObjectParameter(0)->getType()))
19379 return false;
19380 if (!Context.hasSameType(M1->getFunctionObjectParameterReferenceType(),
19382 return false;
19383
19384 return true;
19385}
19386
19387/// [class.mem.special]p6:
19388/// An eligible special member function is a special member function for which:
19389/// - the function is not deleted,
19390/// - the associated constraints, if any, are satisfied, and
19391/// - no special member function of the same kind whose associated constraints
19392/// [CWG2595], if any, are satisfied is more constrained.
19396 SmallVector<bool, 4> SatisfactionStatus;
19397
19398 for (CXXMethodDecl *Method : Methods) {
19399 if (!Method->getTrailingRequiresClause())
19400 SatisfactionStatus.push_back(true);
19401 else {
19402 ConstraintSatisfaction Satisfaction;
19403 if (S.CheckFunctionConstraints(Method, Satisfaction))
19404 SatisfactionStatus.push_back(false);
19405 else
19406 SatisfactionStatus.push_back(Satisfaction.IsSatisfied);
19407 }
19408 }
19409
19410 for (size_t i = 0; i < Methods.size(); i++) {
19411 if (!SatisfactionStatus[i])
19412 continue;
19413 CXXMethodDecl *Method = Methods[i];
19414 CXXMethodDecl *OrigMethod = Method;
19415 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
19416 OrigMethod = cast<CXXMethodDecl>(MF);
19417
19419 bool AnotherMethodIsMoreConstrained = false;
19420 for (size_t j = 0; j < Methods.size(); j++) {
19421 if (i == j || !SatisfactionStatus[j])
19422 continue;
19423 CXXMethodDecl *OtherMethod = Methods[j];
19424 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
19425 OtherMethod = cast<CXXMethodDecl>(MF);
19426
19427 if (!AreSpecialMemberFunctionsSameKind(S.Context, OrigMethod, OtherMethod,
19428 CSM))
19429 continue;
19430
19432 if (!Other)
19433 continue;
19434 if (!Orig) {
19435 AnotherMethodIsMoreConstrained = true;
19436 break;
19437 }
19438 if (S.IsAtLeastAsConstrained(OtherMethod, {Other}, OrigMethod, {Orig},
19439 AnotherMethodIsMoreConstrained)) {
19440 // There was an error with the constraints comparison. Exit the loop
19441 // and don't consider this function eligible.
19442 AnotherMethodIsMoreConstrained = true;
19443 }
19444 if (AnotherMethodIsMoreConstrained)
19445 break;
19446 }
19447 // FIXME: Do not consider deleted methods as eligible after implementing
19448 // DR1734 and DR1496.
19449 if (!AnotherMethodIsMoreConstrained) {
19450 Method->setIneligibleOrNotSelected(false);
19451 Record->addedEligibleSpecialMemberFunction(Method,
19452 1 << llvm::to_underlying(CSM));
19453 }
19454 }
19455}
19456
19459 SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
19460 SmallVector<CXXMethodDecl *, 4> CopyConstructors;
19461 SmallVector<CXXMethodDecl *, 4> MoveConstructors;
19462 SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
19463 SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
19464
19465 for (auto *Decl : Record->decls()) {
19466 auto *MD = dyn_cast<CXXMethodDecl>(Decl);
19467 if (!MD) {
19468 auto *FTD = dyn_cast<FunctionTemplateDecl>(Decl);
19469 if (FTD)
19470 MD = dyn_cast<CXXMethodDecl>(FTD->getTemplatedDecl());
19471 }
19472 if (!MD)
19473 continue;
19474 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
19475 if (CD->isInvalidDecl())
19476 continue;
19477 if (CD->isDefaultConstructor())
19478 DefaultConstructors.push_back(MD);
19479 else if (CD->isCopyConstructor())
19480 CopyConstructors.push_back(MD);
19481 else if (CD->isMoveConstructor())
19482 MoveConstructors.push_back(MD);
19483 } else if (MD->isCopyAssignmentOperator()) {
19484 CopyAssignmentOperators.push_back(MD);
19485 } else if (MD->isMoveAssignmentOperator()) {
19486 MoveAssignmentOperators.push_back(MD);
19487 }
19488 }
19489
19490 SetEligibleMethods(S, Record, DefaultConstructors,
19492 SetEligibleMethods(S, Record, CopyConstructors,
19494 SetEligibleMethods(S, Record, MoveConstructors,
19496 SetEligibleMethods(S, Record, CopyAssignmentOperators,
19498 SetEligibleMethods(S, Record, MoveAssignmentOperators,
19500}
19501
19502bool Sema::EntirelyFunctionPointers(const RecordDecl *Record) {
19503 // Check to see if a FieldDecl is a pointer to a function.
19504 auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
19505 const FieldDecl *FD = dyn_cast<FieldDecl>(D);
19506 if (!FD) {
19507 // Check whether this is a forward declaration that was inserted by
19508 // Clang. This happens when a non-forward declared / defined type is
19509 // used, e.g.:
19510 //
19511 // struct foo {
19512 // struct bar *(*f)();
19513 // struct bar *(*g)();
19514 // };
19515 //
19516 // "struct bar" shows up in the decl AST as a "RecordDecl" with an
19517 // incomplete definition.
19518 if (const auto *TD = dyn_cast<TagDecl>(D))
19519 return !TD->isCompleteDefinition();
19520 return false;
19521 }
19522 QualType FieldType = FD->getType().getDesugaredType(Context);
19523 if (isa<PointerType>(FieldType)) {
19524 QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();
19525 return PointeeType.getDesugaredType(Context)->isFunctionType();
19526 }
19527 // If a member is a struct entirely of function pointers, that counts too.
19528 if (const auto *Record = FieldType->getAsRecordDecl();
19529 Record && Record->isStruct() && EntirelyFunctionPointers(Record))
19530 return true;
19531 return false;
19532 };
19533
19534 return llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl);
19535}
19536
19537void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
19538 ArrayRef<Decl *> Fields, SourceLocation LBrac,
19539 SourceLocation RBrac,
19540 const ParsedAttributesView &Attrs) {
19541 assert(EnclosingDecl && "missing record or interface decl");
19542
19543 // If this is an Objective-C @implementation or category and we have
19544 // new fields here we should reset the layout of the interface since
19545 // it will now change.
19546 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
19547 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
19548 switch (DC->getKind()) {
19549 default: break;
19550 case Decl::ObjCCategory:
19551 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
19552 break;
19553 case Decl::ObjCImplementation:
19554 Context.
19555 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
19556 break;
19557 }
19558 }
19559
19560 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
19561 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
19562
19563 // Start counting up the number of named members; make sure to include
19564 // members of anonymous structs and unions in the total.
19565 unsigned NumNamedMembers = 0;
19566 if (Record) {
19567 for (const auto *I : Record->decls()) {
19568 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
19569 if (IFD->getDeclName())
19570 ++NumNamedMembers;
19571 }
19572 }
19573
19574 // Verify that all the fields are okay.
19576 const FieldDecl *PreviousField = nullptr;
19577 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
19578 i != end; PreviousField = cast<FieldDecl>(*i), ++i) {
19579 FieldDecl *FD = cast<FieldDecl>(*i);
19580
19581 // Get the type for the field.
19582 const Type *FDTy = FD->getType().getTypePtr();
19583
19584 if (!FD->isAnonymousStructOrUnion()) {
19585 // Remember all fields written by the user.
19586 RecFields.push_back(FD);
19587 }
19588
19589 // If the field is already invalid for some reason, don't emit more
19590 // diagnostics about it.
19591 if (FD->isInvalidDecl()) {
19592 EnclosingDecl->setInvalidDecl();
19593 continue;
19594 }
19595
19596 // C99 6.7.2.1p2:
19597 // A structure or union shall not contain a member with
19598 // incomplete or function type (hence, a structure shall not
19599 // contain an instance of itself, but may contain a pointer to
19600 // an instance of itself), except that the last member of a
19601 // structure with more than one named member may have incomplete
19602 // array type; such a structure (and any union containing,
19603 // possibly recursively, a member that is such a structure)
19604 // shall not be a member of a structure or an element of an
19605 // array.
19606 bool IsLastField = (i + 1 == Fields.end());
19607 if (FDTy->isFunctionType()) {
19608 // Field declared as a function.
19609 Diag(FD->getLocation(), diag::err_field_declared_as_function)
19610 << FD->getDeclName();
19611 FD->setInvalidDecl();
19612 EnclosingDecl->setInvalidDecl();
19613 continue;
19614 } else if (FDTy->isIncompleteArrayType() &&
19615 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
19616 if (Record) {
19617 // Flexible array member.
19618 // Microsoft and g++ is more permissive regarding flexible array.
19619 // It will accept flexible array in union and also
19620 // as the sole element of a struct/class.
19621 unsigned DiagID = 0;
19622 if (!Record->isUnion() && !IsLastField) {
19623 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
19624 << FD->getDeclName() << FD->getType() << Record->getTagKind();
19625 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
19626 FD->setInvalidDecl();
19627 EnclosingDecl->setInvalidDecl();
19628 continue;
19629 } else if (Record->isUnion())
19630 DiagID = getLangOpts().MicrosoftExt
19631 ? diag::ext_flexible_array_union_ms
19632 : diag::ext_flexible_array_union_gnu;
19633 else if (NumNamedMembers < 1)
19634 DiagID = getLangOpts().MicrosoftExt
19635 ? diag::ext_flexible_array_empty_aggregate_ms
19636 : diag::ext_flexible_array_empty_aggregate_gnu;
19637
19638 if (DiagID)
19639 Diag(FD->getLocation(), DiagID)
19640 << FD->getDeclName() << Record->getTagKind();
19641 // While the layout of types that contain virtual bases is not specified
19642 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
19643 // virtual bases after the derived members. This would make a flexible
19644 // array member declared at the end of an object not adjacent to the end
19645 // of the type.
19646 if (CXXRecord && CXXRecord->getNumVBases() != 0)
19647 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
19648 << FD->getDeclName() << Record->getTagKind();
19649 if (!getLangOpts().C99)
19650 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
19651 << FD->getDeclName() << Record->getTagKind();
19652
19653 // If the element type has a non-trivial destructor, we would not
19654 // implicitly destroy the elements, so disallow it for now.
19655 //
19656 // FIXME: GCC allows this. We should probably either implicitly delete
19657 // the destructor of the containing class, or just allow this.
19658 QualType BaseElem = Context.getBaseElementType(FD->getType());
19659 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
19660 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
19661 << FD->getDeclName() << FD->getType();
19662 FD->setInvalidDecl();
19663 EnclosingDecl->setInvalidDecl();
19664 continue;
19665 }
19666 // Okay, we have a legal flexible array member at the end of the struct.
19667 Record->setHasFlexibleArrayMember(true);
19668 } else {
19669 // In ObjCContainerDecl ivars with incomplete array type are accepted,
19670 // unless they are followed by another ivar. That check is done
19671 // elsewhere, after synthesized ivars are known.
19672 }
19673 } else if (!FDTy->isDependentType() &&
19674 (LangOpts.HLSL // HLSL allows sizeless builtin types
19676 diag::err_incomplete_type)
19678 FD->getLocation(), FD->getType(),
19679 diag::err_field_incomplete_or_sizeless))) {
19680 // Incomplete type
19681 FD->setInvalidDecl();
19682 EnclosingDecl->setInvalidDecl();
19683 continue;
19684 } else if (const auto *RD = FDTy->getAsRecordDecl()) {
19685 if (Record && RD->hasFlexibleArrayMember()) {
19686 // A type which contains a flexible array member is considered to be a
19687 // flexible array member.
19688 Record->setHasFlexibleArrayMember(true);
19689 if (!Record->isUnion()) {
19690 // If this is a struct/class and this is not the last element, reject
19691 // it. Note that GCC supports variable sized arrays in the middle of
19692 // structures.
19693 if (!IsLastField)
19694 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
19695 << FD->getDeclName() << FD->getType();
19696 else {
19697 // We support flexible arrays at the end of structs in
19698 // other structs as an extension.
19699 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
19700 << FD->getDeclName();
19701 }
19702 }
19703 }
19704 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
19706 diag::err_abstract_type_in_decl,
19708 // Ivars can not have abstract class types
19709 FD->setInvalidDecl();
19710 }
19711 if (Record && RD->hasObjectMember())
19712 Record->setHasObjectMember(true);
19713 if (Record && RD->hasVolatileMember())
19714 Record->setHasVolatileMember(true);
19715 } else if (FDTy->isObjCObjectType()) {
19716 /// A field cannot be an Objective-c object
19717 Diag(FD->getLocation(), diag::err_statically_allocated_object)
19719 QualType T = Context.getObjCObjectPointerType(FD->getType());
19720 FD->setType(T);
19721 } else if (Record && Record->isUnion() &&
19723 getSourceManager().isInSystemHeader(FD->getLocation()) &&
19724 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
19726 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
19727 // For backward compatibility, fields of C unions declared in system
19728 // headers that have non-trivial ObjC ownership qualifications are marked
19729 // as unavailable unless the qualifier is explicit and __strong. This can
19730 // break ABI compatibility between programs compiled with ARC and MRR, but
19731 // is a better option than rejecting programs using those unions under
19732 // ARC.
19733 FD->addAttr(UnavailableAttr::CreateImplicit(
19734 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
19735 FD->getLocation()));
19736 } else if (getLangOpts().ObjC &&
19737 getLangOpts().getGC() != LangOptions::NonGC && Record &&
19738 !Record->hasObjectMember()) {
19739 if (FD->getType()->isObjCObjectPointerType() ||
19740 FD->getType().isObjCGCStrong())
19741 Record->setHasObjectMember(true);
19742 else if (Context.getAsArrayType(FD->getType())) {
19743 QualType BaseType = Context.getBaseElementType(FD->getType());
19744 if (const auto *RD = BaseType->getAsRecordDecl();
19745 RD && RD->hasObjectMember())
19746 Record->setHasObjectMember(true);
19747 else if (BaseType->isObjCObjectPointerType() ||
19748 BaseType.isObjCGCStrong())
19749 Record->setHasObjectMember(true);
19750 }
19751 }
19752
19753 if (Record && !getLangOpts().CPlusPlus &&
19754 !shouldIgnoreForRecordTriviality(FD)) {
19755 QualType FT = FD->getType();
19757 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
19759 Record->isUnion())
19760 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
19761 }
19764 Record->setNonTrivialToPrimitiveCopy(true);
19765 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
19766 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
19767 }
19768 if (FD->hasAttr<ExplicitInitAttr>())
19769 Record->setHasUninitializedExplicitInitFields(true);
19770 if (FT.isDestructedType()) {
19771 Record->setNonTrivialToPrimitiveDestroy(true);
19772 Record->setParamDestroyedInCallee(true);
19773 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
19774 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
19775 }
19776
19777 if (const auto *RD = FT->getAsRecordDecl()) {
19778 if (RD->getArgPassingRestrictions() ==
19780 Record->setArgPassingRestrictions(
19782 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) {
19783 Record->setArgPassingRestrictions(
19785 } else if (PointerAuthQualifier Q = FT.getPointerAuth();
19786 Q && Q.isAddressDiscriminated()) {
19787 Record->setArgPassingRestrictions(
19789 Record->setNonTrivialToPrimitiveCopy(true);
19790 }
19791 }
19792
19793 if (Record && FD->getType().isVolatileQualified())
19794 Record->setHasVolatileMember(true);
19795 bool ReportMSBitfieldStoragePacking =
19796 Record && PreviousField &&
19797 !Diags.isIgnored(diag::warn_ms_bitfield_mismatched_storage_packing,
19798 Record->getLocation());
19799 auto IsNonDependentBitField = [](const FieldDecl *FD) {
19800 return FD->isBitField() && !FD->getType()->isDependentType();
19801 };
19802
19803 if (ReportMSBitfieldStoragePacking && IsNonDependentBitField(FD) &&
19804 IsNonDependentBitField(PreviousField)) {
19805 CharUnits FDStorageSize = Context.getTypeSizeInChars(FD->getType());
19806 CharUnits PreviousFieldStorageSize =
19807 Context.getTypeSizeInChars(PreviousField->getType());
19808 if (FDStorageSize != PreviousFieldStorageSize) {
19809 Diag(FD->getLocation(),
19810 diag::warn_ms_bitfield_mismatched_storage_packing)
19811 << FD << FD->getType() << FDStorageSize.getQuantity()
19812 << PreviousFieldStorageSize.getQuantity();
19813 Diag(PreviousField->getLocation(),
19814 diag::note_ms_bitfield_mismatched_storage_size_previous)
19815 << PreviousField << PreviousField->getType();
19816 }
19817 }
19818 // Keep track of the number of named members.
19819 if (FD->getIdentifier())
19820 ++NumNamedMembers;
19821 }
19822
19823 // Okay, we successfully defined 'Record'.
19824 if (Record) {
19825 bool Completed = false;
19826 if (S) {
19827 Scope *Parent = S->getParent();
19828 if (Parent && Parent->isTypeAliasScope() &&
19829 Parent->isTemplateParamScope())
19830 Record->setInvalidDecl();
19831 }
19832
19833 if (CXXRecord) {
19834 if (!CXXRecord->isInvalidDecl()) {
19835 // Set access bits correctly on the directly-declared conversions.
19837 I = CXXRecord->conversion_begin(),
19838 E = CXXRecord->conversion_end(); I != E; ++I)
19839 I.setAccess((*I)->getAccess());
19840 }
19841
19842 // Add any implicitly-declared members to this class.
19844
19845 if (!CXXRecord->isDependentType()) {
19846 if (!CXXRecord->isInvalidDecl()) {
19847 // If we have virtual base classes, we may end up finding multiple
19848 // final overriders for a given virtual function. Check for this
19849 // problem now.
19850 if (CXXRecord->getNumVBases()) {
19851 CXXFinalOverriderMap FinalOverriders;
19852 CXXRecord->getFinalOverriders(FinalOverriders);
19853
19854 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
19855 MEnd = FinalOverriders.end();
19856 M != MEnd; ++M) {
19857 for (OverridingMethods::iterator SO = M->second.begin(),
19858 SOEnd = M->second.end();
19859 SO != SOEnd; ++SO) {
19860 assert(SO->second.size() > 0 &&
19861 "Virtual function without overriding functions?");
19862 if (SO->second.size() == 1)
19863 continue;
19864
19865 // C++ [class.virtual]p2:
19866 // In a derived class, if a virtual member function of a base
19867 // class subobject has more than one final overrider the
19868 // program is ill-formed.
19869 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
19870 << (const NamedDecl *)M->first << Record;
19871 Diag(M->first->getLocation(),
19872 diag::note_overridden_virtual_function);
19874 OM = SO->second.begin(),
19875 OMEnd = SO->second.end();
19876 OM != OMEnd; ++OM)
19877 Diag(OM->Method->getLocation(), diag::note_final_overrider)
19878 << (const NamedDecl *)M->first << OM->Method->getParent();
19879
19880 Record->setInvalidDecl();
19881 }
19882 }
19883 CXXRecord->completeDefinition(&FinalOverriders);
19884 Completed = true;
19885 }
19886 }
19887 ComputeSelectedDestructor(*this, CXXRecord);
19889 }
19890 }
19891
19892 if (!Completed)
19893 Record->completeDefinition();
19894
19895 // Handle attributes before checking the layout.
19897
19898 // Maybe randomize the record's decls. We automatically randomize a record
19899 // of function pointers, unless it has the "no_randomize_layout" attribute.
19900 if (!getLangOpts().CPlusPlus && !getLangOpts().RandstructSeed.empty() &&
19901 !Record->isRandomized() && !Record->isUnion() &&
19902 (Record->hasAttr<RandomizeLayoutAttr>() ||
19903 (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
19904 EntirelyFunctionPointers(Record)))) {
19905 SmallVector<Decl *, 32> NewDeclOrdering;
19907 NewDeclOrdering))
19908 Record->reorderDecls(NewDeclOrdering);
19909 }
19910
19911 // We may have deferred checking for a deleted destructor. Check now.
19912 if (CXXRecord) {
19913 auto *Dtor = CXXRecord->getDestructor();
19914 if (Dtor && Dtor->isImplicit() &&
19916 CXXRecord->setImplicitDestructorIsDeleted();
19917 SetDeclDeleted(Dtor, CXXRecord->getLocation());
19918 }
19919 }
19920
19921 if (Record->hasAttrs()) {
19923
19924 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
19926 IA->getRange(), IA->getBestCase(),
19927 IA->getInheritanceModel());
19928 }
19929
19930 // Check if the structure/union declaration is a type that can have zero
19931 // size in C. For C this is a language extension, for C++ it may cause
19932 // compatibility problems.
19933 bool CheckForZeroSize;
19934 if (!getLangOpts().CPlusPlus) {
19935 CheckForZeroSize = true;
19936 } else {
19937 // For C++ filter out types that cannot be referenced in C code.
19939 CheckForZeroSize =
19940 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
19941 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
19942 CXXRecord->isCLike();
19943 }
19944 if (CheckForZeroSize) {
19945 bool ZeroSize = true;
19946 bool IsEmpty = true;
19947 unsigned NonBitFields = 0;
19948 for (RecordDecl::field_iterator I = Record->field_begin(),
19949 E = Record->field_end();
19950 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
19951 IsEmpty = false;
19952 if (I->isUnnamedBitField()) {
19953 if (!I->isZeroLengthBitField())
19954 ZeroSize = false;
19955 } else {
19956 ++NonBitFields;
19957 QualType FieldType = I->getType();
19958 if (FieldType->isIncompleteType() ||
19959 !Context.getTypeSizeInChars(FieldType).isZero())
19960 ZeroSize = false;
19961 }
19962 }
19963
19964 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
19965 // allowed in C++, but warn if its declaration is inside
19966 // extern "C" block.
19967 if (ZeroSize) {
19968 Diag(RecLoc, getLangOpts().CPlusPlus ?
19969 diag::warn_zero_size_struct_union_in_extern_c :
19970 diag::warn_zero_size_struct_union_compat)
19971 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
19972 }
19973
19974 // Structs without named members are extension in C (C99 6.7.2.1p7),
19975 // but are accepted by GCC. In C2y, this became implementation-defined
19976 // (C2y 6.7.3.2p10).
19977 if (NonBitFields == 0 && !getLangOpts().CPlusPlus && !getLangOpts().C2y) {
19978 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union
19979 : diag::ext_no_named_members_in_struct_union)
19980 << Record->isUnion();
19981 }
19982 }
19983 } else {
19984 ObjCIvarDecl **ClsFields =
19985 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
19986 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
19987 ID->setEndOfDefinitionLoc(RBrac);
19988 // Add ivar's to class's DeclContext.
19989 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19990 ClsFields[i]->setLexicalDeclContext(ID);
19991 ID->addDecl(ClsFields[i]);
19992 }
19993 // Must enforce the rule that ivars in the base classes may not be
19994 // duplicates.
19995 if (ID->getSuperClass())
19996 ObjC().DiagnoseDuplicateIvars(ID, ID->getSuperClass());
19997 } else if (ObjCImplementationDecl *IMPDecl =
19998 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
19999 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
20000 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
20001 // Ivar declared in @implementation never belongs to the implementation.
20002 // Only it is in implementation's lexical context.
20003 ClsFields[I]->setLexicalDeclContext(IMPDecl);
20004 ObjC().CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(),
20005 RBrac);
20006 IMPDecl->setIvarLBraceLoc(LBrac);
20007 IMPDecl->setIvarRBraceLoc(RBrac);
20008 } else if (ObjCCategoryDecl *CDecl =
20009 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
20010 // case of ivars in class extension; all other cases have been
20011 // reported as errors elsewhere.
20012 // FIXME. Class extension does not have a LocEnd field.
20013 // CDecl->setLocEnd(RBrac);
20014 // Add ivar's to class extension's DeclContext.
20015 // Diagnose redeclaration of private ivars.
20016 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
20017 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
20018 if (IDecl) {
20019 if (const ObjCIvarDecl *ClsIvar =
20020 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
20021 Diag(ClsFields[i]->getLocation(),
20022 diag::err_duplicate_ivar_declaration);
20023 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
20024 continue;
20025 }
20026 for (const auto *Ext : IDecl->known_extensions()) {
20027 if (const ObjCIvarDecl *ClsExtIvar
20028 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
20029 Diag(ClsFields[i]->getLocation(),
20030 diag::err_duplicate_ivar_declaration);
20031 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
20032 continue;
20033 }
20034 }
20035 }
20036 ClsFields[i]->setLexicalDeclContext(CDecl);
20037 CDecl->addDecl(ClsFields[i]);
20038 }
20039 CDecl->setIvarLBraceLoc(LBrac);
20040 CDecl->setIvarRBraceLoc(RBrac);
20041 }
20042 }
20044}
20045
20046// Given an integral type, return the next larger integral type
20047// (or a NULL type of no such type exists).
20049 // FIXME: Int128/UInt128 support, which also needs to be introduced into
20050 // enum checking below.
20051 assert((T->isIntegralType(Context) ||
20052 T->isEnumeralType()) && "Integral type required!");
20053 const unsigned NumTypes = 4;
20054 QualType SignedIntegralTypes[NumTypes] = {
20055 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
20056 };
20057 QualType UnsignedIntegralTypes[NumTypes] = {
20058 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
20059 Context.UnsignedLongLongTy
20060 };
20061
20062 unsigned BitWidth = Context.getTypeSize(T);
20063 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
20064 : UnsignedIntegralTypes;
20065 for (unsigned I = 0; I != NumTypes; ++I)
20066 if (Context.getTypeSize(Types[I]) > BitWidth)
20067 return Types[I];
20068
20069 return QualType();
20070}
20071
20073 EnumConstantDecl *LastEnumConst,
20074 SourceLocation IdLoc,
20075 IdentifierInfo *Id,
20076 Expr *Val) {
20077 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
20078 llvm::APSInt EnumVal(IntWidth);
20079 QualType EltTy;
20080
20082 Val = nullptr;
20083
20084 if (Val)
20085 Val = DefaultLvalueConversion(Val).get();
20086
20087 if (Val) {
20088 if (Enum->isDependentType() || Val->isTypeDependent() ||
20089 Val->containsErrors())
20090 EltTy = Context.DependentTy;
20091 else {
20092 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
20093 // underlying type, but do allow it in all other contexts.
20094 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
20095 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
20096 // constant-expression in the enumerator-definition shall be a converted
20097 // constant expression of the underlying type.
20098 EltTy = Enum->getIntegerType();
20100 Val, EltTy, EnumVal, CCEKind::Enumerator);
20101 if (Converted.isInvalid())
20102 Val = nullptr;
20103 else
20104 Val = Converted.get();
20105 } else if (!Val->isValueDependent() &&
20106 !(Val = VerifyIntegerConstantExpression(Val, &EnumVal,
20108 .get())) {
20109 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
20110 } else {
20111 if (Enum->isComplete()) {
20112 EltTy = Enum->getIntegerType();
20113
20114 // In Obj-C and Microsoft mode, require the enumeration value to be
20115 // representable in the underlying type of the enumeration. In C++11,
20116 // we perform a non-narrowing conversion as part of converted constant
20117 // expression checking.
20118 if (!Context.isRepresentableIntegerValue(EnumVal, EltTy)) {
20119 if (Context.getTargetInfo()
20120 .getTriple()
20121 .isWindowsMSVCEnvironment()) {
20122 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
20123 } else {
20124 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
20125 }
20126 }
20127
20128 // Cast to the underlying type.
20129 Val = ImpCastExprToType(Val, EltTy,
20130 EltTy->isBooleanType() ? CK_IntegralToBoolean
20131 : CK_IntegralCast)
20132 .get();
20133 } else if (getLangOpts().CPlusPlus) {
20134 // C++11 [dcl.enum]p5:
20135 // If the underlying type is not fixed, the type of each enumerator
20136 // is the type of its initializing value:
20137 // - If an initializer is specified for an enumerator, the
20138 // initializing value has the same type as the expression.
20139 EltTy = Val->getType();
20140 } else {
20141 // C99 6.7.2.2p2:
20142 // The expression that defines the value of an enumeration constant
20143 // shall be an integer constant expression that has a value
20144 // representable as an int.
20145
20146 // Complain if the value is not representable in an int.
20147 if (!Context.isRepresentableIntegerValue(EnumVal, Context.IntTy)) {
20148 Diag(IdLoc, getLangOpts().C23
20149 ? diag::warn_c17_compat_enum_value_not_int
20150 : diag::ext_c23_enum_value_not_int)
20151 << 0 << toString(EnumVal, 10) << Val->getSourceRange()
20152 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
20153 } else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
20154 // Force the type of the expression to 'int'.
20155 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
20156 }
20157 EltTy = Val->getType();
20158 }
20159 }
20160 }
20161 }
20162
20163 if (!Val) {
20164 if (Enum->isDependentType())
20165 EltTy = Context.DependentTy;
20166 else if (!LastEnumConst) {
20167 // C++0x [dcl.enum]p5:
20168 // If the underlying type is not fixed, the type of each enumerator
20169 // is the type of its initializing value:
20170 // - If no initializer is specified for the first enumerator, the
20171 // initializing value has an unspecified integral type.
20172 //
20173 // GCC uses 'int' for its unspecified integral type, as does
20174 // C99 6.7.2.2p3.
20175 if (Enum->isFixed()) {
20176 EltTy = Enum->getIntegerType();
20177 }
20178 else {
20179 EltTy = Context.IntTy;
20180 }
20181 } else {
20182 // Assign the last value + 1.
20183 EnumVal = LastEnumConst->getInitVal();
20184 ++EnumVal;
20185 EltTy = LastEnumConst->getType();
20186
20187 // Check for overflow on increment.
20188 if (EnumVal < LastEnumConst->getInitVal()) {
20189 // C++0x [dcl.enum]p5:
20190 // If the underlying type is not fixed, the type of each enumerator
20191 // is the type of its initializing value:
20192 //
20193 // - Otherwise the type of the initializing value is the same as
20194 // the type of the initializing value of the preceding enumerator
20195 // unless the incremented value is not representable in that type,
20196 // in which case the type is an unspecified integral type
20197 // sufficient to contain the incremented value. If no such type
20198 // exists, the program is ill-formed.
20200 if (T.isNull() || Enum->isFixed()) {
20201 // There is no integral type larger enough to represent this
20202 // value. Complain, then allow the value to wrap around.
20203 EnumVal = LastEnumConst->getInitVal();
20204 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
20205 ++EnumVal;
20206 if (Enum->isFixed())
20207 // When the underlying type is fixed, this is ill-formed.
20208 Diag(IdLoc, diag::err_enumerator_wrapped)
20209 << toString(EnumVal, 10)
20210 << EltTy;
20211 else
20212 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
20213 << toString(EnumVal, 10);
20214 } else {
20215 EltTy = T;
20216 }
20217
20218 // Retrieve the last enumerator's value, extent that type to the
20219 // type that is supposed to be large enough to represent the incremented
20220 // value, then increment.
20221 EnumVal = LastEnumConst->getInitVal();
20222 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20223 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
20224 ++EnumVal;
20225
20226 // If we're not in C++, diagnose the overflow of enumerator values,
20227 // which in C99 means that the enumerator value is not representable in
20228 // an int (C99 6.7.2.2p2). However C23 permits enumerator values that
20229 // are representable in some larger integral type and we allow it in
20230 // older language modes as an extension.
20231 // Exclude fixed enumerators since they are diagnosed with an error for
20232 // this case.
20233 if (!getLangOpts().CPlusPlus && !T.isNull() && !Enum->isFixed())
20234 Diag(IdLoc, getLangOpts().C23
20235 ? diag::warn_c17_compat_enum_value_not_int
20236 : diag::ext_c23_enum_value_not_int)
20237 << 1 << toString(EnumVal, 10) << 1;
20238 } else if (!getLangOpts().CPlusPlus && !EltTy->isDependentType() &&
20239 !Context.isRepresentableIntegerValue(EnumVal, EltTy)) {
20240 // Enforce C99 6.7.2.2p2 even when we compute the next value.
20241 Diag(IdLoc, getLangOpts().C23 ? diag::warn_c17_compat_enum_value_not_int
20242 : diag::ext_c23_enum_value_not_int)
20243 << 1 << toString(EnumVal, 10) << 1;
20244 }
20245 }
20246 }
20247
20248 if (!EltTy->isDependentType()) {
20249 // Make the enumerator value match the signedness and size of the
20250 // enumerator's type.
20251 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
20252 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20253 }
20254
20255 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
20256 Val, EnumVal);
20257}
20258
20260 SourceLocation IILoc) {
20261 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
20263 return SkipBodyInfo();
20264
20265 // We have an anonymous enum definition. Look up the first enumerator to
20266 // determine if we should merge the definition with an existing one and
20267 // skip the body.
20268 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
20270 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
20271 if (!PrevECD)
20272 return SkipBodyInfo();
20273
20274 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
20275 NamedDecl *Hidden;
20276 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
20278 Skip.Previous = Hidden;
20279 return Skip;
20280 }
20281
20282 return SkipBodyInfo();
20283}
20284
20285Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
20286 SourceLocation IdLoc, IdentifierInfo *Id,
20287 const ParsedAttributesView &Attrs,
20288 SourceLocation EqualLoc, Expr *Val,
20289 SkipBodyInfo *SkipBody) {
20290 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
20291 EnumConstantDecl *LastEnumConst =
20292 cast_or_null<EnumConstantDecl>(lastEnumConst);
20293
20294 // The scope passed in may not be a decl scope. Zip up the scope tree until
20295 // we find one that is.
20296 S = getNonFieldDeclScope(S);
20297
20298 // Verify that there isn't already something declared with this name in this
20299 // scope.
20300 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName,
20302 LookupName(R, S);
20303 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
20304
20305 if (PrevDecl && PrevDecl->isTemplateParameter()) {
20306 // Maybe we will complain about the shadowed template parameter.
20307 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
20308 // Just pretend that we didn't see the previous declaration.
20309 PrevDecl = nullptr;
20310 }
20311
20312 // C++ [class.mem]p15:
20313 // If T is the name of a class, then each of the following shall have a name
20314 // different from T:
20315 // - every enumerator of every member of class T that is an unscoped
20316 // enumerated type
20317 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped() &&
20319 DeclarationNameInfo(Id, IdLoc)))
20320 return nullptr;
20321
20323 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
20324 if (!New)
20325 return nullptr;
20326
20327 if (PrevDecl && (!SkipBody || !SkipBody->CheckSameAsPrevious)) {
20328 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
20329 // Check for other kinds of shadowing not already handled.
20330 CheckShadow(New, PrevDecl, R);
20331 }
20332
20333 // When in C++, we may get a TagDecl with the same name; in this case the
20334 // enum constant will 'hide' the tag.
20335 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
20336 "Received TagDecl when not in C++!");
20337 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
20338 if (isa<EnumConstantDecl>(PrevDecl))
20339 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
20340 else
20341 Diag(IdLoc, diag::err_redefinition) << Id;
20342 notePreviousDefinition(PrevDecl, IdLoc);
20343 return nullptr;
20344 }
20345 }
20346
20347 // Process attributes.
20348 ProcessDeclAttributeList(S, New, Attrs);
20351
20352 // Register this decl in the current scope stack.
20353 New->setAccess(TheEnumDecl->getAccess());
20355
20357
20358 return New;
20359}
20360
20361// Returns true when the enum initial expression does not trigger the
20362// duplicate enum warning. A few common cases are exempted as follows:
20363// Element2 = Element1
20364// Element2 = Element1 + 1
20365// Element2 = Element1 - 1
20366// Where Element2 and Element1 are from the same enum.
20368 Expr *InitExpr = ECD->getInitExpr();
20369 if (!InitExpr)
20370 return true;
20371 InitExpr = InitExpr->IgnoreImpCasts();
20372
20373 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
20374 if (!BO->isAdditiveOp())
20375 return true;
20376 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
20377 if (!IL)
20378 return true;
20379 if (IL->getValue() != 1)
20380 return true;
20381
20382 InitExpr = BO->getLHS();
20383 }
20384
20385 // This checks if the elements are from the same enum.
20386 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
20387 if (!DRE)
20388 return true;
20389
20390 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
20391 if (!EnumConstant)
20392 return true;
20393
20395 Enum)
20396 return true;
20397
20398 return false;
20399}
20400
20401// Emits a warning when an element is implicitly set a value that
20402// a previous element has already been set to.
20404 EnumDecl *Enum, QualType EnumType) {
20405 // Avoid anonymous enums
20406 if (!Enum->getIdentifier())
20407 return;
20408
20409 // Only check for small enums.
20410 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
20411 return;
20412
20413 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
20414 return;
20415
20416 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
20417 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
20418
20419 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
20420
20421 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
20422 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
20423
20424 // Use int64_t as a key to avoid needing special handling for map keys.
20425 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
20426 llvm::APSInt Val = D->getInitVal();
20427 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
20428 };
20429
20430 DuplicatesVector DupVector;
20431 ValueToVectorMap EnumMap;
20432
20433 // Populate the EnumMap with all values represented by enum constants without
20434 // an initializer.
20435 for (auto *Element : Elements) {
20436 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
20437
20438 // Null EnumConstantDecl means a previous diagnostic has been emitted for
20439 // this constant. Skip this enum since it may be ill-formed.
20440 if (!ECD) {
20441 return;
20442 }
20443
20444 // Constants with initializers are handled in the next loop.
20445 if (ECD->getInitExpr())
20446 continue;
20447
20448 // Duplicate values are handled in the next loop.
20449 EnumMap.insert({EnumConstantToKey(ECD), ECD});
20450 }
20451
20452 if (EnumMap.size() == 0)
20453 return;
20454
20455 // Create vectors for any values that has duplicates.
20456 for (auto *Element : Elements) {
20457 // The last loop returned if any constant was null.
20459 if (!ValidDuplicateEnum(ECD, Enum))
20460 continue;
20461
20462 auto Iter = EnumMap.find(EnumConstantToKey(ECD));
20463 if (Iter == EnumMap.end())
20464 continue;
20465
20466 DeclOrVector& Entry = Iter->second;
20467 if (EnumConstantDecl *D = dyn_cast<EnumConstantDecl *>(Entry)) {
20468 // Ensure constants are different.
20469 if (D == ECD)
20470 continue;
20471
20472 // Create new vector and push values onto it.
20473 auto Vec = std::make_unique<ECDVector>();
20474 Vec->push_back(D);
20475 Vec->push_back(ECD);
20476
20477 // Update entry to point to the duplicates vector.
20478 Entry = Vec.get();
20479
20480 // Store the vector somewhere we can consult later for quick emission of
20481 // diagnostics.
20482 DupVector.emplace_back(std::move(Vec));
20483 continue;
20484 }
20485
20486 ECDVector *Vec = cast<ECDVector *>(Entry);
20487 // Make sure constants are not added more than once.
20488 if (*Vec->begin() == ECD)
20489 continue;
20490
20491 Vec->push_back(ECD);
20492 }
20493
20494 // Emit diagnostics.
20495 for (const auto &Vec : DupVector) {
20496 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
20497
20498 // Emit warning for one enum constant.
20499 auto *FirstECD = Vec->front();
20500 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
20501 << FirstECD << toString(FirstECD->getInitVal(), 10)
20502 << FirstECD->getSourceRange();
20503
20504 // Emit one note for each of the remaining enum constants with
20505 // the same value.
20506 for (auto *ECD : llvm::drop_begin(*Vec))
20507 S.Diag(ECD->getLocation(), diag::note_duplicate_element)
20508 << ECD << toString(ECD->getInitVal(), 10)
20509 << ECD->getSourceRange();
20510 }
20511}
20512
20513bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
20514 bool AllowMask) const {
20515 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
20516 assert(ED->isCompleteDefinition() && "expected enum definition");
20517
20518 auto R = FlagBitsCache.try_emplace(ED);
20519 llvm::APInt &FlagBits = R.first->second;
20520
20521 if (R.second) {
20522 for (auto *E : ED->enumerators()) {
20523 const auto &EVal = E->getInitVal();
20524 // Only single-bit enumerators introduce new flag values.
20525 if (EVal.isPowerOf2())
20526 FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal;
20527 }
20528 }
20529
20530 // A value is in a flag enum if either its bits are a subset of the enum's
20531 // flag bits (the first condition) or we are allowing masks and the same is
20532 // true of its complement (the second condition). When masks are allowed, we
20533 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
20534 //
20535 // While it's true that any value could be used as a mask, the assumption is
20536 // that a mask will have all of the insignificant bits set. Anything else is
20537 // likely a logic error.
20538 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
20539 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
20540}
20541
20543 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
20544 const ParsedAttributesView &Attrs) {
20545 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
20546 CanQualType EnumType = Context.getCanonicalTagType(Enum);
20547
20548 ProcessDeclAttributeList(S, Enum, Attrs);
20550
20551 if (Enum->isDependentType()) {
20552 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
20553 EnumConstantDecl *ECD =
20554 cast_or_null<EnumConstantDecl>(Elements[i]);
20555 if (!ECD) continue;
20556
20557 ECD->setType(EnumType);
20558 }
20559
20560 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
20561 return;
20562 }
20563
20564 // Verify that all the values are okay, compute the size of the values, and
20565 // reverse the list.
20566 unsigned NumNegativeBits = 0;
20567 unsigned NumPositiveBits = 0;
20568 bool MembersRepresentableByInt =
20569 Context.computeEnumBits(Elements, NumNegativeBits, NumPositiveBits);
20570
20571 // Figure out the type that should be used for this enum.
20572 QualType BestType;
20573 unsigned BestWidth;
20574
20575 // C++0x N3000 [conv.prom]p3:
20576 // An rvalue of an unscoped enumeration type whose underlying
20577 // type is not fixed can be converted to an rvalue of the first
20578 // of the following types that can represent all the values of
20579 // the enumeration: int, unsigned int, long int, unsigned long
20580 // int, long long int, or unsigned long long int.
20581 // C99 6.4.4.3p2:
20582 // An identifier declared as an enumeration constant has type int.
20583 // The C99 rule is modified by C23.
20584 QualType BestPromotionType;
20585
20586 bool Packed = Enum->hasAttr<PackedAttr>();
20587 // -fshort-enums is the equivalent to specifying the packed attribute on all
20588 // enum definitions.
20589 if (LangOpts.ShortEnums)
20590 Packed = true;
20591
20592 // If the enum already has a type because it is fixed or dictated by the
20593 // target, promote that type instead of analyzing the enumerators.
20594 if (Enum->isComplete()) {
20595 BestType = Enum->getIntegerType();
20596 if (Context.isPromotableIntegerType(BestType))
20597 BestPromotionType = Context.getPromotedIntegerType(BestType);
20598 else
20599 BestPromotionType = BestType;
20600
20601 BestWidth = Context.getIntWidth(BestType);
20602 } else {
20603 bool EnumTooLarge = Context.computeBestEnumTypes(
20604 Packed, NumNegativeBits, NumPositiveBits, BestType, BestPromotionType);
20605 BestWidth = Context.getIntWidth(BestType);
20606 if (EnumTooLarge)
20607 Diag(Enum->getLocation(), diag::ext_enum_too_large);
20608 }
20609
20610 // Loop over all of the enumerator constants, changing their types to match
20611 // the type of the enum if needed.
20612 for (auto *D : Elements) {
20613 auto *ECD = cast_or_null<EnumConstantDecl>(D);
20614 if (!ECD) continue; // Already issued a diagnostic.
20615
20616 // C99 says the enumerators have int type, but we allow, as an
20617 // extension, the enumerators to be larger than int size. If each
20618 // enumerator value fits in an int, type it as an int, otherwise type it the
20619 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
20620 // that X has type 'int', not 'unsigned'.
20621
20622 // Determine whether the value fits into an int.
20623 llvm::APSInt InitVal = ECD->getInitVal();
20624
20625 // If it fits into an integer type, force it. Otherwise force it to match
20626 // the enum decl type.
20627 QualType NewTy;
20628 unsigned NewWidth;
20629 bool NewSign;
20630 if (!getLangOpts().CPlusPlus && !Enum->isFixed() &&
20631 MembersRepresentableByInt) {
20632 // C23 6.7.3.3.3p15:
20633 // The enumeration member type for an enumerated type without fixed
20634 // underlying type upon completion is:
20635 // - int if all the values of the enumeration are representable as an
20636 // int; or,
20637 // - the enumerated type
20638 NewTy = Context.IntTy;
20639 NewWidth = Context.getTargetInfo().getIntWidth();
20640 NewSign = true;
20641 } else if (ECD->getType() == BestType) {
20642 // Already the right type!
20643 if (getLangOpts().CPlusPlus)
20644 // C++ [dcl.enum]p4: Following the closing brace of an
20645 // enum-specifier, each enumerator has the type of its
20646 // enumeration.
20647 ECD->setType(EnumType);
20648 continue;
20649 } else {
20650 NewTy = BestType;
20651 NewWidth = BestWidth;
20652 NewSign = BestType->isSignedIntegerOrEnumerationType();
20653 }
20654
20655 // Adjust the APSInt value.
20656 InitVal = InitVal.extOrTrunc(NewWidth);
20657 InitVal.setIsSigned(NewSign);
20658 ECD->setInitVal(Context, InitVal);
20659
20660 // Adjust the Expr initializer and type.
20661 if (ECD->getInitExpr() &&
20662 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
20663 ECD->setInitExpr(ImplicitCastExpr::Create(
20664 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
20665 /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
20666 if (getLangOpts().CPlusPlus)
20667 // C++ [dcl.enum]p4: Following the closing brace of an
20668 // enum-specifier, each enumerator has the type of its
20669 // enumeration.
20670 ECD->setType(EnumType);
20671 else
20672 ECD->setType(NewTy);
20673 }
20674
20675 Enum->completeDefinition(BestType, BestPromotionType,
20676 NumPositiveBits, NumNegativeBits);
20677
20678 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
20679
20680 if (Enum->isClosedFlag()) {
20681 for (Decl *D : Elements) {
20682 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
20683 if (!ECD) continue; // Already issued a diagnostic.
20684
20685 llvm::APSInt InitVal = ECD->getInitVal();
20686 if (InitVal != 0 && !InitVal.isPowerOf2() &&
20687 !IsValueInFlagEnum(Enum, InitVal, true))
20688 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
20689 << ECD << Enum;
20690 }
20691 }
20692
20693 // Now that the enum type is defined, ensure it's not been underaligned.
20694 if (Enum->hasAttrs())
20696}
20697
20699 SourceLocation EndLoc) {
20700
20702 FileScopeAsmDecl::Create(Context, CurContext, expr, StartLoc, EndLoc);
20703 CurContext->addDecl(New);
20704 return New;
20705}
20706
20708 auto *New = TopLevelStmtDecl::Create(Context, /*Statement=*/nullptr);
20709 CurContext->addDecl(New);
20710 PushDeclContext(S, New);
20712 PushCompoundScope(false);
20713 return New;
20714}
20715
20717 if (Statement)
20718 D->setStmt(Statement);
20722}
20723
20725 IdentifierInfo* AliasName,
20726 SourceLocation PragmaLoc,
20727 SourceLocation NameLoc,
20728 SourceLocation AliasNameLoc) {
20729 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
20731 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
20733 AsmLabelAttr *Attr =
20734 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), Info);
20735
20736 // If a declaration that:
20737 // 1) declares a function or a variable
20738 // 2) has external linkage
20739 // already exists, add a label attribute to it.
20740 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
20741 if (isDeclExternC(PrevDecl))
20742 PrevDecl->addAttr(Attr);
20743 else
20744 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
20745 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
20746 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
20747 } else
20748 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
20749}
20750
20752 SourceLocation PragmaLoc,
20753 SourceLocation NameLoc) {
20754 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
20755
20756 if (PrevDecl) {
20757 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
20758 } else {
20759 (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
20760 }
20761}
20762
20764 IdentifierInfo* AliasName,
20765 SourceLocation PragmaLoc,
20766 SourceLocation NameLoc,
20767 SourceLocation AliasNameLoc) {
20768 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
20770 WeakInfo W = WeakInfo(Name, NameLoc);
20771
20772 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
20773 if (!PrevDecl->hasAttr<AliasAttr>())
20774 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
20776 } else {
20777 (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
20778 }
20779}
20780
20782 bool Final) {
20783 assert(FD && "Expected non-null FunctionDecl");
20784
20785 // SYCL functions can be template, so we check if they have appropriate
20786 // attribute prior to checking if it is a template.
20787 if (LangOpts.SYCLIsDevice && FD->hasAttr<DeviceKernelAttr>())
20789
20790 // Templates are emitted when they're instantiated.
20791 if (FD->isDependentContext())
20793
20794 // Check whether this function is an externally visible definition.
20795 auto IsEmittedForExternalSymbol = [this, FD]() {
20796 // We have to check the GVA linkage of the function's *definition* -- if we
20797 // only have a declaration, we don't know whether or not the function will
20798 // be emitted, because (say) the definition could include "inline".
20799 const FunctionDecl *Def = FD->getDefinition();
20800
20801 // We can't compute linkage when we skip function bodies.
20802 return Def && !Def->hasSkippedBody() &&
20804 getASTContext().GetGVALinkageForFunction(Def));
20805 };
20806
20807 if (LangOpts.OpenMPIsTargetDevice) {
20808 // In OpenMP device mode we will not emit host only functions, or functions
20809 // we don't need due to their linkage.
20810 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20811 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20812 // DevTy may be changed later by
20813 // #pragma omp declare target to(*) device_type(*).
20814 // Therefore DevTy having no value does not imply host. The emission status
20815 // will be checked again at the end of compilation unit with Final = true.
20816 if (DevTy)
20817 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
20819 // If we have an explicit value for the device type, or we are in a target
20820 // declare context, we need to emit all extern and used symbols.
20821 if (OpenMP().isInOpenMPDeclareTargetContext() || DevTy)
20822 if (IsEmittedForExternalSymbol())
20824 // Device mode only emits what it must, if it wasn't tagged yet and needed,
20825 // we'll omit it.
20826 if (Final)
20828 } else if (LangOpts.OpenMP > 45) {
20829 // In OpenMP host compilation prior to 5.0 everything was an emitted host
20830 // function. In 5.0, no_host was introduced which might cause a function to
20831 // be omitted.
20832 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20833 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20834 if (DevTy)
20835 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
20837 }
20838
20839 if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
20841
20842 if (LangOpts.CUDA) {
20843 // When compiling for device, host functions are never emitted. Similarly,
20844 // when compiling for host, device and global functions are never emitted.
20845 // (Technically, we do emit a host-side stub for global functions, but this
20846 // doesn't count for our purposes here.)
20848 if (LangOpts.CUDAIsDevice && T == CUDAFunctionTarget::Host)
20850 if (!LangOpts.CUDAIsDevice &&
20853
20854 if (IsEmittedForExternalSymbol())
20856
20857 // If FD is a virtual destructor of an explicit instantiation
20858 // of a template class, return Emitted.
20859 if (auto *Destructor = dyn_cast<CXXDestructorDecl>(FD)) {
20860 if (Destructor->isVirtual()) {
20861 if (auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(
20862 Destructor->getParent())) {
20864 Spec->getTemplateSpecializationKind();
20868 }
20869 }
20870 }
20871 }
20872
20873 // Otherwise, the function is known-emitted if it's in our set of
20874 // known-emitted functions.
20876}
20877
20879 // Host-side references to a __global__ function refer to the stub, so the
20880 // function itself is never emitted and therefore should not be marked.
20881 // If we have host fn calls kernel fn calls host+device, the HD function
20882 // does not get instantiated on the host. We model this by omitting at the
20883 // call to the kernel from the callgraph. This ensures that, when compiling
20884 // for host, only HD functions actually called from the host get marked as
20885 // known-emitted.
20886 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
20888}
20889
20891 bool &Visible) {
20892 Visible = hasVisibleDefinition(D, Suggested);
20893 // The redefinition of D in the **current** TU is allowed if D is invisible or
20894 // D is defined in the global module of other module units. We didn't check if
20895 // it is in global module as, we'll check the redefinition in named module
20896 // later with better diagnostic message.
20897 return D->isInAnotherModuleUnit() || !Visible;
20898}
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:2229
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
static bool hasDefinition(const ObjCObjectPointerType *ObjPtr)
Defines the clang::Expr interface and subclasses for C++ expressions.
TokenType getType() const
Returns the token's type, e.g.
FormatToken * Previous
The previous token in the unwrapped line.
FormatToken * Next
The next token in the unwrapped line.
static const Decl * getCanonicalDecl(const Decl *D)
static const GlobalDecl isTemplate(GlobalDecl GD, const TemplateArgumentList *&TemplateArgs)
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Architecture Architecture
Definition MachO.h:27
llvm::MachO::Record Record
Definition MachO.h:31
static bool isExternC(const NamedDecl *ND)
Definition Mangle.cpp:74
#define SM(sm)
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
Defines the clang::Preprocessor interface.
RedeclarationKind
Specifies whether (or how) name lookup is being performed for a redeclaration (vs.
@ NotForRedeclaration
The lookup is a reference to this name that is not for the purpose of redeclaring the name.
@ ForExternalRedeclaration
The lookup results will be used for redeclaration of a name with external linkage; non-visible lookup...
@ ForVisibleRedeclaration
The lookup results will be used for redeclaration of a name, if an entity by that name already exists...
llvm::SmallVector< std::pair< const MemRegion *, SVal >, 4 > Bindings
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis functions specific to ARM.
static bool hasAttr(const Decl *D, bool IgnoreImplicitAttr)
Definition SemaCUDA.cpp:109
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:175
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:230
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:830
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:594
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 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:613
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:845
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 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 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 SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, const VarDecl *VD)
Return the location of the capture if the given lambda captures the given variable VD,...
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:188
SourceManager & getSourceManager()
Definition ASTContext.h:801
TranslationUnitDecl * getTranslationUnitDecl() const
const ConstantArrayType * getAsConstantArrayType(QualType T) const
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType, const Attr *attr=nullptr) const
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
IdentifierTable & Idents
Definition ASTContext.h:740
const LangOptions & getLangOpts() const
Definition ASTContext.h:894
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.
const VariableArrayType * getAsVariableArrayType(QualType T) const
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:859
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:3507
Wrapper for source info for arrays.
Definition TypeLoc.h:1757
SourceLocation getLBracketLoc() const
Definition TypeLoc.h:1759
Expr * getSizeExpr() const
Definition TypeLoc.h:1779
TypeLoc getElementLoc() const
Definition TypeLoc.h:1787
SourceLocation getRBracketLoc() const
Definition TypeLoc.h:1767
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3738
QualType getElementType() const
Definition TypeBase.h:3750
Attr - This represents one attribute.
Definition Attr.h:44
attr::Kind getKind() const
Definition Attr.h:90
bool isInherited() const
Definition Attr.h:99
Attr * clone(ASTContext &C) const
void setImplicit(bool I)
Definition Attr.h:104
SourceLocation getLocation() const
Definition Attr.h:97
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:1017
TypeLoc getModifiedLoc() const
The modified type, which is generally canonically different from the attribute type.
Definition TypeLoc.h:1031
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression which will be evaluated if the condition evaluates to false; ...
Definition Expr.h:4443
Expr * getCond() const
getCond - Return the condition expression; this is defined in terms of the opaque value.
Definition Expr.h:4431
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:3974
Expr * getLHS() const
Definition Expr.h:4024
Expr * getRHS() const
Definition Expr.h:4026
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4115
A binding in a decomposition declaration.
Definition DeclCXX.h:4179
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4634
bool doesNotEscape() const
Definition Decl.h:4785
This class is used for builtin types like 'int'.
Definition TypeBase.h:3182
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
Definition Builtins.h:228
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:375
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:1692
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1612
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:2937
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:3154
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:3083
bool isCallToStdMove() const
Definition Expr.cpp:3578
Expr * getCallee()
Definition Expr.h:3026
arg_range arguments()
Definition Expr.h:3131
CastKind getCastKind() const
Definition Expr.h:3656
Expr * getSubExpr()
Definition Expr.h:3662
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:3776
static unsigned getNumAddressingBits(const ASTContext &Context, QualType ElementType, const llvm::APInt &NumElements)
Determine the number of bits required to address a member of.
Definition Type.cpp:214
static unsigned getMaxSizeBits(const ASTContext &Context)
Determine the maximum number of active bits that an array's size can require, which limits the maximu...
Definition Type.cpp:254
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3832
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:346
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:37
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:1272
ValueDecl * getDecl()
Definition Expr.h:1340
SourceLocation getBeginLoc() const
Definition Expr.h:1351
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:319
bool isInStdNamespace() const
Definition DeclBase.cpp:427
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:524
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:156
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:286
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:578
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:251
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:553
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:360
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:364
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:779
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition Decl.h:821
SourceLocation getOuterLocStart() const
Return start of source range taking into account any outer template declarations.
Definition Decl.cpp:2050
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2090
SourceLocation getTypeSpecStartLoc() const
Definition Decl.cpp:1988
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:830
const AssociatedConstraint & getTrailingRequiresClause() const
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition Decl.h:854
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition Decl.h:813
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition Decl.cpp:2000
NestedNameSpecifier getQualifier() const
Retrieve the nested-name-specifier that qualifies the name of this declaration, if it was present in ...
Definition Decl.h:836
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:808
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition Decl.cpp:2034
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 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 takeAttributes(ParsedAttributes &attrs)
takeAttributes - Takes attributes from the given parsed-attributes set and add them to this declarato...
Definition DeclSpec.h:2650
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:4243
static DecompositionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation LSquareLoc, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< BindingDecl * > Bindings)
Definition DeclCXX.cpp:3613
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:2493
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2581
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2561
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:2570
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:231
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:950
An instance of this object exists for each enum constant that is defined.
Definition Decl.h:3420
llvm::APSInt getInitVal() const
Definition Decl.h:3440
static EnumConstantDecl * Create(ASTContext &C, EnumDecl *DC, SourceLocation L, IdentifierInfo *Id, QualType T, Expr *E, const llvm::APSInt &V)
Definition Decl.cpp:5579
const Expr * getInitExpr() const
Definition Decl.h:3438
Represents an enum.
Definition Decl.h:4004
enumerator_range enumerators() const
Definition Decl.h:4141
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition Decl.h:4213
void setIntegerType(QualType T)
Set the underlying integer type.
Definition Decl.h:4177
void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo)
Set the underlying integer type source info.
Definition Decl.h:4180
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4227
static EnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, bool IsScoped, bool IsScopedUsingClassTag, bool IsFixed)
Definition Decl.cpp:4953
bool isClosedFlag() const
Returns true if this enum is annotated with flag_enum and isn't annotated with enum_extensibility(ope...
Definition Decl.cpp:4992
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition Decl.h:4222
SourceRange getIntegerTypeRange() const LLVM_READONLY
Retrieve the source range that covers the underlying type if specified.
Definition Decl.cpp:4967
void setPromotionType(QualType T)
Set the promotion type.
Definition Decl.h:4163
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4168
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:3073
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:3069
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:3053
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:273
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:3157
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3260
bool isAnonymousStructOrUnion() const
Determines whether this field is a representative for an anonymous struct or union.
Definition Decl.cpp:4656
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3393
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:4641
bool isZeroLengthBitField() const
Is this a zero-length bit-field?
Definition Decl.cpp:4702
static FileScopeAsmDecl * Create(ASTContext &C, DeclContext *DC, Expr *Str, SourceLocation AsmLoc, SourceLocation RParenLoc)
Definition Decl.cpp:5712
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:78
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:139
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:128
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:102
Represents a function declaration or definition.
Definition Decl.h:1999
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2686
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:2188
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2794
ConstexprSpecKind getConstexprKind() const
Definition Decl.h:2475
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4146
void setPreviousDeclaration(FunctionDecl *PrevDecl)
Definition Decl.cpp:3674
void setDescribedFunctionTemplate(FunctionTemplateDecl *Template)
Definition Decl.cpp:4139
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4134
void setIsPureVirtual(bool P=true)
Definition Decl.cpp:3290
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition Decl.h:2313
void setFriendConstraintRefersToEnclosingTemplate(bool V=true)
Definition Decl.h:2698
void setHasSkippedBody(bool Skipped=true)
Definition Decl.h:2677
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition Decl.cpp:3965
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3703
param_iterator param_end()
Definition Decl.h:2784
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:2918
void setIsMultiVersion(bool V=true)
Sets the multiversion state for this declaration and all of its redeclarations.
Definition Decl.h:2692
QualType getReturnType() const
Definition Decl.h:2842
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2771
bool isCPUSpecificMultiVersion() const
True if this function is a multiversioned processor specific function as a part of the cpu_specific/c...
Definition Decl.cpp:3647
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted.
Definition Decl.h:2388
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2376
LanguageLinkage getLanguageLinkage() const
Compute the language linkage.
Definition Decl.cpp:3555
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4254
bool hasWrittenPrototype() const
Whether this function has a written prototype.
Definition Decl.h:2447
void setWillHaveBody(bool V=true)
Definition Decl.h:2683
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:2593
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition Decl.h:2442
FunctionTemplateSpecializationInfo * getTemplateSpecializationInfo() const
If this function is actually a function template specialization, retrieve information about this func...
Definition Decl.cpp:4264
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3688
param_iterator param_begin()
Definition Decl.h:2783
const ParmVarDecl * getNonObjectParameter(unsigned I) const
Definition Decl.h:2820
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3125
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition Decl.h:2325
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2539
FunctionEffectsRef getFunctionEffects() const
Definition Decl.h:3131
bool isMSVCRTEntryPoint() const
Determines whether this function is a MSVCRT user defined entry point.
Definition Decl.cpp:3363
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition Decl.cpp:4198
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:2885
bool isStatic() const
Definition Decl.h:2926
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a member function.
Definition Decl.cpp:4467
void setTrivial(bool IT)
Definition Decl.h:2377
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4085
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:2469
bool isDeletedAsWritten() const
Definition Decl.h:2543
redecl_iterator redecls_end() const
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition Decl.h:2352
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition Decl.cpp:3559
bool isLateTemplateParsed() const
Whether this templated function will be late parsed.
Definition Decl.h:2356
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:2427
void setVirtualAsWritten(bool V)
State that this function is marked as virtual explicitly.
Definition Decl.h:2348
bool hasSkippedBody() const
True if the function was a definition but its body was skipped.
Definition Decl.h:2676
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition Decl.h:2281
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition Decl.cpp:3356
void setImplicitlyInline(bool I=true)
Flag that this function is implicitly inline.
Definition Decl.h:2913
bool param_empty() const
Definition Decl.h:2782
bool isThisDeclarationInstantiatedFromAFriendDefinition() const
Determine whether this specific declaration of the function is a friend declaration that was instanti...
Definition Decl.cpp:3215
void setRangeEnd(SourceLocation E)
Definition Decl.h:2217
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
Definition Decl.cpp:3643
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2384
void setIneligibleOrNotSelected(bool II)
Definition Decl.h:2420
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:4490
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition Decl.h:2930
const IdentifierInfo * getLiteralIdentifier() const
getLiteralIdentifier - The literal suffix identifier this function represents, if any.
Definition Decl.cpp:4079
void setConstexprKind(ConstexprSpecKind CSK)
Definition Decl.h:2472
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4358
void setDefaulted(bool D=true)
Definition Decl.h:2385
bool isConsteval() const
Definition Decl.h:2481
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:2859
void setBody(Stmt *B)
Definition Decl.cpp:3283
bool isGlobal() const
Determines whether this is a global function.
Definition Decl.cpp:3573
void setDeletedAsWritten(bool D=true, StringLiteral *Message=nullptr)
Definition Decl.cpp:3161
bool hasInheritedPrototype() const
Whether this function inherited its prototype from a previous declaration.
Definition Decl.h:2458
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4106
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3767
DeclarationNameInfo getNameInfo() const
Definition Decl.h:2210
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3191
void setHasImplicitReturnZero(bool IRZ)
State that falling off this function implicitly returns null/zero.
Definition Decl.h:2434
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:3238
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:2896
MultiVersionKind getMultiVersionKind() const
Gets the kind of multiversioning attribute this declaration has.
Definition Decl.cpp:3629
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition Decl.h:2682
A mutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5218
SmallVector< Conflict > Conflicts
Definition TypeBase.h:5250
static FunctionEffectSet getUnion(FunctionEffectsRef LHS, FunctionEffectsRef RHS, Conflicts &Errs)
Definition Type.cpp:5724
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5082
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5282
unsigned getNumParams() const
Definition TypeBase.h:5560
QualType getParamType(unsigned i) const
Definition TypeBase.h:5562
unsigned getAArch64SMEAttributes() const
Return a bitmask describing the SME attributes on the function type, see AArch64SMETypeAttributes for...
Definition TypeBase.h:5779
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition TypeBase.h:5595
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5686
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5571
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5567
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:1624
A class which abstracts out some details necessary for making a call.
Definition TypeBase.h:4589
ExtInfo withCallingConv(CallingConv cc) const
Definition TypeBase.h:4701
CallingConv getCC() const
Definition TypeBase.h:4648
ExtInfo withProducesResult(bool producesResult) const
Definition TypeBase.h:4667
unsigned getRegParm() const
Definition TypeBase.h:4641
bool getNoCallerSavedRegs() const
Definition TypeBase.h:4637
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4660
ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const
Definition TypeBase.h:4681
ExtInfo withRegParm(unsigned RegParm) const
Definition TypeBase.h:4695
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4478
ExtInfo getExtInfo() const
Definition TypeBase.h:4834
static StringRef getNameForCallConv(CallingConv CC)
Definition Type.cpp:3613
unsigned getRegParmType() const
Definition TypeBase.h:4821
CallingConv getCallConv() const
Definition TypeBase.h:4833
QualType getReturnType() const
Definition TypeBase.h:4818
bool getCmseNSCallAttr() const
Definition TypeBase.h:4832
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:2068
Represents a C array with an unspecified size.
Definition TypeBase.h:3925
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3464
static IndirectFieldDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, const IdentifierInfo *Id, QualType T, MutableArrayRef< NamedDecl * > CH)
Definition Decl.cpp:5606
void setInherited(bool I)
Definition Attr.h:156
Description of a constructor that was inherited from a base class.
Definition DeclCXX.h:2575
child_range children()
Definition Expr.h:5434
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:971
Represents the declaration of a label.
Definition Decl.h:523
bool isResolvedMSAsmLabel() const
Definition Decl.h:558
LabelStmt * getStmt() const
Definition Decl.h:547
bool isMSAsmLabel() const
Definition Decl.h:557
llvm::iterator_range< capture_init_iterator > capture_inits()
Retrieve the initialization expressions for this lambda's captures.
Definition ExprCXX.h:2085
@ 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...
bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const
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....
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:3009
static LinkageSpecDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExternLoc, SourceLocation LangLoc, LinkageSpecLanguageIDs Lang, bool HasBraces)
Definition DeclCXX.cpp:3184
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:3383
Expr * getBase() const
Definition Expr.h:3377
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3669
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:273
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:486
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:294
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:300
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition Decl.cpp:1095
Visibility getVisibility() const
Determines the visibility of this entity.
Definition Decl.h:443
bool hasLinkageBeenComputed() const
True if something has required us to compute the linkage of this declaration.
Definition Decl.h:478
bool hasExternalFormalLinkage() const
True if this decl has external linkage.
Definition Decl.h:428
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:339
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:1858
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:1930
bool isExternallyVisible() const
Definition Decl.h:432
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:396
Represent a C++ namespace.
Definition Decl.h:591
bool isAnonymousNamespace() const
Returns true if this is an anonymous namespace declaration.
Definition Decl.h:642
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:1283
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:1293
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:904
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:1153
@ CSK_Normal
Normal lookup.
Definition Overload.h:1157
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1369
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:256
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1395
TypeLoc getInnerLoc() const
Definition TypeLoc.h:1408
void setLParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1391
Sugar for parentheses used when specifying types.
Definition TypeBase.h:3320
Represents a parameter to a function.
Definition Decl.h:1789
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition Decl.h:1849
ObjCDeclQualifier getObjCDeclQualifier() const
Definition Decl.h:1853
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition Decl.h:1822
void setExplicitObjectParameterLoc(SourceLocation Loc)
Definition Decl.h:1881
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:2946
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2969
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:8161
Pointer-authentication qualifiers.
Definition TypeBase.h:152
bool isAddressDiscriminated() const
Definition TypeBase.h:265
TypeLoc getPointeeLoc() const
Definition TypeLoc.h:1474
Wrapper for source info for pointers.
Definition TypeLoc.h:1493
void setStarLoc(SourceLocation Loc)
Definition TypeLoc.h:1499
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3346
QualType getPointeeType() const
Definition TypeBase.h:3356
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:8427
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition TypeBase.h:8421
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:87
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:1453
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition Type.cpp:2925
const IdentifierInfo * getBaseTypeIdentifier() const
Retrieves a pointer to the name of the base type.
Definition Type.cpp:109
QualType withoutLocalFastQualifiers() const
Definition TypeBase.h:1214
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition TypeBase.h:1296
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const
Check if this is a non-trivial type that would cause a C struct transitively containing this type to ...
Definition Type.cpp:2974
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8343
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8469
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:81
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8383
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1438
QualType getCanonicalType() const
Definition TypeBase.h:8395
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8437
PrimitiveDefaultInitializeKind isNonTrivialToPrimitiveDefaultInitialize() const
Functions to query basic properties of non-trivial C struct types.
Definition Type.cpp:2958
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:8416
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1670
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1545
bool isCanonical() const
Definition TypeBase.h:8400
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:2699
@ 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:75
A qualifier set is used to build a set of qualifiers.
Definition TypeBase.h:8283
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8290
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition Type.cpp:4710
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:4309
field_range fields() const
Definition Decl.h:4512
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition Decl.cpp:5111
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4509
field_iterator field_begin() const
Definition Decl.cpp:5154
Frontend produces RecoveryExprs on semantic errors that prevent creating other well-formed expression...
Definition Expr.h:7364
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:5292
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3589
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition Stmt.h:3160
void setNRVOCandidate(const VarDecl *Var)
Set the variable that might be used for the named return value optimization.
Definition Stmt.h:3203
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:1403
SemaDiagnosticBuilder DiagCompat(SourceLocation Loc, unsigned CompatDiagId, bool DeferHint=false)
Emit a compatibility diagnostic.
Definition SemaBase.cpp:91
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition SemaBase.cpp:61
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
void checkAllowedInitializer(VarDecl *VD)
Definition SemaCUDA.cpp:669
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:134
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:757
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:822
void CheckEntryPoint(FunctionDecl *FD)
Definition SemaHLSL.cpp:772
HLSLVkConstantIdAttr * mergeVkConstantIdAttr(Decl *D, const AttributeCommonInfo &AL, int Id)
Definition SemaHLSL.cpp:655
HLSLNumThreadsAttr * mergeNumThreadsAttr(Decl *D, const AttributeCommonInfo &AL, int X, int Y, int Z)
Definition SemaHLSL.cpp:621
void deduceAddressSpace(VarDecl *Decl)
void ActOnTopLevelFunction(FunctionDecl *FD)
Definition SemaHLSL.cpp:724
HLSLShaderAttr * mergeShaderAttr(Decl *D, const AttributeCommonInfo &AL, llvm::Triple::EnvironmentType ShaderType)
Definition SemaHLSL.cpp:691
HLSLWaveSizeAttr * mergeWaveSizeAttr(Decl *D, const AttributeCommonInfo &AL, int Min, int Max, int Preferred, int SpelledArgsCount)
Definition SemaHLSL.cpp:635
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:1884
Mode getAlignMode() const
Definition Sema.h:1886
A RAII object to temporarily push a declaration context.
Definition Sema.h:3468
A class which encapsulates the logic for delaying diagnostics during parsing and other processing.
Definition Sema.h:1352
bool shouldDelayDiagnostics()
Determines whether diagnostics should be delayed.
Definition Sema.h:1364
void add(const sema::DelayedDiagnostic &diag)
Adds a delayed diagnostic.
static NameClassification DependentNonType()
Definition Sema.h:3682
static NameClassification VarTemplate(TemplateName Name)
Definition Sema.h:3692
static NameClassification Unknown()
Definition Sema.h:3662
static NameClassification OverloadSet(ExprResult E)
Definition Sema.h:3666
static NameClassification UndeclaredTemplate(TemplateName Name)
Definition Sema.h:3710
static NameClassification FunctionTemplate(TemplateName Name)
Definition Sema.h:3698
static NameClassification NonType(NamedDecl *D)
Definition Sema.h:3672
static NameClassification Concept(TemplateName Name)
Definition Sema.h:3704
static NameClassification UndeclaredNonType()
Definition Sema.h:3678
static NameClassification TypeTemplate(TemplateName Name)
Definition Sema.h:3686
static NameClassification Error()
Definition Sema.h:3658
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12360
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12393
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:850
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:3560
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D)
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:12937
sema::CapturingScopeInfo * getEnclosingLambdaOrBlock() const
Get the innermost lambda or block enclosing the current location, if any.
Definition Sema.cpp:2539
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1113
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:8189
CXXSpecialMemberKind getSpecialMember(const CXXMethodDecl *MD)
Definition Sema.h:6264
LookupNameKind
Describes the kind of name lookup to perform.
Definition Sema.h:9277
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9281
@ LookupNestedNameSpecifierName
Look up of a name that precedes the '::' scope resolution operator in C++.
Definition Sema.h:9300
@ LookupLocalFriendName
Look up a friend of a local class.
Definition Sema.h:9316
@ LookupRedeclarationWithLinkage
Look up an ordinary name that is going to be redeclared as a name with linkage.
Definition Sema.h:9313
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9289
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition Sema.h:9284
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:1498
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:1234
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:4721
llvm::SmallSetVector< const TypedefNameDecl *, 4 > UnusedLocalTypedefNameCandidates
Set containing all typedefs that are likely unused.
Definition Sema.h:3542
PragmaClangSection PragmaClangRodataSection
Definition Sema.h:1810
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:6456
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:1438
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)
DeclResult ActOnVarTemplateSpecialization(Scope *S, Declarator &D, TypeSourceInfo *DI, LookupResult &Previous, SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, StorageClass SC, bool IsPartialSpecialization)
PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, const Decl *D=nullptr, QualType BlockType=QualType())
Pop a function (or block or lambda or captured region) scope from the stack.
Definition Sema.cpp:2442
Preprocessor & getPreprocessor() const
Definition Sema.h:917
void deduceOpenCLAddressSpace(ValueDecl *decl)
PragmaStack< FPOptionsOverride > FpPragmaStack
Definition Sema.h:2041
PragmaStack< StringLiteral * > CodeSegStack
Definition Sema.h:2035
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:4126
@ Delete
deleted-function-body
Definition Sema.h:4132
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:1523
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:1647
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:671
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:1276
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:915
void ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement)
void * SkippedDefinitionContext
Definition Sema.h:4350
bool LookupBuiltin(LookupResult &R)
Lookup a builtin function, when name lookup would otherwise fail.
SemaObjC & ObjC()
Definition Sema.h:1483
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:75
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
PragmaStack< bool > StrictGuardStackCheckStack
Definition Sema.h:2038
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:3550
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:918
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:2034
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:695
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:1184
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:1652
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)
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition Sema.h:12074
EnumDecl * getStdAlignValT() const
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition Sema.h:8307
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:2330
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:4559
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:913
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:2348
void PopCompoundScope()
Definition Sema.cpp:2481
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:14238
@ UPPC_EnumeratorValue
The enumerator value.
Definition Sema.h:14241
@ UPPC_Initializer
An initializer.
Definition Sema.h:14253
@ UPPC_FriendDeclaration
A friend declaration.
Definition Sema.h:14247
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition Sema.h:14226
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition Sema.h:14265
@ UPPC_DeclarationQualifier
A declaration qualifier.
Definition Sema.h:14250
@ UPPC_DataMemberType
The type of a data member.
Definition Sema.h:14229
@ UPPC_BitFieldWidth
The size of a bit-field.
Definition Sema.h:14232
const LangOptions & getLangOpts() const
Definition Sema.h:911
void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl, bool SupportedForCompatibility=false)
DiagnoseTemplateParameterShadow - Produce a diagnostic complaining that the template parameter 'PrevD...
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
bool RebuildTemplateParamsInCurrentInstantiation(TemplateParameterList *Params)
Rebuild the template parameters now that we know we're in a current instantiation.
void DiagnoseInvalidJumps(Stmt *Body)
SourceLocation CurInitSegLoc
Definition Sema.h:2074
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:3567
SemaOpenACC & OpenACC()
Definition Sema.h:1488
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:1275
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:2113
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:1274
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:2557
bool isReachable(const NamedDecl *D)
Determine whether a declaration is reachable.
Definition Sema.h:15330
Decl * ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody=nullptr, FnBodyKind BodyKind=FnBodyKind::Other)
SemaHLSL & HLSL()
Definition Sema.h:1448
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:1811
SemaRISCV & RISCV()
Definition Sema.h:1513
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:15504
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:207
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:1528
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:2023
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:6915
PragmaStack< StringLiteral * > BSSSegStack
Definition Sema.h:2033
bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true, bool AllowNonTemplateFunctions=false)
DeclContext * getCurLexicalContext() const
Definition Sema.h:1117
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:894
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:4736
void CheckMSVCRTEntryPoint(FunctionDecl *FD)
sema::FunctionScopeInfo * getCurFunction() const
Definition Sema.h:1307
void PushCompoundScope(bool IsStmtExpr)
Definition Sema.cpp:2476
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:6912
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:633
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:15324
StringLiteral * CurInitSeg
Last section used with pragma init_seg.
Definition Sema.h:2073
FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl, bool Final=false)
Module * getCurrentModule() const
Get the module unit whose scope we are currently within.
Definition Sema.h:9807
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:1411
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
SemaOpenCL & OpenCL()
Definition Sema.h:1493
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.
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:3564
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:13792
SourceManager & getSourceManager() const
Definition Sema.h:916
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:3517
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:1812
@ NTCUK_Destruct
Definition Sema.h:4065
@ NTCUK_Init
Definition Sema.h:4064
@ NTCUK_Copy
Definition Sema.h:4066
PragmaClangSection PragmaClangDataSection
Definition Sema.h:1809
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:6717
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:218
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:2497
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:6478
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:623
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:3538
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:270
EnumConstantDecl * CheckEnumConstant(EnumDecl *Enum, EnumConstantDecl *LastEnumConst, SourceLocation IdLoc, IdentifierInfo *Id, Expr *val)
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:1277
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition Sema.h:4622
SmallVector< ExprWithCleanups::CleanupObject, 8 > ExprCleanupObjects
ExprCleanupObjects - This is the stack of objects requiring cleanup that are created by the current f...
Definition Sema.h:6919
void DiagnoseUnusedNestedTypedefs(const RecordDecl *D)
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition Sema.h:1312
bool hasUncompilableErrorOccurred() const
Whether uncompilable error has occurred.
Definition Sema.cpp:1772
@ FirstDecl
Parsing the first decl in a TU.
Definition Sema.h:9835
void CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc)
void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FunctionDecl *FD)
If this function is a C++ replaceable global allocation function (C++2a [basic.stc....
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:1503
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:1239
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:3557
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:8262
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:1279
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:1278
OpenCLOptions & getOpenCLOptions()
Definition Sema.h:912
FPOptions CurFPFeatures
Definition Sema.h:1272
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:2032
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:11532
@ TPC_ClassTemplateMember
Definition Sema.h:11530
@ TPC_FunctionTemplate
Definition Sema.h:11529
@ TPC_FriendFunctionTemplateDefinition
Definition Sema.h:11533
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:1553
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:6494
QualType CheckConstructorDeclarator(Declarator &D, QualType R, StorageClass &SC)
CheckConstructorDeclarator - Called by ActOnDeclarator to check the well-formedness of the constructo...
void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD)
ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in it, apply them to D.
QualType SubstAutoTypeDependent(QualType TypeWithAuto)
void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace)
Filters out lookup results that don't fall within the given scope as determined by isDeclInScope.
void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, const WeakInfo &W)
DeclApplyPragmaWeak - A declaration (maybe definition) needs #pragma weak applied to it,...
bool IsInvalidSMECallConversion(QualType FromType, QualType ToType)
void ActOnUninitializedDecl(Decl *dcl)
void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc)
Emit diagnostics if the initializer or any of its explicit or implicitly-generated subexpressions req...
static Scope * getScopeForDeclContext(Scope *S, DeclContext *DC)
Finds the scope corresponding to the given decl context, if it happens to be an enclosing scope.
TypedefDecl * ParseTypedefDecl(Scope *S, Declarator &D, QualType T, TypeSourceInfo *TInfo)
Subroutines of ActOnDeclarator().
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit)
AddInitializerToDecl - Adds the initializer Init to the declaration dcl.
bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckOverridingFunctionExceptionSpec - Checks whether the exception spec is a subset of base spec.
Decl * ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth)
ActOnField - Each field of a C struct/union is passed into this in order to create a FieldDecl object...
FormatMatchesAttr * mergeFormatMatchesAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Format, int FormatIdx, StringLiteral *FormatStr)
AvailabilityAttr * mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI, IdentifierInfo *Platform, bool Implicit, VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable, StringRef Message, bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK, int Priority, IdentifierInfo *IIEnvironment)
void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old)
bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC, SkipBodyInfo *SkipBody=nullptr)
Checks the validity of a template parameter list, possibly considering the template parameter list fr...
void ActOnCXXForRangeDecl(Decl *D)
bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckOverridingFunctionReturnType - Checks whether the return types are covariant,...
std::tuple< MangleNumberingContext *, Decl * > getCurrentMangleNumberContext(const DeclContext *DC)
Compute the mangling number context for a lambda expression or block literal.
llvm::MapVector< IdentifierInfo *, llvm::SetVector< WeakInfo, llvm::SmallVector< WeakInfo, 1u >, llvm::SmallDenseSet< WeakInfo, 2u, WeakInfo::DenseMapInfoByAliasOnly > > > WeakUndeclaredIdentifiers
WeakUndeclaredIdentifiers - Identifiers contained in #pragma weak before declared.
Definition Sema.h:3532
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition Sema.cpp:2096
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:1808
Decl * ActOnDeclarator(Scope *S, Declarator &D)
@ AbstractVariableType
Definition Sema.h:6188
@ AbstractReturnType
Definition Sema.h:6186
@ AbstractFieldType
Definition Sema.h:6189
@ AbstractIvarType
Definition Sema.h:6190
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:8311
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:6375
void CheckVariableDeclarationType(VarDecl *NewVD)
OpaquePtr< TemplateName > TemplateTy
Definition Sema.h:1268
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:3513
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:1538
IdentifierResolver IdResolver
Definition Sema.h:3461
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:2488
void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc, Scope *S, CXXScopeSpec *SS, ParsedType &SuggestedType, bool IsTemplateName=false)
Definition SemaDecl.cpp:714
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:143
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:8270
OpaquePtr< DeclGroupRef > DeclGroupPtrTy
Definition Sema.h:1267
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:3805
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:1418
void inferNullableClassAttribute(CXXRecordDecl *CRD)
Add _Nullable attributes for std:: types.
Definition SemaAttr.cpp:322
void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, SourceLocation FinalLoc, bool IsFinalSpelledSealed, bool IsAbstract, SourceLocation TriviallyRelocatable, SourceLocation Replaceable, SourceLocation LBraceLoc)
ActOnStartCXXMemberDeclarations - Invoked when we have parsed a C++ record definition's base-specifie...
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8599
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:358
child_range children()
Definition Stmt.cpp:295
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:334
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:346
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1801
SourceLocation getStrTokenLoc(unsigned TokNum) const
Get one of the string literal token.
Definition Expr.h:1947
StringRef getString() const
Definition Expr.h:1869
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3714
static TagDecl * castFromDeclContext(const DeclContext *DC)
Definition Decl.h:3996
TagDecl * getDefinition() const
Returns the TagDecl that actually defines this struct/union/class/enum.
Definition Decl.cpp:4870
bool isThisDeclarationADefinition() const
Return true if this declaration is a completion definition of the type.
Definition Decl.h:3804
SourceLocation getInnerLocStart() const
Return SourceLocation representing start of source range ignoring outer template declarations.
Definition Decl.h:3790
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3809
bool isStruct() const
Definition Decl.h:3916
void setTypedefNameForAnonDecl(TypedefNameDecl *TDD)
Definition Decl.cpp:4842
bool isUnion() const
Definition Decl.h:3919
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type?
Definition Decl.h:3941
TagKind getTagKind() const
Definition Decl.h:3908
bool isDependentType() const
Whether this declaration declares a type that is dependent, i.e., a type that somehow depends on temp...
Definition Decl.h:3854
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:810
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:104
bool isNot(tok::TokenKind K) const
Definition Token.h:103
A declaration that models statements at global scope.
Definition Decl.h:4597
static TopLevelStmtDecl * Create(ASTContext &C, Stmt *Statement)
Definition Decl.cpp:5730
void setStmt(Stmt *S)
Definition Decl.cpp:5750
Represents a declaration of a type.
Definition Decl.h:3510
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:354
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:1417
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:222
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:942
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:2843
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:193
A container of type source information.
Definition TypeBase.h:8314
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:272
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8325
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:556
The base class of the type hierarchy.
Definition TypeBase.h:1833
bool isStructureType() const
Definition Type.cpp:678
bool isDependentSizedArrayType() const
Definition TypeBase.h:8699
bool isVoidType() const
Definition TypeBase.h:8936
bool isBooleanType() const
Definition TypeBase.h:9066
bool isFunctionReferenceType() const
Definition TypeBase.h:8654
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2229
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition TypeBase.h:9116
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition Type.cpp:2998
bool isIncompleteArrayType() const
Definition TypeBase.h:8687
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9235
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:8683
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition TypeBase.h:9096
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isArrayType() const
Definition TypeBase.h:8679
bool isFunctionPointerType() const
Definition TypeBase.h:8647
bool isPointerType() const
Definition TypeBase.h:8580
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9226
bool isReferenceType() const
Definition TypeBase.h:8604
bool isScalarType() const
Definition TypeBase.h:9038
bool isVariableArrayType() const
Definition TypeBase.h:8691
bool isClkEventT() const
Definition TypeBase.h:8822
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2107
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:752
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9054
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:65
bool isImageType() const
Definition TypeBase.h:8834
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition TypeBase.h:2917
bool isPipeType() const
Definition TypeBase.h:8841
bool isOpenCLSpecificType() const
Definition TypeBase.h:8870
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2800
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition Type.cpp:2415
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool isHalfType() const
Definition TypeBase.h:8940
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition Type.cpp:2060
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition Type.cpp:2562
bool containsErrors() const
Whether this type is an error type.
Definition TypeBase.h:2794
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition TypeBase.h:9109
bool isAtomicType() const
Definition TypeBase.h:8762
bool isFunctionProtoType() const
Definition TypeBase.h:2619
bool isObjCIdType() const
Definition TypeBase.h:8782
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2818
bool isObjCObjectType() const
Definition TypeBase.h:8753
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9072
bool isEventT() const
Definition TypeBase.h:8818
bool isPointerOrReferenceType() const
Definition TypeBase.h:8584
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2440
const T * getAsAdjusted() const
Member-template getAsAdjusted<specific type>.
Definition TypeBase.h:9176
bool isFunctionType() const
Definition TypeBase.h:8576
bool isObjCObjectPointerType() const
Definition TypeBase.h:8749
bool isMemberFunctionPointerType() const
Definition TypeBase.h:8665
bool isFloatingType() const
Definition Type.cpp:2308
bool isAnyPointerType() const
Definition TypeBase.h:8588
bool hasAutoForTrailingReturnType() const
Determine whether this type was written with a leading 'auto' corresponding to a trailing return type...
Definition Type.cpp:2065
bool isSamplerT() const
Definition TypeBase.h:8814
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9159
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:653
bool isNullPtrType() const
Definition TypeBase.h:8973
bool isRecordType() const
Definition TypeBase.h:8707
bool isHLSLResourceRecordArray() const
Definition Type.cpp:5419
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5066
bool isUnionType() const
Definition Type.cpp:718
bool isFunctionNoProtoType() const
Definition TypeBase.h:2618
bool isReserveIDT() const
Definition TypeBase.h:8830
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition Decl.h:3664
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition Decl.cpp:5629
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3559
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:3609
QualType getUnderlyingType() const
Definition Decl.h:3614
void setTypeSourceInfo(TypeSourceInfo *newType)
Definition Decl.h:3620
Wrapper for source info for typedefs.
Definition TypeLoc.h:782
TypedefNameDecl * getDecl() const
Definition TypeBase.h:6127
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:2287
Opcode getOpcode() const
Definition Expr.h:2282
static bool isIncrementDecrementOp(Opcode Op)
Definition Expr.h:2342
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:787
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3393
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3457
BaseUsingDecl * getIntroducer() const
Gets the (written or instantiated) using declaration that introduced this declaration.
Definition DeclCXX.cpp:3358
Wrapper for source info for types used via transparent aliases.
Definition TypeLoc.h:790
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:711
void setType(QualType newType)
Definition Decl.h:723
QualType getType() const
Definition Decl.h:722
bool isParameterPack() const
Determine whether this value is actually a function parameter pack, init-capture pack,...
Definition Decl.cpp:5461
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.cpp:5455
Represents a variable declaration or definition.
Definition Decl.h:925
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition Decl.cpp:2810
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition Decl.cpp:2151
void setCXXForRangeDecl(bool FRD)
Definition Decl.h:1524
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:1568
TLSKind getTLSKind() const
Definition Decl.cpp:2168
bool hasInit() const
Definition Decl.cpp:2398
void setInitStyle(InitializationStyle Style)
Definition Decl.h:1451
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:2260
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2190
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:2461
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:2257
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.h:1577
bool isCXXCondDecl() const
Definition Decl.h:1610
@ ListInit
Direct list-initialization (C++11)
Definition Decl.h:936
@ ParenListInit
Parenthesized list-initialization (C++20)
Definition Decl.h:939
@ CallInit
Call-style initialization (C++98)
Definition Decl.h:933
void setStorageClass(StorageClass SC)
Definition Decl.cpp:2163
void setPreviousDeclInSameBlockScope(bool Same)
Definition Decl.h:1592
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1282
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition Decl.h:1225
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition Decl.cpp:2366
void setInlineSpecified()
Definition Decl.h:1557
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1207
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition Decl.cpp:2772
bool isFileVarDecl() const
Returns true for file scoped variable declaration.
Definition Decl.h:1341
void setTSCSpec(ThreadStorageClassSpecifier TSC)
Definition Decl.h:1172
bool isInline() const
Whether this variable is (C++1z) inline.
Definition Decl.h:1550
ThreadStorageClassSpecifier getTSCSpec() const
Definition Decl.h:1176
const Expr * getInit() const
Definition Decl.h:1367
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition Decl.h:1216
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition Decl.h:1183
VarDecl * getInitializingDeclaration()
Get the initializing declaration of this variable, if any.
Definition Decl.cpp:2429
void setConstexpr(bool IC)
Definition Decl.h:1571
@ TLS_Static
TLS with a known-constant initializer.
Definition Decl.h:948
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition Decl.h:951
void setInit(Expr *I)
Definition Decl.cpp:2477
VarDecl * getActingDefinition()
Get the tentative definition that acts as the real definition in a TU.
Definition Decl.cpp:2345
@ TentativeDefinition
This declaration is a tentative definition.
Definition Decl.h:1297
@ DeclarationOnly
This declaration is only a declaration.
Definition Decl.h:1294
@ Definition
This declaration is definitely a definition.
Definition Decl.h:1300
void setDescribedVarTemplate(VarTemplateDecl *Template)
Definition Decl.cpp:2815
bool isExternC() const
Determines whether this variable is a variable with external, C linkage.
Definition Decl.cpp:2245
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition Decl.h:1252
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:1167
void setImplicitlyInline()
Definition Decl.h:1562
bool isThisDeclarationADemotedDefinition() const
If this definition should pretend to be a declaration.
Definition Decl.h:1475
bool isPreviousDeclInSameBlockScope() const
Whether this local extern variable declaration's previous declaration was declared in the same block ...
Definition Decl.h:1587
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:2706
bool isLocalVarDeclOrParm() const
Similar to isLocalVarDecl but also includes parameters.
Definition Decl.h:1261
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:2779
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition Decl.h:1357
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:3982
Expr * getSizeExpr() const
Definition TypeBase.h:3996
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.
bool evaluateRequiredTargetFeatures(llvm::StringRef RequiredFatures, const llvm::StringMap< bool > &TargetFetureMap)
Returns true if the required target features of a builtin function are enabled.
Public enums and private classes that are part of the SourceManager implementation.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
unsigned kind
All of the diagnostics that can be emitted by the frontend.
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
bool randomizeStructureLayout(const ASTContext &Context, RecordDecl *RD, llvm::SmallVectorImpl< Decl * > &FinalOrdering)
The JSON file list parser is used to communicate input to InstallAPI.
bool FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI)
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
@ TST_struct
Definition Specifiers.h:81
@ TST_class
Definition Specifiers.h:82
@ TST_union
Definition Specifiers.h:80
@ TST_enum
Definition Specifiers.h:79
@ TST_interface
Definition Specifiers.h:83
ImplicitTypenameContext
Definition DeclSpec.h:1857
@ NonFunction
This is not an overload because the lookup results contain a non-function.
Definition Sema.h:820
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:816
@ Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition Sema.h:812
bool isa(CodeGen::Address addr)
Definition Address.h:330
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition Specifiers.h:212
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus11
@ CPlusPlus14
@ CPlusPlus17
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition Ownership.h:263
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition Overload.h:55
@ GVA_AvailableExternally
Definition Linkage.h:74
CUDAFunctionTarget
Definition Cuda.h:60
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition ASTLambda.h:102
int hasAttribute(AttributeCommonInfo::Syntax Syntax, llvm::StringRef ScopeName, llvm::StringRef AttrName, const TargetInfo &Target, const LangOptions &LangOpts, bool CheckPlugins)
Return the version number associated with the attribute if we recognize and implement the attribute s...
ConstexprSpecKind
Define the kind of constexpr specifier.
Definition Specifiers.h:35
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition Lookup.h:64
@ NotFound
No entity found met the criteria.
Definition Lookup.h:41
@ FoundOverloaded
Name lookup found a set of overloaded functions that met the criteria.
Definition Lookup.h:54
@ Found
Name lookup found a single declaration that met the criteria.
Definition Lookup.h:50
@ FoundUnresolvedValue
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition Lookup.h:59
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition Lookup.h:46
InClassInitStyle
In-class initialization styles for non-static data members.
Definition Specifiers.h:271
@ ICIS_NoInit
No in-class initializer.
Definition Specifiers.h:272
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
Definition Parser.h:61
OverloadCandidateDisplayKind
Definition Overload.h:64
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
Definition Overload.h:73
@ OCD_AllCandidates
Requests that all candidates be shown.
Definition Overload.h:67
std::pair< FileID, unsigned > FileIDAndOffset
@ LCK_ByRef
Capturing by reference.
Definition Lambda.h:37
@ LCK_StarThis
Capturing the *this object by copy.
Definition Lambda.h:35
NonTagKind
Common ways to introduce type names without a tag for use in diagnostics.
Definition Sema.h:602
@ TemplateTemplateArgument
Definition Sema.h:611
NonTrivialCUnionContext
Definition Sema.h:530
AvailabilityMergeKind
Describes the kind of merge to perform for availability attributes (including "deprecated",...
Definition Sema.h:626
@ None
Don't merge availability attributes at all.
Definition Sema.h:628
@ Override
Merge availability attributes for an override, which requires an exact match or a weakening of constr...
Definition Sema.h:634
@ OptionalProtocolImplementation
Merge availability attributes for an implementation of an optional protocol requirement.
Definition Sema.h:640
@ Redeclaration
Merge availability attributes for a redeclaration, which requires an exact match.
Definition Sema.h:631
@ ProtocolImplementation
Merge availability attributes for an implementation of a protocol requirement.
Definition Sema.h:637
@ IK_DeductionGuideName
A deduction-guide name (a template-name)
Definition DeclSpec.h:994
@ IK_ImplicitSelfParam
An implicit 'self' parameter.
Definition DeclSpec.h:992
@ IK_TemplateId
A template-id, e.g., f<int>.
Definition DeclSpec.h:990
@ IK_ConstructorTemplateId
A constructor named via a template-id.
Definition DeclSpec.h:986
@ IK_ConstructorName
A constructor name.
Definition DeclSpec.h:984
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
Definition DeclSpec.h:982
@ IK_Identifier
An identifier.
Definition DeclSpec.h:976
@ IK_DestructorName
A destructor name.
Definition DeclSpec.h:988
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
Definition DeclSpec.h:978
@ IK_ConversionFunctionId
A conversion function name, e.g., operator int.
Definition DeclSpec.h:980
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition Specifiers.h:123
@ AS_public
Definition Specifiers.h:124
@ AS_protected
Definition Specifiers.h:125
@ AS_none
Definition Specifiers.h:127
SmallVector< Attr *, 4 > AttrVec
AttrVec - A vector of Attr, which is how they are stored on the AST.
ActionResult< Decl * > DeclResult
Definition Ownership.h:255
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
bool DeclAttrsMatchCUDAMode(const LangOptions &LangOpts, Decl *D)
@ AmbiguousTagHiding
Name lookup results in an ambiguity because an entity with a tag name was hidden by an entity with an...
Definition Lookup.h:137
LanguageLinkage
Describes the different kinds of language linkage (C++ [dcl.link]) that an entity may have.
Definition Linkage.h:63
@ CLanguageLinkage
Definition Linkage.h:64
@ CXXLanguageLinkage
Definition Linkage.h:65
StorageClass
Storage classes.
Definition Specifiers.h:248
@ SC_Auto
Definition Specifiers.h:256
@ SC_PrivateExtern
Definition Specifiers.h:253
@ SC_Extern
Definition Specifiers.h:251
@ SC_Register
Definition Specifiers.h:257
@ SC_Static
Definition Specifiers.h:252
@ SC_None
Definition Specifiers.h:250
@ TSCS_thread_local
C++11 thread_local.
Definition Specifiers.h:241
@ TSCS_unspecified
Definition Specifiers.h:236
@ TSCS__Thread_local
C11 _Thread_local.
Definition Specifiers.h:244
@ TSCS___thread
GNU __thread.
Definition Specifiers.h:238
const StreamingDiagnostic & operator<<(const StreamingDiagnostic &DB, const ASTContext::SectionInfo &Section)
Insertion operator for diagnostics.
std::pair< NullabilityKind, bool > DiagNullabilityKind
A nullability kind paired with a bit indicating whether it used a context-sensitive keyword.
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
Definition Linkage.h:24
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition Linkage.h:35
@ External
External linkage, which indicates that the entity can be referred to from other translation units.
Definition Linkage.h:58
@ Module
Module linkage, which indicates that the entity can be referred to from other translation units withi...
Definition Linkage.h:54
TemplateDecl * getAsTypeTemplateDecl(Decl *D)
llvm::Expected< Decl * > ExpectedDecl
@ SD_Thread
Thread storage duration.
Definition Specifiers.h:342
@ SD_Static
Static storage duration.
Definition Specifiers.h:343
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition ASTLambda.h:28
@ Parameter
The parameter type of a method or function.
Definition TypeBase.h:908
@ Result
The result type of a method or function.
Definition TypeBase.h:905
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
OffsetOfKind
Definition Sema.h:614
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
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:448
TagTypeKind
The kind of a tag type.
Definition TypeBase.h:5906
@ Interface
The "__interface" keyword.
Definition TypeBase.h:5911
@ Struct
The "struct" keyword.
Definition TypeBase.h:5908
@ Class
The "class" keyword.
Definition TypeBase.h:5917
@ Union
The "union" keyword.
Definition TypeBase.h:5914
@ Enum
The "enum" keyword.
Definition TypeBase.h:5920
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:4302
@ 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:424
@ 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
const FunctionProtoType * T
MultiVersionKind
Definition Decl.h:1978
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:366
@ Success
Template argument deduction was successful.
Definition Sema.h:368
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:420
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:146
@ Enumerator
Enumerator value with fixed underlying type.
Definition Sema.h:826
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition Ownership.h:230
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5902
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5892
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5895
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition TypeBase.h:5899
bool IsArmStreamingFunction(const FunctionDecl *FD, bool IncludeLocallyStreaming)
Returns whether the given FunctionDecl has an __arm[_locally]_streaming attribute.
Definition Decl.cpp:5967
ReservedIdentifierStatus
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Other
Other implicit parameter.
Definition Decl.h:1745
@ 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:87
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:5367
ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI)
Definition TypeBase.h:5394
static StringRef getTagTypeKindName(TagTypeKind Kind)
Definition TypeBase.h:5945
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition Type.cpp:3246
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:2008
SourceLocation CurrentPragmaLocation
Definition Sema.h:2009
bool CheckSameAsPrevious
Definition Sema.h:352
NamedDecl * Previous
Definition Sema.h:353
NamedDecl * New
Definition Sema.h:354
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