clang 23.0.0git
SemaDecl.cpp
Go to the documentation of this file.
1//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for declarations.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TypeLocBuilder.h"
16#include "clang/AST/ASTLambda.h"
18#include "clang/AST/CharUnits.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclObjC.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
29#include "clang/AST/StmtCXX.h"
30#include "clang/AST/Type.h"
37#include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
38#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
39#include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
40#include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
42#include "clang/Sema/DeclSpec.h"
45#include "clang/Sema/Lookup.h"
47#include "clang/Sema/Scope.h"
49#include "clang/Sema/SemaARM.h"
50#include "clang/Sema/SemaCUDA.h"
51#include "clang/Sema/SemaHLSL.h"
53#include "clang/Sema/SemaObjC.h"
56#include "clang/Sema/SemaPPC.h"
58#include "clang/Sema/SemaSYCL.h"
60#include "clang/Sema/SemaWasm.h"
61#include "clang/Sema/Template.h"
62#include "llvm/ADT/ArrayRef.h"
63#include "llvm/ADT/STLForwardCompat.h"
64#include "llvm/ADT/ScopeExit.h"
65#include "llvm/ADT/SmallPtrSet.h"
66#include "llvm/ADT/SmallString.h"
67#include "llvm/ADT/StringExtras.h"
68#include "llvm/ADT/StringRef.h"
69#include "llvm/Support/SaveAndRestore.h"
70#include "llvm/TargetParser/Triple.h"
71#include <algorithm>
72#include <cstring>
73#include <optional>
74#include <unordered_map>
75
76using namespace clang;
77using namespace sema;
78
80 if (OwnedType) {
81 Decl *Group[2] = { OwnedType, Ptr };
83 }
84
86}
87
88namespace {
89
90class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
91 public:
92 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
93 bool AllowTemplates = false,
94 bool AllowNonTemplates = true)
95 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
96 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
97 WantExpressionKeywords = false;
98 WantCXXNamedCasts = false;
99 WantRemainingKeywords = false;
100 }
101
102 bool ValidateCandidate(const TypoCorrection &candidate) override {
103 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
104 if (!AllowInvalidDecl && ND->isInvalidDecl())
105 return false;
106
107 if (getAsTypeTemplateDecl(ND))
108 return AllowTemplates;
109
110 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
111 if (!IsType)
112 return false;
113
114 if (AllowNonTemplates)
115 return true;
116
117 // An injected-class-name of a class template (specialization) is valid
118 // as a template or as a non-template.
119 if (AllowTemplates) {
120 auto *RD = dyn_cast<CXXRecordDecl>(ND);
121 if (!RD || !RD->isInjectedClassName())
122 return false;
123 RD = cast<CXXRecordDecl>(RD->getDeclContext());
124 return RD->getDescribedClassTemplate() ||
126 }
127
128 return false;
129 }
130
131 return !WantClassName && candidate.isKeyword();
132 }
133
134 std::unique_ptr<CorrectionCandidateCallback> clone() override {
135 return std::make_unique<TypeNameValidatorCCC>(*this);
136 }
137
138 private:
139 bool AllowInvalidDecl;
140 bool WantClassName;
141 bool AllowTemplates;
142 bool AllowNonTemplates;
143};
144
145} // end anonymous namespace
146
148 TypeDecl *TD, SourceLocation NameLoc) {
149 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
150 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
151 if (DCK != DiagCtorKind::None && LookupRD && FoundRD &&
152 FoundRD->isInjectedClassName() &&
153 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) {
154 Diag(NameLoc,
156 ? diag::ext_out_of_line_qualified_id_type_names_constructor
157 : diag::err_out_of_line_qualified_id_type_names_constructor)
158 << TD->getIdentifier() << /*Type=*/1
159 << 0 /*if any keyword was present, it was 'typename'*/;
160 }
161
162 DiagnoseUseOfDecl(TD, NameLoc);
163 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
164}
165
166namespace {
167enum class UnqualifiedTypeNameLookupResult {
168 NotFound,
169 FoundNonType,
170 FoundType
171};
172} // end anonymous namespace
173
174/// Tries to perform unqualified lookup of the type decls in bases for
175/// dependent class.
176/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
177/// type decl, \a FoundType if only type decls are found.
178static UnqualifiedTypeNameLookupResult
180 SourceLocation NameLoc,
181 const CXXRecordDecl *RD) {
182 if (!RD->hasDefinition())
183 return UnqualifiedTypeNameLookupResult::NotFound;
184 // Look for type decls in base classes.
185 UnqualifiedTypeNameLookupResult FoundTypeDecl =
186 UnqualifiedTypeNameLookupResult::NotFound;
187 for (const auto &Base : RD->bases()) {
188 const CXXRecordDecl *BaseRD = Base.getType()->getAsCXXRecordDecl();
189 if (BaseRD) {
190 } else if (auto *TST = dyn_cast<TemplateSpecializationType>(
191 Base.getType().getCanonicalType())) {
192 // Look for type decls in dependent base classes that have known primary
193 // templates.
194 if (!TST->isDependentType())
195 continue;
196 auto *TD = TST->getTemplateName().getAsTemplateDecl();
197 if (!TD)
198 continue;
199 if (auto *BasePrimaryTemplate =
200 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
201 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
202 BaseRD = BasePrimaryTemplate;
203 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
205 CTD->findPartialSpecialization(Base.getType()))
206 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
207 BaseRD = PS;
208 }
209 }
210 }
211 if (BaseRD) {
212 for (NamedDecl *ND : BaseRD->lookup(&II)) {
213 if (!isa<TypeDecl>(ND))
214 return UnqualifiedTypeNameLookupResult::FoundNonType;
215 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
216 }
217 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
218 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
219 case UnqualifiedTypeNameLookupResult::FoundNonType:
220 return UnqualifiedTypeNameLookupResult::FoundNonType;
221 case UnqualifiedTypeNameLookupResult::FoundType:
222 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
223 break;
224 case UnqualifiedTypeNameLookupResult::NotFound:
225 break;
226 }
227 }
228 }
229 }
230
231 return FoundTypeDecl;
232}
233
235 const IdentifierInfo &II,
236 SourceLocation NameLoc) {
237 // Lookup in the parent class template context, if any.
238 const CXXRecordDecl *RD = nullptr;
239 UnqualifiedTypeNameLookupResult FoundTypeDecl =
240 UnqualifiedTypeNameLookupResult::NotFound;
241 for (DeclContext *DC = S.CurContext;
242 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
243 DC = DC->getParent()) {
244 // Look for type decls in dependent base classes that have known primary
245 // templates.
246 RD = dyn_cast<CXXRecordDecl>(DC);
247 if (RD && RD->getDescribedClassTemplate())
248 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
249 }
250 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
251 return nullptr;
252
253 // We found some types in dependent base classes. Recover as if the user
254 // wrote 'MyClass::II' instead of 'II', and this implicit typename was
255 // allowed. We'll fully resolve the lookup during template instantiation.
256 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
257
258 ASTContext &Context = S.Context;
259 NestedNameSpecifier NNS(Context.getCanonicalTagType(RD).getTypePtr());
260 QualType T =
261 Context.getDependentNameType(ElaboratedTypeKeyword::None, NNS, &II);
262
263 CXXScopeSpec SS;
264 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
265
266 TypeLocBuilder Builder;
267 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
268 DepTL.setNameLoc(NameLoc);
270 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
271 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
272}
273
275 Scope *S, CXXScopeSpec *SS, bool isClassName,
276 bool HasTrailingDot, ParsedType ObjectTypePtr,
277 bool IsCtorOrDtorName,
278 bool WantNontrivialTypeSourceInfo,
279 bool IsClassTemplateDeductionContext,
280 ImplicitTypenameContext AllowImplicitTypename,
281 IdentifierInfo **CorrectedII) {
282 bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
283 // FIXME: Consider allowing this outside C++1z mode as an extension.
284 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
285 getLangOpts().CPlusPlus17 && IsImplicitTypename &&
286 !HasTrailingDot;
287
288 // Determine where we will perform name lookup.
289 DeclContext *LookupCtx = nullptr;
290 if (ObjectTypePtr) {
291 QualType ObjectType = ObjectTypePtr.get();
292 if (ObjectType->isRecordType())
293 LookupCtx = computeDeclContext(ObjectType);
294 } else if (SS && SS->isNotEmpty()) {
295 LookupCtx = computeDeclContext(*SS, false);
296
297 if (!LookupCtx) {
298 if (isDependentScopeSpecifier(*SS)) {
299 // C++ [temp.res]p3:
300 // A qualified-id that refers to a type and in which the
301 // nested-name-specifier depends on a template-parameter (14.6.2)
302 // shall be prefixed by the keyword typename to indicate that the
303 // qualified-id denotes a type, forming an
304 // elaborated-type-specifier (7.1.5.3).
305 //
306 // We therefore do not perform any name lookup if the result would
307 // refer to a member of an unknown specialization.
308 // In C++2a, in several contexts a 'typename' is not required. Also
309 // allow this as an extension.
310 if (IsImplicitTypename) {
311 if (AllowImplicitTypename == ImplicitTypenameContext::No)
312 return nullptr;
313 SourceLocation QualifiedLoc = SS->getRange().getBegin();
314 // FIXME: Defer the diagnostic after we build the type and use it.
315 auto DB = DiagCompat(QualifiedLoc, diag_compat::implicit_typename)
316 << Context.getDependentNameType(ElaboratedTypeKeyword::None,
317 SS->getScopeRep(), &II);
319 DB << FixItHint::CreateInsertion(QualifiedLoc, "typename ");
320 }
321
322 // We know from the grammar that this name refers to a type,
323 // so build a dependent node to describe the type.
324 if (WantNontrivialTypeSourceInfo)
325 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc,
326 (ImplicitTypenameContext)IsImplicitTypename)
327 .get();
328
331 IsImplicitTypename ? ElaboratedTypeKeyword::Typename
333 SourceLocation(), QualifierLoc, II, NameLoc);
334 return ParsedType::make(T);
335 }
336
337 return nullptr;
338 }
339
340 if (!LookupCtx->isDependentContext() &&
341 RequireCompleteDeclContext(*SS, LookupCtx))
342 return nullptr;
343 }
344
345 // In the case where we know that the identifier is a class name, we know that
346 // it is a type declaration (struct, class, union or enum) so we can use tag
347 // name lookup.
348 //
349 // C++ [class.derived]p2 (wrt lookup in a base-specifier): The lookup for
350 // the component name of the type-name or simple-template-id is type-only.
351 LookupNameKind Kind = isClassName ? LookupTagName : LookupOrdinaryName;
352 LookupResult Result(*this, &II, NameLoc, Kind);
353 if (LookupCtx) {
354 // Perform "qualified" name lookup into the declaration context we
355 // computed, which is either the type of the base of a member access
356 // expression or the declaration context associated with a prior
357 // nested-name-specifier.
358 LookupQualifiedName(Result, LookupCtx);
359
360 if (ObjectTypePtr && Result.empty()) {
361 // C++ [basic.lookup.classref]p3:
362 // If the unqualified-id is ~type-name, the type-name is looked up
363 // in the context of the entire postfix-expression. If the type T of
364 // the object expression is of a class type C, the type-name is also
365 // looked up in the scope of class C. At least one of the lookups shall
366 // find a name that refers to (possibly cv-qualified) T.
367 LookupName(Result, S);
368 }
369 } else {
370 // Perform unqualified name lookup.
371 LookupName(Result, S);
372
373 // For unqualified lookup in a class template in MSVC mode, look into
374 // dependent base classes where the primary class template is known.
375 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
376 if (ParsedType TypeInBase =
377 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
378 return TypeInBase;
379 }
380 }
381
382 NamedDecl *IIDecl = nullptr;
383 UsingShadowDecl *FoundUsingShadow = nullptr;
384 switch (Result.getResultKind()) {
386 if (CorrectedII) {
387 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
388 AllowDeducedTemplate);
389 TypoCorrection Correction =
390 CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS, CCC,
392 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
394 bool MemberOfUnknownSpecialization;
396 TemplateName.setIdentifier(NewII, NameLoc);
398 CXXScopeSpec NewSS, *NewSSPtr = SS;
399 if (SS && NNS) {
400 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
401 NewSSPtr = &NewSS;
402 }
403 if (Correction && (NNS || NewII != &II) &&
404 // Ignore a correction to a template type as the to-be-corrected
405 // identifier is not a template (typo correction for template names
406 // is handled elsewhere).
407 !(getLangOpts().CPlusPlus && NewSSPtr &&
408 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
409 Template, MemberOfUnknownSpecialization))) {
410 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
411 isClassName, HasTrailingDot, ObjectTypePtr,
412 IsCtorOrDtorName,
413 WantNontrivialTypeSourceInfo,
414 IsClassTemplateDeductionContext);
415 if (Ty) {
416 diagnoseTypo(Correction,
417 PDiag(diag::err_unknown_type_or_class_name_suggest)
418 << Result.getLookupName() << isClassName);
419 if (SS && NNS)
420 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
421 *CorrectedII = NewII;
422 return Ty;
423 }
424 }
425 }
426 Result.suppressDiagnostics();
427 return nullptr;
429 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
430 QualType T = Context.getDependentNameType(ElaboratedTypeKeyword::None,
431 SS->getScopeRep(), &II);
432 TypeLocBuilder TLB;
436 TL.setNameLoc(NameLoc);
438 }
439 [[fallthrough]];
442 Result.suppressDiagnostics();
443 return nullptr;
444
446 // Recover from type-hiding ambiguities by hiding the type. We'll
447 // do the lookup again when looking for an object, and we can
448 // diagnose the error then. If we don't do this, then the error
449 // about hiding the type will be immediately followed by an error
450 // that only makes sense if the identifier was treated like a type.
451 if (Result.getAmbiguityKind() == LookupAmbiguityKind::AmbiguousTagHiding) {
452 Result.suppressDiagnostics();
453 return nullptr;
454 }
455
456 // Look to see if we have a type anywhere in the list of results.
457 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
458 Res != ResEnd; ++Res) {
459 NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
461 RealRes) ||
462 (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
463 if (!IIDecl ||
464 // Make the selection of the recovery decl deterministic.
465 RealRes->getLocation() < IIDecl->getLocation()) {
466 IIDecl = RealRes;
467 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
468 }
469 }
470 }
471
472 if (!IIDecl) {
473 // None of the entities we found is a type, so there is no way
474 // to even assume that the result is a type. In this case, don't
475 // complain about the ambiguity. The parser will either try to
476 // perform this lookup again (e.g., as an object name), which
477 // will produce the ambiguity, or will complain that it expected
478 // a type name.
479 Result.suppressDiagnostics();
480 return nullptr;
481 }
482
483 // We found a type within the ambiguous lookup; diagnose the
484 // ambiguity and then return that type. This might be the right
485 // answer, or it might not be, but it suppresses any attempt to
486 // perform the name lookup again.
487 break;
488
490 IIDecl = Result.getFoundDecl();
491 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
492 break;
493 }
494
495 assert(IIDecl && "Didn't find decl");
496
497 TypeLocBuilder TLB;
498 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
499 checkTypeDeclType(LookupCtx,
500 IsImplicitTypename ? DiagCtorKind::Implicit
502 TD, NameLoc);
503 QualType T;
504 if (FoundUsingShadow) {
506 SS ? SS->getScopeRep() : std::nullopt,
507 FoundUsingShadow);
508 if (!WantNontrivialTypeSourceInfo)
509 return ParsedType::make(T);
510 TLB.push<UsingTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),
513 NameLoc);
514 } else if (auto *Tag = dyn_cast<TagDecl>(TD)) {
516 SS ? SS->getScopeRep() : std::nullopt, Tag,
517 /*OwnsTag=*/false);
518 if (!WantNontrivialTypeSourceInfo)
519 return ParsedType::make(T);
520 auto TL = TLB.push<TagTypeLoc>(T);
522 TL.setQualifierLoc(SS ? SS->getWithLocInContext(Context)
524 TL.setNameLoc(NameLoc);
525 } else if (auto *TN = dyn_cast<TypedefNameDecl>(TD);
526 TN && !isa<ObjCTypeParamDecl>(TN)) {
527 T = Context.getTypedefType(ElaboratedTypeKeyword::None,
528 SS ? SS->getScopeRep() : std::nullopt, TN);
529 if (!WantNontrivialTypeSourceInfo)
530 return ParsedType::make(T);
531 TLB.push<TypedefTypeLoc>(T).set(
532 /*ElaboratedKeywordLoc=*/SourceLocation(),
534 NameLoc);
535 } else if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(TD)) {
536 T = Context.getUnresolvedUsingType(ElaboratedTypeKeyword::None,
537 SS ? SS->getScopeRep() : std::nullopt,
538 UD);
539 if (!WantNontrivialTypeSourceInfo)
540 return ParsedType::make(T);
541 TLB.push<UnresolvedUsingTypeLoc>(T).set(
542 /*ElaboratedKeywordLoc=*/SourceLocation(),
544 NameLoc);
545 } else {
546 T = Context.getTypeDeclType(TD);
547 if (!WantNontrivialTypeSourceInfo)
548 return ParsedType::make(T);
550 TLB.push<ObjCTypeParamTypeLoc>(T).setNameLoc(NameLoc);
551 else
552 TLB.pushTypeSpec(T).setNameLoc(NameLoc);
553 }
555 }
556 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
557 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
558 if (!HasTrailingDot) {
559 // FIXME: Support UsingType for this case.
560 QualType T = Context.getObjCInterfaceType(IDecl);
561 if (!WantNontrivialTypeSourceInfo)
562 return ParsedType::make(T);
563 auto TL = TLB.push<ObjCInterfaceTypeLoc>(T);
564 TL.setNameLoc(NameLoc);
565 // FIXME: Pass in this source location.
566 TL.setNameEndLoc(NameLoc);
568 }
569 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
570 (void)DiagnoseUseOfDecl(UD, NameLoc);
571 // Recover with 'int'
572 return ParsedType::make(Context.IntTy);
573 } else if (AllowDeducedTemplate) {
574 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
575 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
576 // FIXME: Support UsingType here.
577 TemplateName Template = Context.getQualifiedTemplateName(
578 SS ? SS->getScopeRep() : std::nullopt, /*TemplateKeyword=*/false,
579 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
580 QualType T = Context.getDeducedTemplateSpecializationType(
584 TL.setNameLoc(NameLoc);
585 TL.setQualifierLoc(SS ? SS->getWithLocInContext(Context)
588 }
589 }
590
591 // As it's not plausibly a type, suppress diagnostics.
592 Result.suppressDiagnostics();
593 return nullptr;
594}
595
596// Builds a fake NNS for the given decl context.
599 for (;; DC = DC->getLookupParent()) {
600 DC = DC->getPrimaryContext();
601 auto *ND = dyn_cast<NamespaceDecl>(DC);
602 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
603 return NestedNameSpecifier(Context, ND, std::nullopt);
604 if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
605 return NestedNameSpecifier(Context.getCanonicalTagType(RD)->getTypePtr());
608 }
609 llvm_unreachable("something isn't in TU scope?");
610}
611
612/// Find the parent class with dependent bases of the innermost enclosing method
613/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
614/// up allowing unqualified dependent type names at class-level, which MSVC
615/// correctly rejects.
616static const CXXRecordDecl *
618 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
619 DC = DC->getPrimaryContext();
620 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
621 if (MD->getParent()->hasAnyDependentBases())
622 return MD->getParent();
623 }
624 return nullptr;
625}
626
628 SourceLocation NameLoc,
629 bool IsTemplateTypeArg) {
630 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
631
632 NestedNameSpecifier NNS = std::nullopt;
633 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
634 // If we weren't able to parse a default template argument, delay lookup
635 // until instantiation time by making a non-dependent DependentTypeName. We
636 // pretend we saw a NestedNameSpecifier referring to the current scope, and
637 // lookup is retried.
638 // FIXME: This hurts our diagnostic quality, since we get errors like "no
639 // type named 'Foo' in 'current_namespace'" when the user didn't write any
640 // name specifiers.
642 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
643 } else if (const CXXRecordDecl *RD =
645 // Build a DependentNameType that will perform lookup into RD at
646 // instantiation time.
647 NNS = NestedNameSpecifier(Context.getCanonicalTagType(RD)->getTypePtr());
648
649 // Diagnose that this identifier was undeclared, and retry the lookup during
650 // template instantiation.
651 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
652 << RD;
653 } else {
654 // This is not a situation that we should recover from.
655 return ParsedType();
656 }
657
658 QualType T =
659 Context.getDependentNameType(ElaboratedTypeKeyword::None, NNS, &II);
660
661 // Build type location information. We synthesized the qualifier, so we have
662 // to build a fake NestedNameSpecifierLoc.
663 NestedNameSpecifierLocBuilder NNSLocBuilder;
664 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
665 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
666
667 TypeLocBuilder Builder;
668 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
669 DepTL.setNameLoc(NameLoc);
671 DepTL.setQualifierLoc(QualifierLoc);
672 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
673}
674
676 // Do a tag name lookup in this scope.
677 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
678 LookupName(R, S, false);
681 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
682 switch (TD->getTagKind()) {
688 return DeclSpec::TST_union;
690 return DeclSpec::TST_class;
692 return DeclSpec::TST_enum;
693 }
694 }
695
697}
698
700 if (!CurContext->isRecord())
701 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
702
703 switch (SS->getScopeRep().getKind()) {
705 return true;
707 QualType T(SS->getScopeRep().getAsType(), 0);
708 for (const auto &Base : cast<CXXRecordDecl>(CurContext)->bases())
709 if (Context.hasSameUnqualifiedType(T, Base.getType()))
710 return true;
711 [[fallthrough]];
712 }
713 default:
714 return S->isFunctionPrototypeScope();
715 }
716}
717
719 SourceLocation IILoc,
720 Scope *S,
721 CXXScopeSpec *SS,
722 ParsedType &SuggestedType,
723 bool IsTemplateName) {
724 // Don't report typename errors for editor placeholders.
725 if (II->isEditorPlaceholder())
726 return;
727 // We don't have anything to suggest (yet).
728 SuggestedType = nullptr;
729
730 // There may have been a typo in the name of the type. Look up typo
731 // results, in case we have something that we can suggest.
732 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
733 /*AllowTemplates=*/IsTemplateName,
734 /*AllowNonTemplates=*/!IsTemplateName);
735 if (TypoCorrection Corrected =
738 // FIXME: Support error recovery for the template-name case.
739 bool CanRecover = !IsTemplateName;
740 if (Corrected.isKeyword()) {
741 // We corrected to a keyword.
742 diagnoseTypo(Corrected,
743 PDiag(IsTemplateName ? diag::err_no_template_suggest
744 : diag::err_unknown_typename_suggest)
745 << II);
746 II = Corrected.getCorrectionAsIdentifierInfo();
747 } else {
748 // We found a similarly-named type or interface; suggest that.
749 if (!SS || !SS->isSet()) {
750 diagnoseTypo(Corrected,
751 PDiag(IsTemplateName ? diag::err_no_template_suggest
752 : diag::err_unknown_typename_suggest)
753 << II, CanRecover);
754 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
755 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
756 bool DroppedSpecifier =
757 Corrected.WillReplaceSpecifier() && II->getName() == CorrectedStr;
758 diagnoseTypo(Corrected,
759 PDiag(IsTemplateName
760 ? diag::err_no_member_template_suggest
761 : diag::err_unknown_nested_typename_suggest)
762 << II << DC << DroppedSpecifier << SS->getRange(),
763 CanRecover);
764 } else {
765 llvm_unreachable("could not have corrected a typo here");
766 }
767
768 if (!CanRecover)
769 return;
770
771 CXXScopeSpec tmpSS;
772 if (Corrected.getCorrectionSpecifier())
773 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
774 SourceRange(IILoc));
775 // FIXME: Support class template argument deduction here.
776 SuggestedType =
777 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
778 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
779 /*IsCtorOrDtorName=*/false,
780 /*WantNontrivialTypeSourceInfo=*/true);
781 }
782 return;
783 }
784
785 if (getLangOpts().CPlusPlus && !IsTemplateName) {
786 // See if II is a class template that the user forgot to pass arguments to.
787 UnqualifiedId Name;
788 Name.setIdentifier(II, IILoc);
789 CXXScopeSpec EmptySS;
790 TemplateTy TemplateResult;
791 bool MemberOfUnknownSpecialization;
792 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
793 Name, nullptr, true, TemplateResult,
794 MemberOfUnknownSpecialization) == TNK_Type_template) {
795 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
796 return;
797 }
798 }
799
800 // FIXME: Should we move the logic that tries to recover from a missing tag
801 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
802
803 if (!SS || (!SS->isSet() && !SS->isInvalid()))
804 Diag(IILoc, IsTemplateName ? diag::err_no_template
805 : diag::err_unknown_typename)
806 << II;
807 else if (DeclContext *DC = computeDeclContext(*SS, false))
808 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
809 : diag::err_typename_nested_not_found)
810 << II << DC << SS->getRange();
811 else if (SS->isValid() && SS->getScopeRep().containsErrors()) {
812 SuggestedType =
813 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
814 } else if (isDependentScopeSpecifier(*SS)) {
815 unsigned DiagID = diag::err_typename_missing;
816 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
817 DiagID = diag::ext_typename_missing;
818
819 SuggestedType =
820 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
821
822 Diag(SS->getRange().getBegin(), DiagID)
823 << GetTypeFromParser(SuggestedType)
824 << SourceRange(SS->getRange().getBegin(), IILoc)
825 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
826 } else {
827 assert(SS && SS->isInvalid() &&
828 "Invalid scope specifier has already been diagnosed");
829 }
830}
831
832/// Determine whether the given result set contains either a type name
833/// or
834static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
835 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
836 NextToken.is(tok::less);
837
838 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
840 return true;
841
842 if (CheckTemplate && isa<TemplateDecl>(*I))
843 return true;
844 }
845
846 return false;
847}
848
849static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
850 Scope *S, CXXScopeSpec &SS,
851 IdentifierInfo *&Name,
852 SourceLocation NameLoc) {
853 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
854 SemaRef.LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
855 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
856 StringRef FixItTagName;
857 switch (Tag->getTagKind()) {
859 FixItTagName = "class ";
860 break;
861
863 FixItTagName = "enum ";
864 break;
865
867 FixItTagName = "struct ";
868 break;
869
871 FixItTagName = "__interface ";
872 break;
873
875 FixItTagName = "union ";
876 break;
877 }
878
879 StringRef TagName = FixItTagName.drop_back();
880 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
881 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
882 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
883
884 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
885 I != IEnd; ++I)
886 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
887 << Name << TagName;
888
889 // Replace lookup results with just the tag decl.
890 Result.clear(Sema::LookupTagName);
891 SemaRef.LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType());
892 return true;
893 }
894
895 return false;
896}
897
899 IdentifierInfo *&Name,
900 SourceLocation NameLoc,
901 const Token &NextToken,
903 DeclarationNameInfo NameInfo(Name, NameLoc);
904 ObjCMethodDecl *CurMethod = getCurMethodDecl();
905
906 assert(NextToken.isNot(tok::coloncolon) &&
907 "parse nested name specifiers before calling ClassifyName");
908 if (getLangOpts().CPlusPlus && SS.isSet() &&
909 isCurrentClassName(*Name, S, &SS)) {
910 // Per [class.qual]p2, this names the constructors of SS, not the
911 // injected-class-name. We don't have a classification for that.
912 // There's not much point caching this result, since the parser
913 // will reject it later.
915 }
916
917 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
918 LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType(),
919 /*AllowBuiltinCreation=*/!CurMethod);
920
921 if (SS.isInvalid())
923
924 // For unqualified lookup in a class template in MSVC mode, look into
925 // dependent base classes where the primary class template is known.
926 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
927 if (ParsedType TypeInBase =
928 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
929 return TypeInBase;
930 }
931
932 // Perform lookup for Objective-C instance variables (including automatically
933 // synthesized instance variables), if we're in an Objective-C method.
934 // FIXME: This lookup really, really needs to be folded in to the normal
935 // unqualified lookup mechanism.
936 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
937 DeclResult Ivar = ObjC().LookupIvarInObjCMethod(Result, S, Name);
938 if (Ivar.isInvalid())
940 if (Ivar.isUsable())
942
943 // We defer builtin creation until after ivar lookup inside ObjC methods.
944 if (Result.empty())
946 }
947
948 bool SecondTry = false;
949 bool IsFilteredTemplateName = false;
950
951Corrected:
952 switch (Result.getResultKind()) {
954 // If an unqualified-id is followed by a '(', then we have a function
955 // call.
956 if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
957 // In C++, this is an ADL-only call.
958 // FIXME: Reference?
961
962 // C90 6.3.2.2:
963 // If the expression that precedes the parenthesized argument list in a
964 // function call consists solely of an identifier, and if no
965 // declaration is visible for this identifier, the identifier is
966 // implicitly declared exactly as if, in the innermost block containing
967 // the function call, the declaration
968 //
969 // extern int identifier ();
970 //
971 // appeared.
972 //
973 // We also allow this in C99 as an extension. However, this is not
974 // allowed in all language modes as functions without prototypes may not
975 // be supported.
976 if (getLangOpts().implicitFunctionsAllowed()) {
977 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
979 }
980 }
981
982 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
983 // In C++20 onwards, this could be an ADL-only call to a function
984 // template, and we're required to assume that this is a template name.
985 //
986 // FIXME: Find a way to still do typo correction in this case.
988 Context.getAssumedTemplateName(NameInfo.getName());
990 }
991
992 // In C, we first see whether there is a tag type by the same name, in
993 // which case it's likely that the user just forgot to write "enum",
994 // "struct", or "union".
995 if (!getLangOpts().CPlusPlus && !SecondTry &&
996 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
997 break;
998 }
999
1000 // Perform typo correction to determine if there is another name that is
1001 // close to this name.
1002 if (!SecondTry && CCC) {
1003 SecondTry = true;
1004 if (TypoCorrection Corrected =
1005 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
1006 &SS, *CCC, CorrectTypoKind::ErrorRecovery)) {
1007 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
1008 unsigned QualifiedDiag = diag::err_no_member_suggest;
1009
1010 NamedDecl *FirstDecl = Corrected.getFoundDecl();
1011 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
1012 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1013 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
1014 UnqualifiedDiag = diag::err_no_template_suggest;
1015 QualifiedDiag = diag::err_no_member_template_suggest;
1016 } else if (UnderlyingFirstDecl &&
1017 (isa<TypeDecl>(UnderlyingFirstDecl) ||
1018 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
1019 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
1020 UnqualifiedDiag = diag::err_unknown_typename_suggest;
1021 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
1022 }
1023
1024 if (SS.isEmpty()) {
1025 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
1026 } else {// FIXME: is this even reachable? Test it.
1027 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1028 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
1029 Name->getName() == CorrectedStr;
1030 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
1031 << Name << computeDeclContext(SS, false)
1032 << DroppedSpecifier << SS.getRange());
1033 }
1034
1035 // Update the name, so that the caller has the new name.
1036 Name = Corrected.getCorrectionAsIdentifierInfo();
1037
1038 // Typo correction corrected to a keyword.
1039 if (Corrected.isKeyword())
1040 return Name;
1041
1042 // Also update the LookupResult...
1043 // FIXME: This should probably go away at some point
1044 Result.clear();
1045 Result.setLookupName(Corrected.getCorrection());
1046 if (FirstDecl)
1047 Result.addDecl(FirstDecl);
1048
1049 // If we found an Objective-C instance variable, let
1050 // LookupInObjCMethod build the appropriate expression to
1051 // reference the ivar.
1052 // FIXME: This is a gross hack.
1053 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1054 DeclResult R =
1055 ObjC().LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1056 if (R.isInvalid())
1058 if (R.isUsable())
1059 return NameClassification::NonType(Ivar);
1060 }
1061
1062 goto Corrected;
1063 }
1064 }
1065
1066 // We failed to correct; just fall through and let the parser deal with it.
1067 Result.suppressDiagnostics();
1069
1071 // We performed name lookup into the current instantiation, and there were
1072 // dependent bases, so we treat this result the same way as any other
1073 // dependent nested-name-specifier.
1074
1075 // C++ [temp.res]p2:
1076 // A name used in a template declaration or definition and that is
1077 // dependent on a template-parameter is assumed not to name a type
1078 // unless the applicable name lookup finds a type name or the name is
1079 // qualified by the keyword typename.
1080 //
1081 // FIXME: If the next token is '<', we might want to ask the parser to
1082 // perform some heroics to see if we actually have a
1083 // template-argument-list, which would indicate a missing 'template'
1084 // keyword here.
1086 }
1087
1091 break;
1092
1094 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1095 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1096 /*AllowDependent=*/false)) {
1097 // C++ [temp.local]p3:
1098 // A lookup that finds an injected-class-name (10.2) can result in an
1099 // ambiguity in certain cases (for example, if it is found in more than
1100 // one base class). If all of the injected-class-names that are found
1101 // refer to specializations of the same class template, and if the name
1102 // is followed by a template-argument-list, the reference refers to the
1103 // class template itself and not a specialization thereof, and is not
1104 // ambiguous.
1105 //
1106 // This filtering can make an ambiguous result into an unambiguous one,
1107 // so try again after filtering out template names.
1109 if (!Result.isAmbiguous()) {
1110 IsFilteredTemplateName = true;
1111 break;
1112 }
1113 }
1114
1115 // Diagnose the ambiguity and return an error.
1117 }
1118
1119 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1120 (IsFilteredTemplateName ||
1122 Result, /*AllowFunctionTemplates=*/true,
1123 /*AllowDependent=*/false,
1124 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1126 // C++ [temp.names]p3:
1127 // After name lookup (3.4) finds that a name is a template-name or that
1128 // an operator-function-id or a literal- operator-id refers to a set of
1129 // overloaded functions any member of which is a function template if
1130 // this is followed by a <, the < is always taken as the delimiter of a
1131 // template-argument-list and never as the less-than operator.
1132 // C++2a [temp.names]p2:
1133 // A name is also considered to refer to a template if it is an
1134 // unqualified-id followed by a < and name lookup finds either one
1135 // or more functions or finds nothing.
1136 if (!IsFilteredTemplateName)
1138
1139 bool IsFunctionTemplate;
1140 bool IsVarTemplate;
1142 if (Result.end() - Result.begin() > 1) {
1143 IsFunctionTemplate = true;
1144 Template = Context.getOverloadedTemplateName(Result.begin(),
1145 Result.end());
1146 } else if (!Result.empty()) {
1148 *Result.begin(), /*AllowFunctionTemplates=*/true,
1149 /*AllowDependent=*/false));
1150 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1151 IsVarTemplate = isa<VarTemplateDecl>(TD);
1152
1153 UsingShadowDecl *FoundUsingShadow =
1154 dyn_cast<UsingShadowDecl>(*Result.begin());
1155 assert(!FoundUsingShadow ||
1156 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1157 Template = Context.getQualifiedTemplateName(
1158 SS.getScopeRep(),
1159 /*TemplateKeyword=*/false,
1160 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
1161 } else {
1162 // All results were non-template functions. This is a function template
1163 // name.
1164 IsFunctionTemplate = true;
1165 Template = Context.getAssumedTemplateName(NameInfo.getName());
1166 }
1167
1168 if (IsFunctionTemplate) {
1169 // Function templates always go through overload resolution, at which
1170 // point we'll perform the various checks (e.g., accessibility) we need
1171 // to based on which function we selected.
1172 Result.suppressDiagnostics();
1173
1175 }
1176
1177 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1179 }
1180
1181 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1182 QualType T;
1183 TypeLocBuilder TLB;
1184 if (const auto *USD = dyn_cast<UsingShadowDecl>(Found)) {
1185 T = Context.getUsingType(ElaboratedTypeKeyword::None, SS.getScopeRep(),
1186 USD);
1187 TLB.push<UsingTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),
1188 SS.getWithLocInContext(Context), NameLoc);
1189 } else {
1190 T = Context.getTypeDeclType(ElaboratedTypeKeyword::None, SS.getScopeRep(),
1191 Type);
1192 if (isa<TagType>(T)) {
1193 auto TTL = TLB.push<TagTypeLoc>(T);
1195 TTL.setQualifierLoc(SS.getWithLocInContext(Context));
1196 TTL.setNameLoc(NameLoc);
1197 } else if (isa<TypedefType>(T)) {
1198 TLB.push<TypedefTypeLoc>(T).set(
1199 /*ElaboratedKeywordLoc=*/SourceLocation(),
1200 SS.getWithLocInContext(Context), NameLoc);
1201 } else if (isa<UnresolvedUsingType>(T)) {
1202 TLB.push<UnresolvedUsingTypeLoc>(T).set(
1203 /*ElaboratedKeywordLoc=*/SourceLocation(),
1204 SS.getWithLocInContext(Context), NameLoc);
1205 } else {
1206 TLB.pushTypeSpec(T).setNameLoc(NameLoc);
1207 }
1208 }
1210 };
1211
1212 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1213 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1214 DiagnoseUseOfDecl(Type, NameLoc);
1215 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1216 return BuildTypeFor(Type, *Result.begin());
1217 }
1218
1219 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1220 if (!Class) {
1221 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1222 if (ObjCCompatibleAliasDecl *Alias =
1223 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1224 Class = Alias->getClassInterface();
1225 }
1226
1227 if (Class) {
1228 DiagnoseUseOfDecl(Class, NameLoc);
1229
1230 if (NextToken.is(tok::period)) {
1231 // Interface. <something> is parsed as a property reference expression.
1232 // Just return "unknown" as a fall-through for now.
1233 Result.suppressDiagnostics();
1235 }
1236
1237 QualType T = Context.getObjCInterfaceType(Class);
1238 return ParsedType::make(T);
1239 }
1240
1242 // We want to preserve the UsingShadowDecl for concepts.
1243 if (auto *USD = dyn_cast<UsingShadowDecl>(Result.getRepresentativeDecl()))
1247 }
1248
1249 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1250 (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1252 }
1253
1254 // We can have a type template here if we're classifying a template argument.
1259
1260 // Check for a tag type hidden by a non-type decl in a few cases where it
1261 // seems likely a type is wanted instead of the non-type that was found.
1262 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1263 if ((NextToken.is(tok::identifier) ||
1264 (NextIsOp &&
1265 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1266 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1267 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1268 DiagnoseUseOfDecl(Type, NameLoc);
1269 return BuildTypeFor(Type, *Result.begin());
1270 }
1271
1272 // If we already know which single declaration is referenced, just annotate
1273 // that declaration directly. Defer resolving even non-overloaded class
1274 // member accesses, as we need to defer certain access checks until we know
1275 // the context.
1276 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1277 if (Result.isSingleResult() && !ADL &&
1278 (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(FirstDecl)))
1279 return NameClassification::NonType(Result.getRepresentativeDecl());
1280
1281 // Otherwise, this is an overload set that we will need to resolve later.
1282 Result.suppressDiagnostics();
1284 Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1285 Result.getLookupNameInfo(), ADL, Result.begin(), Result.end(),
1286 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false));
1287}
1288
1291 SourceLocation NameLoc) {
1292 assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1293 CXXScopeSpec SS;
1294 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1295 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1296}
1297
1300 IdentifierInfo *Name,
1301 SourceLocation NameLoc,
1302 bool IsAddressOfOperand) {
1303 DeclarationNameInfo NameInfo(Name, NameLoc);
1304 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1305 NameInfo, IsAddressOfOperand,
1306 /*TemplateArgs=*/nullptr);
1307}
1308
1311 SourceLocation NameLoc,
1312 const Token &NextToken) {
1313 if (getCurMethodDecl() && SS.isEmpty())
1314 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1315 return ObjC().BuildIvarRefExpr(S, NameLoc, Ivar);
1316
1317 // Reconstruct the lookup result.
1318 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1319 Result.addDecl(Found);
1320 Result.resolveKind();
1321
1322 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1323 return BuildDeclarationNameExpr(SS, Result, ADL, /*AcceptInvalidDecl=*/true);
1324}
1325
1327 // For an implicit class member access, transform the result into a member
1328 // access expression if necessary.
1329 auto *ULE = cast<UnresolvedLookupExpr>(E);
1330 if ((*ULE->decls_begin())->isCXXClassMember()) {
1331 CXXScopeSpec SS;
1332 SS.Adopt(ULE->getQualifierLoc());
1333
1334 // Reconstruct the lookup result.
1335 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1337 Result.setNamingClass(ULE->getNamingClass());
1338 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1339 Result.addDecl(*I, I.getAccess());
1340 Result.resolveKind();
1342 nullptr, S);
1343 }
1344
1345 // Otherwise, this is already in the form we needed, and no further checks
1346 // are necessary.
1347 return ULE;
1348}
1349
1369
1371 assert(DC->getLexicalParent() == CurContext &&
1372 "The next DeclContext should be lexically contained in the current one.");
1373 CurContext = DC;
1374 S->setEntity(DC);
1375}
1376
1378 assert(CurContext && "DeclContext imbalance!");
1379
1380 CurContext = CurContext->getLexicalParent();
1381 assert(CurContext && "Popped translation unit!");
1382}
1383
1385 Decl *D) {
1386 // Unlike PushDeclContext, the context to which we return is not necessarily
1387 // the containing DC of TD, because the new context will be some pre-existing
1388 // TagDecl definition instead of a fresh one.
1389 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1390 CurContext = cast<TagDecl>(D)->getDefinition();
1391 assert(CurContext && "skipping definition of undefined tag");
1392 // Start lookups from the parent of the current context; we don't want to look
1393 // into the pre-existing complete definition.
1394 S->setEntity(CurContext->getLookupParent());
1395 return Result;
1396}
1397
1401
1403 // C++0x [basic.lookup.unqual]p13:
1404 // A name used in the definition of a static data member of class
1405 // X (after the qualified-id of the static member) is looked up as
1406 // if the name was used in a member function of X.
1407 // C++0x [basic.lookup.unqual]p14:
1408 // If a variable member of a namespace is defined outside of the
1409 // scope of its namespace then any name used in the definition of
1410 // the variable member (after the declarator-id) is looked up as
1411 // if the definition of the variable member occurred in its
1412 // namespace.
1413 // Both of these imply that we should push a scope whose context
1414 // is the semantic context of the declaration. We can't use
1415 // PushDeclContext here because that context is not necessarily
1416 // lexically contained in the current context. Fortunately,
1417 // the containing scope should have the appropriate information.
1418
1419 assert(!S->getEntity() && "scope already has entity");
1420
1421#ifndef NDEBUG
1422 Scope *Ancestor = S->getParent();
1423 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1424 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1425#endif
1426
1427 CurContext = DC;
1428 S->setEntity(DC);
1429
1430 if (S->getParent()->isTemplateParamScope()) {
1431 // Also set the corresponding entities for all immediately-enclosing
1432 // template parameter scopes.
1434 }
1435}
1436
1438 assert(S->getEntity() == CurContext && "Context imbalance!");
1439
1440 // Switch back to the lexical context. The safety of this is
1441 // enforced by an assert in EnterDeclaratorContext.
1442 Scope *Ancestor = S->getParent();
1443 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1444 CurContext = Ancestor->getEntity();
1445
1446 // We don't need to do anything with the scope, which is going to
1447 // disappear.
1448}
1449
1451 assert(S->isTemplateParamScope() &&
1452 "expected to be initializing a template parameter scope");
1453
1454 // C++20 [temp.local]p7:
1455 // In the definition of a member of a class template that appears outside
1456 // of the class template definition, the name of a member of the class
1457 // template hides the name of a template-parameter of any enclosing class
1458 // templates (but not a template-parameter of the member if the member is a
1459 // class or function template).
1460 // C++20 [temp.local]p9:
1461 // In the definition of a class template or in the definition of a member
1462 // of such a template that appears outside of the template definition, for
1463 // each non-dependent base class (13.8.2.1), if the name of the base class
1464 // or the name of a member of the base class is the same as the name of a
1465 // template-parameter, the base class name or member name hides the
1466 // template-parameter name (6.4.10).
1467 //
1468 // This means that a template parameter scope should be searched immediately
1469 // after searching the DeclContext for which it is a template parameter
1470 // scope. For example, for
1471 // template<typename T> template<typename U> template<typename V>
1472 // void N::A<T>::B<U>::f(...)
1473 // we search V then B<U> (and base classes) then U then A<T> (and base
1474 // classes) then T then N then ::.
1475 unsigned ScopeDepth = getTemplateDepth(S);
1476 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1477 DeclContext *SearchDCAfterScope = DC;
1478 for (; DC; DC = DC->getLookupParent()) {
1479 if (const TemplateParameterList *TPL =
1480 cast<Decl>(DC)->getDescribedTemplateParams()) {
1481 unsigned DCDepth = TPL->getDepth() + 1;
1482 if (DCDepth > ScopeDepth)
1483 continue;
1484 if (ScopeDepth == DCDepth)
1485 SearchDCAfterScope = DC = DC->getLookupParent();
1486 break;
1487 }
1488 }
1489 S->setLookupEntity(SearchDCAfterScope);
1490 }
1491}
1492
1494 // We assume that the caller has already called
1495 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1496 FunctionDecl *FD = D->getAsFunction();
1497 if (!FD)
1498 return;
1499
1500 // Same implementation as PushDeclContext, but enters the context
1501 // from the lexical parent, rather than the top-level class.
1502 assert(CurContext == FD->getLexicalParent() &&
1503 "The next DeclContext should be lexically contained in the current one.");
1504 CurContext = FD;
1506
1507 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1508 ParmVarDecl *Param = FD->getParamDecl(P);
1509 // If the parameter has an identifier, then add it to the scope
1510 if (Param->getIdentifier()) {
1511 S->AddDecl(Param);
1512 IdResolver.AddDecl(Param);
1513 }
1514 }
1515}
1516
1518 // Same implementation as PopDeclContext, but returns to the lexical parent,
1519 // rather than the top-level class.
1520 assert(CurContext && "DeclContext imbalance!");
1521 CurContext = CurContext->getLexicalParent();
1522 assert(CurContext && "Popped translation unit!");
1523}
1524
1525/// Determine whether overloading is allowed for a new function
1526/// declaration considering prior declarations of the same name.
1527///
1528/// This routine determines whether overloading is possible, not
1529/// whether a new declaration actually overloads a previous one.
1530/// It will return true in C++ (where overloads are always permitted)
1531/// or, as a C extension, when either the new declaration or a
1532/// previous one is declared with the 'overloadable' attribute.
1534 ASTContext &Context,
1535 const FunctionDecl *New) {
1536 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1537 return true;
1538
1539 // Multiversion function declarations are not overloads in the
1540 // usual sense of that term, but lookup will report that an
1541 // overload set was found if more than one multiversion function
1542 // declaration is present for the same name. It is therefore
1543 // inadequate to assume that some prior declaration(s) had
1544 // the overloadable attribute; checking is required. Since one
1545 // declaration is permitted to omit the attribute, it is necessary
1546 // to check at least two; hence the 'any_of' check below. Note that
1547 // the overloadable attribute is implicitly added to declarations
1548 // that were required to have it but did not.
1549 if (Previous.getResultKind() == LookupResultKind::FoundOverloaded) {
1550 return llvm::any_of(Previous, [](const NamedDecl *ND) {
1551 return ND->hasAttr<OverloadableAttr>();
1552 });
1553 } else if (Previous.getResultKind() == LookupResultKind::Found)
1554 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1555
1556 return false;
1557}
1558
1559void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1560 // Move up the scope chain until we find the nearest enclosing
1561 // non-transparent context. The declaration will be introduced into this
1562 // scope.
1563 while (S->getEntity() && S->getEntity()->isTransparentContext())
1564 S = S->getParent();
1565
1566 // Add scoped declarations into their context, so that they can be
1567 // found later. Declarations without a context won't be inserted
1568 // into any context.
1569 if (AddToContext)
1570 CurContext->addDecl(D);
1571
1572 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1573 // are function-local declarations.
1574 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1575 return;
1576
1577 // Template instantiations should also not be pushed into scope.
1578 if (isa<FunctionDecl>(D) &&
1579 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1580 return;
1581
1582 if (isa<UsingEnumDecl>(D) && D->getDeclName().isEmpty()) {
1583 S->AddDecl(D);
1584 return;
1585 }
1586 // If this replaces anything in the current scope,
1588 IEnd = IdResolver.end();
1589 for (; I != IEnd; ++I) {
1590 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1591 S->RemoveDecl(*I);
1592 IdResolver.RemoveDecl(*I);
1593
1594 // Should only need to replace one decl.
1595 break;
1596 }
1597 }
1598
1599 S->AddDecl(D);
1600
1601 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1602 // Implicitly-generated labels may end up getting generated in an order that
1603 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1604 // the label at the appropriate place in the identifier chain.
1605 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1606 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1607 if (IDC == CurContext) {
1608 if (!S->isDeclScope(*I))
1609 continue;
1610 } else if (IDC->Encloses(CurContext))
1611 break;
1612 }
1613
1614 IdResolver.InsertDeclAfter(I, D);
1615 } else {
1616 IdResolver.AddDecl(D);
1617 }
1619}
1620
1622 bool AllowInlineNamespace) const {
1623 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1624}
1625
1627 DeclContext *TargetDC = DC->getPrimaryContext();
1628 do {
1629 if (DeclContext *ScopeDC = S->getEntity())
1630 if (ScopeDC->getPrimaryContext() == TargetDC)
1631 return S;
1632 } while ((S = S->getParent()));
1633
1634 return nullptr;
1635}
1636
1638 DeclContext*,
1639 ASTContext&);
1640
1642 bool ConsiderLinkage,
1643 bool AllowInlineNamespace) {
1645 while (F.hasNext()) {
1646 NamedDecl *D = F.next();
1647
1648 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1649 continue;
1650
1651 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1652 continue;
1653
1654 F.erase();
1655 }
1656
1657 F.done();
1658}
1659
1661 if (auto *VD = dyn_cast<VarDecl>(D))
1662 return VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1663 if (auto *FD = dyn_cast<FunctionDecl>(D))
1664 return FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1665 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1666 return RD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1667
1668 return false;
1669}
1670
1672 // [module.interface]p7:
1673 // A declaration is attached to a module as follows:
1674 // - If the declaration is a non-dependent friend declaration that nominates a
1675 // function with a declarator-id that is a qualified-id or template-id or that
1676 // nominates a class other than with an elaborated-type-specifier with neither
1677 // a nested-name-specifier nor a simple-template-id, it is attached to the
1678 // module to which the friend is attached ([basic.link]).
1679 if (New->getFriendObjectKind() &&
1680 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1681 New->setLocalOwningModule(Old->getOwningModule());
1683 return false;
1684 }
1685
1686 // Although we have questions for the module ownership of implicit
1687 // instantiations, it should be sure that we shouldn't diagnose the
1688 // redeclaration of incorrect module ownership for different implicit
1689 // instantiations in different modules. We will diagnose the redeclaration of
1690 // incorrect module ownership for the template itself.
1692 return false;
1693
1694 Module *NewM = New->getOwningModule();
1695 Module *OldM = Old->getOwningModule();
1696
1697 if (NewM && NewM->isPrivateModule())
1698 NewM = NewM->Parent;
1699 if (OldM && OldM->isPrivateModule())
1700 OldM = OldM->Parent;
1701
1702 if (NewM == OldM)
1703 return false;
1704
1705 if (NewM && OldM) {
1706 // A module implementation unit has visibility of the decls in its
1707 // implicitly imported interface.
1708 if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1709 return false;
1710
1711 // Partitions are part of the module, but a partition could import another
1712 // module, so verify that the PMIs agree.
1713 if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1714 getASTContext().isInSameModule(NewM, OldM))
1715 return false;
1716 }
1717
1718 bool NewIsModuleInterface = NewM && NewM->isNamedModule();
1719 bool OldIsModuleInterface = OldM && OldM->isNamedModule();
1720 if (NewIsModuleInterface || OldIsModuleInterface) {
1721 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1722 // if a declaration of D [...] appears in the purview of a module, all
1723 // other such declarations shall appear in the purview of the same module
1724 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1725 << New
1726 << NewIsModuleInterface
1727 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1728 << OldIsModuleInterface
1729 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1730 Diag(Old->getLocation(), diag::note_previous_declaration);
1731 New->setInvalidDecl();
1732 return true;
1733 }
1734
1735 return false;
1736}
1737
1739 // [module.interface]p1:
1740 // An export-declaration shall inhabit a namespace scope.
1741 //
1742 // So it is meaningless to talk about redeclaration which is not at namespace
1743 // scope.
1744 if (!New->getLexicalDeclContext()
1745 ->getNonTransparentContext()
1746 ->isFileContext() ||
1747 !Old->getLexicalDeclContext()
1749 ->isFileContext())
1750 return false;
1751
1752 bool IsNewExported = New->isInExportDeclContext();
1753 bool IsOldExported = Old->isInExportDeclContext();
1754
1755 // It should be irrevelant if both of them are not exported.
1756 if (!IsNewExported && !IsOldExported)
1757 return false;
1758
1759 if (IsOldExported)
1760 return false;
1761
1762 // If the Old declaration are not attached to named modules
1763 // and the New declaration are attached to global module.
1764 // It should be fine to allow the export since it doesn't change
1765 // the linkage of declarations. See
1766 // https://github.com/llvm/llvm-project/issues/98583 for details.
1767 if (!Old->isInNamedModule() && New->getOwningModule() &&
1768 New->getOwningModule()->isImplicitGlobalModule())
1769 return false;
1770
1771 assert(IsNewExported);
1772
1773 auto Lk = Old->getFormalLinkage();
1774 int S = 0;
1775 if (Lk == Linkage::Internal)
1776 S = 1;
1777 else if (Lk == Linkage::Module)
1778 S = 2;
1779 Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1780 Diag(Old->getLocation(), diag::note_previous_declaration);
1781 return true;
1782}
1783
1786 return true;
1787
1789 return true;
1790
1791 return false;
1792}
1793
1795 const NamedDecl *Old) const {
1796 assert(getASTContext().isSameEntity(New, Old) &&
1797 "New and Old are not the same definition, we should diagnostic it "
1798 "immediately instead of checking it.");
1799 assert(const_cast<Sema *>(this)->isReachable(New) &&
1800 const_cast<Sema *>(this)->isReachable(Old) &&
1801 "We shouldn't see unreachable definitions here.");
1802
1803 Module *NewM = New->getOwningModule();
1804 Module *OldM = Old->getOwningModule();
1805
1806 // We only checks for named modules here. The header like modules is skipped.
1807 // FIXME: This is not right if we import the header like modules in the module
1808 // purview.
1809 //
1810 // For example, assuming "header.h" provides definition for `D`.
1811 // ```C++
1812 // //--- M.cppm
1813 // export module M;
1814 // import "header.h"; // or #include "header.h" but import it by clang modules
1815 // actually.
1816 //
1817 // //--- Use.cpp
1818 // import M;
1819 // import "header.h"; // or uses clang modules.
1820 // ```
1821 //
1822 // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1823 // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1824 // reject it. But the current implementation couldn't detect the case since we
1825 // don't record the information about the importee modules.
1826 //
1827 // But this might not be painful in practice. Since the design of C++20 Named
1828 // Modules suggests us to use headers in global module fragment instead of
1829 // module purview.
1830 if (NewM && NewM->isHeaderLikeModule())
1831 NewM = nullptr;
1832 if (OldM && OldM->isHeaderLikeModule())
1833 OldM = nullptr;
1834
1835 if (!NewM && !OldM)
1836 return true;
1837
1838 // [basic.def.odr]p14.3
1839 // Each such definition shall not be attached to a named module
1840 // ([module.unit]).
1841 if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule()))
1842 return true;
1843
1844 // Then New and Old lives in the same TU if their share one same module unit.
1845 if (NewM)
1846 NewM = NewM->getTopLevelModule();
1847 if (OldM)
1848 OldM = OldM->getTopLevelModule();
1849 return OldM == NewM;
1850}
1851
1853 if (D->getDeclContext()->isFileContext())
1854 return false;
1855
1856 return isa<UsingShadowDecl>(D) ||
1859}
1860
1861/// Removes using shadow declarations not at class scope from the lookup
1862/// results.
1865 while (F.hasNext())
1867 F.erase();
1868
1869 F.done();
1870}
1871
1872/// Check for this common pattern:
1873/// @code
1874/// class S {
1875/// S(const S&); // DO NOT IMPLEMENT
1876/// void operator=(const S&); // DO NOT IMPLEMENT
1877/// };
1878/// @endcode
1880 // FIXME: Should check for private access too but access is set after we get
1881 // the decl here.
1883 return false;
1884
1885 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1886 return CD->isCopyConstructor();
1887 return D->isCopyAssignmentOperator();
1888}
1889
1890bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1891 const DeclContext *DC = D->getDeclContext();
1892 while (!DC->isTranslationUnit()) {
1893 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1894 if (!RD->hasNameForLinkage())
1895 return true;
1896 }
1897 DC = DC->getParent();
1898 }
1899
1900 return !D->isExternallyVisible();
1901}
1902
1903// FIXME: This needs to be refactored; some other isInMainFile users want
1904// these semantics.
1905static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1907 return false;
1908 return S.SourceMgr.isInMainFile(Loc);
1909}
1910
1912 assert(D);
1913
1914 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1915 return false;
1916
1917 // Ignore all entities declared within templates, and out-of-line definitions
1918 // of members of class templates.
1919 if (D->getDeclContext()->isDependentContext() ||
1921 return false;
1922
1923 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1924 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1925 return false;
1926 // A non-out-of-line declaration of a member specialization was implicitly
1927 // instantiated; it's the out-of-line declaration that we're interested in.
1928 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1929 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1930 return false;
1931
1932 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1933 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1934 return false;
1935 } else {
1936 // 'static inline' functions are defined in headers; don't warn.
1937 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1938 return false;
1939 }
1940
1941 if (FD->doesThisDeclarationHaveABody() &&
1942 Context.DeclMustBeEmitted(FD))
1943 return false;
1944 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1945 // Constants and utility variables are defined in headers with internal
1946 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1947 // like "inline".)
1948 if (!isMainFileLoc(*this, VD->getLocation()))
1949 return false;
1950
1951 if (Context.DeclMustBeEmitted(VD))
1952 return false;
1953
1954 if (VD->isStaticDataMember() &&
1955 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1956 return false;
1957 if (VD->isStaticDataMember() &&
1958 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1959 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1960 return false;
1961
1962 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1963 return false;
1964 } else {
1965 return false;
1966 }
1967
1968 // Only warn for unused decls internal to the translation unit.
1969 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1970 // for inline functions defined in the main source file, for instance.
1971 return mightHaveNonExternalLinkage(D);
1972}
1973
1975 if (!D)
1976 return;
1977
1978 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1979 const FunctionDecl *First = FD->getFirstDecl();
1981 return; // First should already be in the vector.
1982 }
1983
1984 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1985 const VarDecl *First = VD->getFirstDecl();
1987 return; // First should already be in the vector.
1988 }
1989
1991 UnusedFileScopedDecls.push_back(D);
1992}
1993
1994static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts,
1995 const NamedDecl *D) {
1996 if (D->isInvalidDecl())
1997 return false;
1998
1999 if (const auto *DD = dyn_cast<DecompositionDecl>(D)) {
2000 // For a decomposition declaration, warn if none of the bindings are
2001 // referenced, instead of if the variable itself is referenced (which
2002 // it is, by the bindings' expressions).
2003 bool IsAllIgnored = true;
2004 for (const auto *BD : DD->bindings()) {
2005 if (BD->isReferenced())
2006 return false;
2007 IsAllIgnored = IsAllIgnored && (BD->isPlaceholderVar(LangOpts) ||
2008 BD->hasAttr<UnusedAttr>());
2009 }
2010 if (IsAllIgnored)
2011 return false;
2012 } else if (!D->getDeclName()) {
2013 return false;
2014 } else if (D->isReferenced() || D->isUsed()) {
2015 return false;
2016 }
2017
2018 if (D->isPlaceholderVar(LangOpts))
2019 return false;
2020
2021 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||
2022 D->hasAttr<CleanupAttr>())
2023 return false;
2024
2025 if (isa<LabelDecl>(D))
2026 return true;
2027
2028 // Except for labels, we only care about unused decls that are local to
2029 // functions.
2030 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
2031 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
2032 // For dependent types, the diagnostic is deferred.
2033 WithinFunction =
2034 WithinFunction || (R->isLocalClass() && !R->isDependentType());
2035 if (!WithinFunction)
2036 return false;
2037
2038 if (isa<TypedefNameDecl>(D))
2039 return true;
2040
2041 // White-list anything that isn't a local variable.
2043 return false;
2044
2045 // Types of valid local variables should be complete, so this should succeed.
2046 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2047
2048 const Expr *Init = VD->getInit();
2049 if (const auto *Cleanups = dyn_cast_if_present<ExprWithCleanups>(Init))
2050 Init = Cleanups->getSubExpr();
2051
2052 const auto *Ty = VD->getType().getTypePtr();
2053
2054 // Only look at the outermost level of typedef.
2055 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
2056 // Allow anything marked with __attribute__((unused)).
2057 if (TT->getDecl()->hasAttr<UnusedAttr>())
2058 return false;
2059 }
2060
2061 // Warn for reference variables whose initializtion performs lifetime
2062 // extension.
2063 if (const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(Init);
2064 MTE && MTE->getExtendingDecl()) {
2065 Ty = VD->getType().getNonReferenceType().getTypePtr();
2066 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
2067 }
2068
2069 // If we failed to complete the type for some reason, or if the type is
2070 // dependent, don't diagnose the variable.
2071 if (Ty->isIncompleteType() || Ty->isDependentType())
2072 return false;
2073
2074 // Look at the element type to ensure that the warning behaviour is
2075 // consistent for both scalars and arrays.
2076 Ty = Ty->getBaseElementTypeUnsafe();
2077
2078 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2079 if (Tag->hasAttr<UnusedAttr>())
2080 return false;
2081
2082 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2083 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2084 return false;
2085
2086 if (Init) {
2087 const auto *Construct =
2088 dyn_cast<CXXConstructExpr>(Init->IgnoreImpCasts());
2089 if (Construct && !Construct->isElidable()) {
2090 const CXXConstructorDecl *CD = Construct->getConstructor();
2091 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2092 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2093 return false;
2094 }
2095
2096 // Suppress the warning if we don't know how this is constructed, and
2097 // it could possibly be non-trivial constructor.
2098 if (Init->isTypeDependent()) {
2099 for (const CXXConstructorDecl *Ctor : RD->ctors())
2100 if (!Ctor->isTrivial())
2101 return false;
2102 }
2103
2104 // Suppress the warning if the constructor is unresolved because
2105 // its arguments are dependent.
2107 return false;
2108 }
2109 }
2110 }
2111
2112 // TODO: __attribute__((unused)) templates?
2113 }
2114
2115 return true;
2116}
2117
2119 FixItHint &Hint) {
2120 if (isa<LabelDecl>(D)) {
2122 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
2123 /*SkipTrailingWhitespaceAndNewline=*/false);
2124 if (AfterColon.isInvalid())
2125 return;
2127 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
2128 }
2129}
2130
2133 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2134}
2135
2137 DiagReceiverTy DiagReceiver) {
2138 if (D->isDependentType())
2139 return;
2140
2141 for (auto *TmpD : D->decls()) {
2142 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2143 DiagnoseUnusedDecl(T, DiagReceiver);
2144 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2145 DiagnoseUnusedNestedTypedefs(R, DiagReceiver);
2146 }
2147}
2148
2151 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2152}
2153
2156 return;
2157
2158 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2159 // typedefs can be referenced later on, so the diagnostics are emitted
2160 // at end-of-translation-unit.
2162 return;
2163 }
2164
2165 FixItHint Hint;
2167
2168 unsigned DiagID;
2169 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2170 DiagID = diag::warn_unused_exception_param;
2171 else if (isa<LabelDecl>(D))
2172 DiagID = diag::warn_unused_label;
2173 else
2174 DiagID = diag::warn_unused_variable;
2175
2176 SourceLocation DiagLoc = D->getLocation();
2177 DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
2178}
2179
2181 DiagReceiverTy DiagReceiver) {
2182 // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2183 // it's not really unused.
2184 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>())
2185 return;
2186
2187 // In C++, `_` variables behave as if they were maybe_unused
2188 if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(getLangOpts()))
2189 return;
2190
2191 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2192
2193 if (Ty->isReferenceType() || Ty->isDependentType())
2194 return;
2195
2196 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2197 if (Tag->hasAttr<UnusedAttr>())
2198 return;
2199 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2200 // mimic gcc's behavior.
2201 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag);
2202 RD && !RD->hasAttr<WarnUnusedAttr>())
2203 return;
2204 }
2205
2206 // Don't warn about __block Objective-C pointer variables, as they might
2207 // be assigned in the block but not used elsewhere for the purpose of lifetime
2208 // extension.
2209 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2210 return;
2211
2212 // Don't warn about Objective-C pointer variables with precise lifetime
2213 // semantics; they can be used to ensure ARC releases the object at a known
2214 // time, which may mean assignment but no other references.
2215 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2216 return;
2217
2218 auto iter = RefsMinusAssignments.find(VD);
2219 if (iter == RefsMinusAssignments.end())
2220 return;
2221
2222 assert(iter->getSecond() >= 0 &&
2223 "Found a negative number of references to a VarDecl");
2224 if (int RefCnt = iter->getSecond(); RefCnt > 0) {
2225 // Assume the given VarDecl is "used" if its ref count stored in
2226 // `RefMinusAssignments` is positive, with one exception.
2227 //
2228 // For a C++ variable whose decl (with initializer) entirely consist the
2229 // condition expression of a if/while/for construct,
2230 // Clang creates a DeclRefExpr for the condition expression rather than a
2231 // BinaryOperator of AssignmentOp. Thus, the C++ variable's ref
2232 // count stored in `RefMinusAssignment` equals 1 when the variable is never
2233 // used in the body of the if/while/for construct.
2234 bool UnusedCXXCondDecl = VD->isCXXCondDecl() && (RefCnt == 1);
2235 if (!UnusedCXXCondDecl)
2236 return;
2237 }
2238
2239 unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2240 : diag::warn_unused_but_set_variable;
2241 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2242}
2243
2245 Sema::DiagReceiverTy DiagReceiver) {
2246 // Verify that we have no forward references left. If so, there was a goto
2247 // or address of a label taken, but no definition of it. Label fwd
2248 // definitions are indicated with a null substmt which is also not a resolved
2249 // MS inline assembly label name.
2250 bool Diagnose = false;
2251 if (L->isMSAsmLabel())
2252 Diagnose = !L->isResolvedMSAsmLabel();
2253 else
2254 Diagnose = L->getStmt() == nullptr;
2255 if (Diagnose)
2256 DiagReceiver(L->getLocation(), S.PDiag(diag::err_undeclared_label_use)
2257 << L);
2258}
2259
2261 S->applyNRVO();
2262
2263 if (S->decl_empty()) return;
2265 "Scope shouldn't contain decls!");
2266
2267 /// We visit the decls in non-deterministic order, but we want diagnostics
2268 /// emitted in deterministic order. Collect any diagnostic that may be emitted
2269 /// and sort the diagnostics before emitting them, after we visited all decls.
2270 struct LocAndDiag {
2271 SourceLocation Loc;
2272 std::optional<SourceLocation> PreviousDeclLoc;
2274 };
2276 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2277 DeclDiags.push_back(LocAndDiag{Loc, std::nullopt, std::move(PD)});
2278 };
2279 auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2280 SourceLocation PreviousDeclLoc,
2281 PartialDiagnostic PD) {
2282 DeclDiags.push_back(LocAndDiag{Loc, PreviousDeclLoc, std::move(PD)});
2283 };
2284
2285 for (auto *TmpD : S->decls()) {
2286 assert(TmpD && "This decl didn't get pushed??");
2287
2288 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2289 NamedDecl *D = cast<NamedDecl>(TmpD);
2290
2291 // Diagnose unused variables in this scope.
2293 DiagnoseUnusedDecl(D, addDiag);
2294 if (const auto *RD = dyn_cast<RecordDecl>(D))
2295 DiagnoseUnusedNestedTypedefs(RD, addDiag);
2296 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2297 DiagnoseUnusedButSetDecl(VD, addDiag);
2298 RefsMinusAssignments.erase(VD);
2299 }
2300 }
2301
2302 if (!D->getDeclName()) continue;
2303
2304 // If this was a forward reference to a label, verify it was defined.
2305 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2306 CheckPoppedLabel(LD, *this, addDiag);
2307
2308 // Partial translation units that are created in incremental processing must
2309 // not clean up the IdResolver because PTUs should take into account the
2310 // declarations that came from previous PTUs.
2311 if (!PP.isIncrementalProcessingEnabled() || getLangOpts().ObjC ||
2313 IdResolver.RemoveDecl(D);
2314
2315 // Warn on it if we are shadowing a declaration.
2316 auto ShadowI = ShadowingDecls.find(D);
2317 if (ShadowI != ShadowingDecls.end()) {
2318 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2319 addDiagWithPrev(D->getLocation(), FD->getLocation(),
2320 PDiag(diag::warn_ctor_parm_shadows_field)
2321 << D << FD << FD->getParent());
2322 }
2323 ShadowingDecls.erase(ShadowI);
2324 }
2325 }
2326
2327 llvm::sort(DeclDiags,
2328 [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2329 // The particular order for diagnostics is not important, as long
2330 // as the order is deterministic. Using the raw location is going
2331 // to generally be in source order unless there are macro
2332 // expansions involved.
2333 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2334 });
2335 for (const LocAndDiag &D : DeclDiags) {
2336 Diag(D.Loc, D.PD);
2337 if (D.PreviousDeclLoc)
2338 Diag(*D.PreviousDeclLoc, diag::note_previous_declaration);
2339 }
2340}
2341
2343 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2344 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2345 (S->isClassScope() && !getLangOpts().CPlusPlus))
2346 S = S->getParent();
2347 return S;
2348}
2349
2350static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2352 switch (Error) {
2354 return "";
2356 return BuiltinInfo.getHeaderName(ID);
2358 return "stdio.h";
2360 return "setjmp.h";
2362 return "ucontext.h";
2363 }
2364 llvm_unreachable("unhandled error kind");
2365}
2366
2368 unsigned ID, SourceLocation Loc) {
2369 DeclContext *Parent = Context.getTranslationUnitDecl();
2370
2371 if (getLangOpts().CPlusPlus) {
2373 Context, Parent, Loc, Loc, LinkageSpecLanguageIDs::C, false);
2374 CLinkageDecl->setImplicit();
2375 Parent->addDecl(CLinkageDecl);
2376 Parent = CLinkageDecl;
2377 }
2378
2380 if (Context.BuiltinInfo.isImmediate(ID)) {
2381 assert(getLangOpts().CPlusPlus20 &&
2382 "consteval builtins should only be available in C++20 mode");
2383 ConstexprKind = ConstexprSpecKind::Consteval;
2384 }
2385
2387 Context, Parent, Loc, Loc, II, Type, /*TInfo=*/nullptr, SC_Extern,
2388 getCurFPFeatures().isFPConstrained(), /*isInlineSpecified=*/false,
2389 Type->isFunctionProtoType(), ConstexprKind);
2390 New->setImplicit();
2391 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2392
2393 // Create Decl objects for each parameter, adding them to the
2394 // FunctionDecl.
2395 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2397 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2399 Context, New, SourceLocation(), SourceLocation(), nullptr,
2400 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2401 parm->setScopeInfo(0, i);
2402 Params.push_back(parm);
2403 }
2404 New->setParams(Params);
2405 }
2406
2408 return New;
2409}
2410
2412 Scope *S, bool ForRedeclaration,
2413 SourceLocation Loc) {
2415
2417 QualType R = Context.GetBuiltinType(ID, Error);
2418 if (Error) {
2419 if (!ForRedeclaration)
2420 return nullptr;
2421
2422 // If we have a builtin without an associated type we should not emit a
2423 // warning when we were not able to find a type for it.
2425 Context.BuiltinInfo.allowTypeMismatch(ID))
2426 return nullptr;
2427
2428 // If we could not find a type for setjmp it is because the jmp_buf type was
2429 // not defined prior to the setjmp declaration.
2431 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2432 << Context.BuiltinInfo.getName(ID);
2433 return nullptr;
2434 }
2435
2436 // Generally, we emit a warning that the declaration requires the
2437 // appropriate header.
2438 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2439 << getHeaderName(Context.BuiltinInfo, ID, Error)
2440 << Context.BuiltinInfo.getName(ID);
2441 return nullptr;
2442 }
2443
2444 if (!ForRedeclaration &&
2445 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2446 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2447 Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2448 : diag::ext_implicit_lib_function_decl)
2449 << Context.BuiltinInfo.getName(ID) << R;
2450 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2451 Diag(Loc, diag::note_include_header_or_declare)
2452 << Header << Context.BuiltinInfo.getName(ID);
2453 }
2454
2455 if (R.isNull())
2456 return nullptr;
2457
2458 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2460
2461 // TUScope is the translation-unit scope to insert this function into.
2462 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2463 // relate Scopes to DeclContexts, and probably eliminate CurContext
2464 // entirely, but we're not there yet.
2465 DeclContext *SavedContext = CurContext;
2466 CurContext = New->getDeclContext();
2468 CurContext = SavedContext;
2469 return New;
2470}
2471
2472/// Typedef declarations don't have linkage, but they still denote the same
2473/// entity if their types are the same.
2474/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2475/// isSameEntity.
2476static void
2479 // This is only interesting when modules are enabled.
2480 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2481 return;
2482
2483 // Empty sets are uninteresting.
2484 if (Previous.empty())
2485 return;
2486
2487 LookupResult::Filter Filter = Previous.makeFilter();
2488 while (Filter.hasNext()) {
2489 NamedDecl *Old = Filter.next();
2490
2491 // Non-hidden declarations are never ignored.
2492 if (S.isVisible(Old))
2493 continue;
2494
2495 // Declarations of the same entity are not ignored, even if they have
2496 // different linkages.
2497 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2498 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2499 Decl->getUnderlyingType()))
2500 continue;
2501
2502 // If both declarations give a tag declaration a typedef name for linkage
2503 // purposes, then they declare the same entity.
2504 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2505 Decl->getAnonDeclWithTypedefName())
2506 continue;
2507 }
2508
2509 Filter.erase();
2510 }
2511
2512 Filter.done();
2513}
2514
2516 QualType OldType;
2517 if (const TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2518 OldType = OldTypedef->getUnderlyingType();
2519 else
2520 OldType = Context.getTypeDeclType(Old);
2521 QualType NewType = New->getUnderlyingType();
2522
2523 if (NewType->isVariablyModifiedType()) {
2524 // Must not redefine a typedef with a variably-modified type.
2525 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2526 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2527 << Kind << NewType;
2528 if (Old->getLocation().isValid())
2529 notePreviousDefinition(Old, New->getLocation());
2530 New->setInvalidDecl();
2531 return true;
2532 }
2533
2534 if (OldType != NewType &&
2535 !OldType->isDependentType() &&
2536 !NewType->isDependentType() &&
2537 !Context.hasSameType(OldType, NewType)) {
2538 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2539 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2540 << Kind << NewType << OldType;
2541 if (Old->getLocation().isValid())
2542 notePreviousDefinition(Old, New->getLocation());
2543 New->setInvalidDecl();
2544 return true;
2545 }
2546 return false;
2547}
2548
2550 LookupResult &OldDecls) {
2551 // If the new decl is known invalid already, don't bother doing any
2552 // merging checks.
2553 if (New->isInvalidDecl()) return;
2554
2555 // Allow multiple definitions for ObjC built-in typedefs.
2556 // FIXME: Verify the underlying types are equivalent!
2557 if (getLangOpts().ObjC) {
2558 const IdentifierInfo *TypeID = New->getIdentifier();
2559 switch (TypeID->getLength()) {
2560 default: break;
2561 case 2:
2562 {
2563 if (!TypeID->isStr("id"))
2564 break;
2565 QualType T = New->getUnderlyingType();
2566 if (!T->isPointerType())
2567 break;
2568 if (!T->isVoidPointerType()) {
2569 QualType PT = T->castAs<PointerType>()->getPointeeType();
2570 if (!PT->isStructureType())
2571 break;
2572 }
2573 Context.setObjCIdRedefinitionType(T);
2574 // Install the built-in type for 'id', ignoring the current definition.
2575 New->setModedTypeSourceInfo(New->getTypeSourceInfo(),
2576 Context.getObjCIdType());
2577 return;
2578 }
2579 case 5:
2580 if (!TypeID->isStr("Class"))
2581 break;
2582 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2583 // Install the built-in type for 'Class', ignoring the current definition.
2584 New->setModedTypeSourceInfo(New->getTypeSourceInfo(),
2585 Context.getObjCClassType());
2586 return;
2587 case 3:
2588 if (!TypeID->isStr("SEL"))
2589 break;
2590 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2591 // Install the built-in type for 'SEL', ignoring the current definition.
2592 New->setModedTypeSourceInfo(New->getTypeSourceInfo(),
2593 Context.getObjCSelType());
2594 return;
2595 }
2596 // Fall through - the typedef name was not a builtin type.
2597 }
2598
2599 // Verify the old decl was also a type.
2600 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2601 if (!Old) {
2602 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2603 << New->getDeclName();
2604
2605 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2606 if (OldD->getLocation().isValid())
2607 notePreviousDefinition(OldD, New->getLocation());
2608
2609 return New->setInvalidDecl();
2610 }
2611
2612 // If the old declaration is invalid, just give up here.
2613 if (Old->isInvalidDecl())
2614 return New->setInvalidDecl();
2615
2616 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2617 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2618 auto *NewTag = New->getAnonDeclWithTypedefName();
2619 NamedDecl *Hidden = nullptr;
2620 if (OldTag && NewTag &&
2621 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2622 !hasVisibleDefinition(OldTag, &Hidden)) {
2623 // There is a definition of this tag, but it is not visible. Use it
2624 // instead of our tag.
2625 if (OldTD->isModed())
2626 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2627 OldTD->getUnderlyingType());
2628 else
2629 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2630
2631 // Make the old tag definition visible.
2633
2635 }
2636 }
2637
2638 // If the typedef types are not identical, reject them in all languages and
2639 // with any extensions enabled.
2640 if (isIncompatibleTypedef(Old, New))
2641 return;
2642
2643 // The types match. Link up the redeclaration chain and merge attributes if
2644 // the old declaration was a typedef.
2645 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2646 New->setPreviousDecl(Typedef);
2648 }
2649
2650 if (getLangOpts().MicrosoftExt)
2651 return;
2652
2653 if (getLangOpts().CPlusPlus) {
2654 // C++ [dcl.typedef]p2:
2655 // In a given non-class scope, a typedef specifier can be used to
2656 // redefine the name of any type declared in that scope to refer
2657 // to the type to which it already refers.
2659 return;
2660
2661 // C++0x [dcl.typedef]p4:
2662 // In a given class scope, a typedef specifier can be used to redefine
2663 // any class-name declared in that scope that is not also a typedef-name
2664 // to refer to the type to which it already refers.
2665 //
2666 // This wording came in via DR424, which was a correction to the
2667 // wording in DR56, which accidentally banned code like:
2668 //
2669 // struct S {
2670 // typedef struct A { } A;
2671 // };
2672 //
2673 // in the C++03 standard. We implement the C++0x semantics, which
2674 // allow the above but disallow
2675 //
2676 // struct S {
2677 // typedef int I;
2678 // typedef int I;
2679 // };
2680 //
2681 // since that was the intent of DR56.
2682 if (!isa<TypedefNameDecl>(Old))
2683 return;
2684
2685 Diag(New->getLocation(), diag::err_redefinition)
2686 << New->getDeclName();
2687 notePreviousDefinition(Old, New->getLocation());
2688 return New->setInvalidDecl();
2689 }
2690
2691 // Modules always permit redefinition of typedefs, as does C11.
2692 if (getLangOpts().Modules || getLangOpts().C11)
2693 return;
2694
2695 // If we have a redefinition of a typedef in C, emit a warning. This warning
2696 // is normally mapped to an error, but can be controlled with
2697 // -Wtypedef-redefinition. If either the original or the redefinition is
2698 // in a system header, don't emit this for compatibility with GCC.
2699 if (getDiagnostics().getSuppressSystemWarnings() &&
2700 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2701 (Old->isImplicit() ||
2702 Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2703 Context.getSourceManager().isInSystemHeader(New->getLocation())))
2704 return;
2705
2706 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2707 << New->getDeclName();
2708 notePreviousDefinition(Old, New->getLocation());
2709}
2710
2712 // If this was an unscoped enumeration, yank all of its enumerators
2713 // out of the scope.
2714 if (auto *ED = dyn_cast<EnumDecl>(New); ED && !ED->isScoped()) {
2715 Scope *EnumScope = getNonFieldDeclScope(S);
2716 for (auto *ECD : ED->enumerators()) {
2717 assert(EnumScope->isDeclScope(ECD));
2718 EnumScope->RemoveDecl(ECD);
2719 IdResolver.RemoveDecl(ECD);
2720 }
2721 }
2722}
2723
2724/// DeclhasAttr - returns true if decl Declaration already has the target
2725/// attribute.
2726static bool DeclHasAttr(const Decl *D, const Attr *A) {
2727 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2728 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2729 for (const auto *i : D->attrs())
2730 if (i->getKind() == A->getKind()) {
2731 if (Ann) {
2732 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2733 return true;
2734 continue;
2735 }
2736 // FIXME: Don't hardcode this check
2737 if (OA && isa<OwnershipAttr>(i))
2738 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2739 return true;
2740 }
2741
2742 return false;
2743}
2744
2746 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2747 return VD->isThisDeclarationADefinition();
2748 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2749 return TD->isCompleteDefinition() || TD->isBeingDefined();
2750 return true;
2751}
2752
2753/// Merge alignment attributes from \p Old to \p New, taking into account the
2754/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2755///
2756/// \return \c true if any attributes were added to \p New.
2757static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2758 // Look for alignas attributes on Old, and pick out whichever attribute
2759 // specifies the strictest alignment requirement.
2760 AlignedAttr *OldAlignasAttr = nullptr;
2761 AlignedAttr *OldStrictestAlignAttr = nullptr;
2762 unsigned OldAlign = 0;
2763 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2764 // FIXME: We have no way of representing inherited dependent alignments
2765 // in a case like:
2766 // template<int A, int B> struct alignas(A) X;
2767 // template<int A, int B> struct alignas(B) X {};
2768 // For now, we just ignore any alignas attributes which are not on the
2769 // definition in such a case.
2770 if (I->isAlignmentDependent())
2771 return false;
2772
2773 if (I->isAlignas())
2774 OldAlignasAttr = I;
2775
2776 unsigned Align = I->getAlignment(S.Context);
2777 if (Align > OldAlign) {
2778 OldAlign = Align;
2779 OldStrictestAlignAttr = I;
2780 }
2781 }
2782
2783 // Look for alignas attributes on New.
2784 AlignedAttr *NewAlignasAttr = nullptr;
2785 unsigned NewAlign = 0;
2786 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2787 if (I->isAlignmentDependent())
2788 return false;
2789
2790 if (I->isAlignas())
2791 NewAlignasAttr = I;
2792
2793 unsigned Align = I->getAlignment(S.Context);
2794 if (Align > NewAlign)
2795 NewAlign = Align;
2796 }
2797
2798 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2799 // Both declarations have 'alignas' attributes. We require them to match.
2800 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2801 // fall short. (If two declarations both have alignas, they must both match
2802 // every definition, and so must match each other if there is a definition.)
2803
2804 // If either declaration only contains 'alignas(0)' specifiers, then it
2805 // specifies the natural alignment for the type.
2806 if (OldAlign == 0 || NewAlign == 0) {
2807 QualType Ty;
2808 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2809 Ty = VD->getType();
2810 else
2812
2813 if (OldAlign == 0)
2814 OldAlign = S.Context.getTypeAlign(Ty);
2815 if (NewAlign == 0)
2816 NewAlign = S.Context.getTypeAlign(Ty);
2817 }
2818
2819 if (OldAlign != NewAlign) {
2820 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2823 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2824 }
2825 }
2826
2827 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2828 // C++11 [dcl.align]p6:
2829 // if any declaration of an entity has an alignment-specifier,
2830 // every defining declaration of that entity shall specify an
2831 // equivalent alignment.
2832 // C11 6.7.5/7:
2833 // If the definition of an object does not have an alignment
2834 // specifier, any other declaration of that object shall also
2835 // have no alignment specifier.
2836 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2837 << OldAlignasAttr;
2838 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2839 << OldAlignasAttr;
2840 }
2841
2842 bool AnyAdded = false;
2843
2844 // Ensure we have an attribute representing the strictest alignment.
2845 if (OldAlign > NewAlign) {
2846 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2847 Clone->setInherited(true);
2848 New->addAttr(Clone);
2849 AnyAdded = true;
2850 }
2851
2852 // Ensure we have an alignas attribute if the old declaration had one.
2853 if (OldAlignasAttr && !NewAlignasAttr &&
2854 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2855 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2856 Clone->setInherited(true);
2857 New->addAttr(Clone);
2858 AnyAdded = true;
2859 }
2860
2861 return AnyAdded;
2862}
2863
2864#define WANT_DECL_MERGE_LOGIC
2865#include "clang/Sema/AttrParsedAttrImpl.inc"
2866#undef WANT_DECL_MERGE_LOGIC
2867
2869 const InheritableAttr *Attr,
2871 // Diagnose any mutual exclusions between the attribute that we want to add
2872 // and attributes that already exist on the declaration.
2873 if (!DiagnoseMutualExclusions(S, D, Attr))
2874 return false;
2875
2876 // This function copies an attribute Attr from a previous declaration to the
2877 // new declaration D if the new declaration doesn't itself have that attribute
2878 // yet or if that attribute allows duplicates.
2879 // If you're adding a new attribute that requires logic different from
2880 // "use explicit attribute on decl if present, else use attribute from
2881 // previous decl", for example if the attribute needs to be consistent
2882 // between redeclarations, you need to call a custom merge function here.
2883 InheritableAttr *NewAttr = nullptr;
2884 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2885 NewAttr = S.mergeAvailabilityAttr(
2886 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2887 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2888 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2889 AA->getPriority(), AA->getEnvironment());
2890 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2891 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2892 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2893 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2894 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2895 NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2896 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2897 NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2898 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2899 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2900 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2901 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2902 FA->getFirstArg());
2903 else if (const auto *FMA = dyn_cast<FormatMatchesAttr>(Attr))
2904 NewAttr = S.mergeFormatMatchesAttr(
2905 D, *FMA, FMA->getType(), FMA->getFormatIdx(), FMA->getFormatString());
2906 else if (const auto *MFA = dyn_cast<ModularFormatAttr>(Attr))
2907 NewAttr = S.mergeModularFormatAttr(
2908 D, *MFA, MFA->getModularImplFn(), MFA->getImplName(),
2909 MutableArrayRef<StringRef>{MFA->aspects_begin(), MFA->aspects_size()});
2910 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2911 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2912 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2913 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2914 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2915 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2916 IA->getInheritanceModel());
2917 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2918 NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2919 &S.Context.Idents.get(AA->getSpelling()));
2920 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2923 // CUDA target attributes are part of function signature for
2924 // overloading purposes and must not be merged.
2925 return false;
2926 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2927 NewAttr = S.mergeMinSizeAttr(D, *MA);
2928 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2929 NewAttr = S.Swift().mergeNameAttr(D, *SNA, SNA->getName());
2930 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2931 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2932 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2933 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2934 else if (isa<AlignedAttr>(Attr))
2935 // AlignedAttrs are handled separately, because we need to handle all
2936 // such attributes on a declaration at the same time.
2937 NewAttr = nullptr;
2942 NewAttr = nullptr;
2943 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2944 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2945 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2946 NewAttr = S.Wasm().mergeImportModuleAttr(D, *IMA);
2947 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2948 NewAttr = S.Wasm().mergeImportNameAttr(D, *INA);
2949 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2950 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2951 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2952 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2953 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2954 NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2955 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
2956 NewAttr = S.HLSL().mergeNumThreadsAttr(D, *NT, NT->getX(), NT->getY(),
2957 NT->getZ());
2958 else if (const auto *WS = dyn_cast<HLSLWaveSizeAttr>(Attr))
2959 NewAttr = S.HLSL().mergeWaveSizeAttr(D, *WS, WS->getMin(), WS->getMax(),
2960 WS->getPreferred(),
2961 WS->getSpelledArgsCount());
2962 else if (const auto *CI = dyn_cast<HLSLVkConstantIdAttr>(Attr))
2963 NewAttr = S.HLSL().mergeVkConstantIdAttr(D, *CI, CI->getId());
2964 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
2965 NewAttr = S.HLSL().mergeShaderAttr(D, *SA, SA->getType());
2966 else if (isa<SuppressAttr>(Attr))
2967 // Do nothing. Each redeclaration should be suppressed separately.
2968 NewAttr = nullptr;
2969 else if (const auto *RD = dyn_cast<OpenACCRoutineDeclAttr>(Attr))
2970 NewAttr = S.OpenACC().mergeRoutineDeclAttr(*RD);
2971 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2972 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2973
2974 if (NewAttr) {
2975 NewAttr->setInherited(true);
2976 D->addAttr(NewAttr);
2977 if (isa<MSInheritanceAttr>(NewAttr))
2979 return true;
2980 }
2981
2982 return false;
2983}
2984
2985static const NamedDecl *getDefinition(const Decl *D) {
2986 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
2987 if (const auto *Def = TD->getDefinition(); Def && !Def->isBeingDefined())
2988 return Def;
2989 return nullptr;
2990 }
2991 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2992 const VarDecl *Def = VD->getDefinition();
2993 if (Def)
2994 return Def;
2995 return VD->getActingDefinition();
2996 }
2997 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2998 const FunctionDecl *Def = nullptr;
2999 if (FD->isDefined(Def, true))
3000 return Def;
3001 }
3002 return nullptr;
3003}
3004
3005static bool hasAttribute(const Decl *D, attr::Kind Kind) {
3006 for (const auto *Attribute : D->attrs())
3007 if (Attribute->getKind() == Kind)
3008 return true;
3009 return false;
3010}
3011
3012/// checkNewAttributesAfterDef - If we already have a definition, check that
3013/// there are no new attributes in this declaration.
3014static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
3015 if (!New->hasAttrs())
3016 return;
3017
3018 const NamedDecl *Def = getDefinition(Old);
3019 if (!Def || Def == New)
3020 return;
3021
3022 AttrVec &NewAttributes = New->getAttrs();
3023 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
3024 Attr *NewAttribute = NewAttributes[I];
3025
3026 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
3027 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
3028 SkipBodyInfo SkipBody;
3029 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
3030
3031 // If we're skipping this definition, drop the "alias" attribute.
3032 if (SkipBody.ShouldSkip) {
3033 NewAttributes.erase(NewAttributes.begin() + I);
3034 --E;
3035 continue;
3036 }
3037 } else {
3038 VarDecl *VD = cast<VarDecl>(New);
3039 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
3041 ? diag::err_alias_after_tentative
3042 : diag::err_redefinition;
3043 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
3044 if (Diag == diag::err_redefinition)
3045 S.notePreviousDefinition(Def, VD->getLocation());
3046 else
3047 S.Diag(Def->getLocation(), diag::note_previous_definition);
3048 VD->setInvalidDecl();
3049 }
3050 ++I;
3051 continue;
3052 }
3053
3054 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
3055 // Tentative definitions are only interesting for the alias check above.
3056 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
3057 ++I;
3058 continue;
3059 }
3060 }
3061
3062 if (hasAttribute(Def, NewAttribute->getKind())) {
3063 ++I;
3064 continue; // regular attr merging will take care of validating this.
3065 }
3066
3067 if (isa<C11NoReturnAttr>(NewAttribute)) {
3068 // C's _Noreturn is allowed to be added to a function after it is defined.
3069 ++I;
3070 continue;
3071 } else if (isa<UuidAttr>(NewAttribute)) {
3072 // msvc will allow a subsequent definition to add an uuid to a class
3073 ++I;
3074 continue;
3076 NewAttribute) &&
3077 NewAttribute->isStandardAttributeSyntax()) {
3078 // C++14 [dcl.attr.deprecated]p3: A name or entity declared without the
3079 // deprecated attribute can later be re-declared with the attribute and
3080 // vice-versa.
3081 // C++17 [dcl.attr.unused]p4: A name or entity declared without the
3082 // maybe_unused attribute can later be redeclared with the attribute and
3083 // vice versa.
3084 // C++20 [dcl.attr.nodiscard]p2: A name or entity declared without the
3085 // nodiscard attribute can later be redeclared with the attribute and
3086 // vice-versa.
3087 // C23 6.7.13.3p3, 6.7.13.4p3. and 6.7.13.5p5 give the same allowances.
3088 ++I;
3089 continue;
3090 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
3091 if (AA->isAlignas()) {
3092 // C++11 [dcl.align]p6:
3093 // if any declaration of an entity has an alignment-specifier,
3094 // every defining declaration of that entity shall specify an
3095 // equivalent alignment.
3096 // C11 6.7.5/7:
3097 // If the definition of an object does not have an alignment
3098 // specifier, any other declaration of that object shall also
3099 // have no alignment specifier.
3100 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
3101 << AA;
3102 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
3103 << AA;
3104 NewAttributes.erase(NewAttributes.begin() + I);
3105 --E;
3106 continue;
3107 }
3108 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
3109 // If there is a C definition followed by a redeclaration with this
3110 // attribute then there are two different definitions. In C++, prefer the
3111 // standard diagnostics.
3112 if (!S.getLangOpts().CPlusPlus) {
3113 S.Diag(NewAttribute->getLocation(),
3114 diag::err_loader_uninitialized_redeclaration);
3115 S.Diag(Def->getLocation(), diag::note_previous_definition);
3116 NewAttributes.erase(NewAttributes.begin() + I);
3117 --E;
3118 continue;
3119 }
3120 } else if (isa<SelectAnyAttr>(NewAttribute) &&
3121 cast<VarDecl>(New)->isInline() &&
3122 !cast<VarDecl>(New)->isInlineSpecified()) {
3123 // Don't warn about applying selectany to implicitly inline variables.
3124 // Older compilers and language modes would require the use of selectany
3125 // to make such variables inline, and it would have no effect if we
3126 // honored it.
3127 ++I;
3128 continue;
3129 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
3130 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3131 // declarations after definitions.
3132 ++I;
3133 continue;
3134 } else if (isa<SYCLKernelEntryPointAttr>(NewAttribute)) {
3135 // Elevate latent uses of the sycl_kernel_entry_point attribute to an
3136 // error since the definition will have already been created without
3137 // the semantic effects of the attribute having been applied.
3138 S.Diag(NewAttribute->getLocation(),
3139 diag::err_sycl_entry_point_after_definition)
3140 << NewAttribute;
3141 S.Diag(Def->getLocation(), diag::note_previous_definition);
3142 cast<SYCLKernelEntryPointAttr>(NewAttribute)->setInvalidAttr();
3143 ++I;
3144 continue;
3145 } else if (isa<SYCLExternalAttr>(NewAttribute)) {
3146 // SYCLExternalAttr may be added after a definition.
3147 ++I;
3148 continue;
3149 }
3150
3151 S.Diag(NewAttribute->getLocation(),
3152 diag::warn_attribute_precede_definition);
3153 S.Diag(Def->getLocation(), diag::note_previous_definition);
3154 NewAttributes.erase(NewAttributes.begin() + I);
3155 --E;
3156 }
3157}
3158
3159static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3160 const ConstInitAttr *CIAttr,
3161 bool AttrBeforeInit) {
3162 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3163
3164 // Figure out a good way to write this specifier on the old declaration.
3165 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3166 // enough of the attribute list spelling information to extract that without
3167 // heroics.
3168 std::string SuitableSpelling;
3169 if (S.getLangOpts().CPlusPlus20)
3170 SuitableSpelling = std::string(
3171 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
3172 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3173 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3174 InsertLoc, {tok::l_square, tok::l_square,
3175 S.PP.getIdentifierInfo("clang"), tok::coloncolon,
3176 S.PP.getIdentifierInfo("require_constant_initialization"),
3177 tok::r_square, tok::r_square}));
3178 if (SuitableSpelling.empty())
3179 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3180 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
3181 S.PP.getIdentifierInfo("require_constant_initialization"),
3182 tok::r_paren, tok::r_paren}));
3183 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3184 SuitableSpelling = "constinit";
3185 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3186 SuitableSpelling = "[[clang::require_constant_initialization]]";
3187 if (SuitableSpelling.empty())
3188 SuitableSpelling = "__attribute__((require_constant_initialization))";
3189 SuitableSpelling += " ";
3190
3191 if (AttrBeforeInit) {
3192 // extern constinit int a;
3193 // int a = 0; // error (missing 'constinit'), accepted as extension
3194 assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3195 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3196 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3197 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3198 } else {
3199 // int a = 0;
3200 // constinit extern int a; // error (missing 'constinit')
3201 S.Diag(CIAttr->getLocation(),
3202 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3203 : diag::warn_require_const_init_added_too_late)
3204 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3205 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3206 << CIAttr->isConstinit()
3207 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3208 }
3209}
3210
3213 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3214 UsedAttr *NewAttr = OldAttr->clone(Context);
3215 NewAttr->setInherited(true);
3216 New->addAttr(NewAttr);
3217 }
3218 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3219 RetainAttr *NewAttr = OldAttr->clone(Context);
3220 NewAttr->setInherited(true);
3221 New->addAttr(NewAttr);
3222 }
3223
3224 if (!Old->hasAttrs() && !New->hasAttrs())
3225 return;
3226
3227 // [dcl.constinit]p1:
3228 // If the [constinit] specifier is applied to any declaration of a
3229 // variable, it shall be applied to the initializing declaration.
3230 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3231 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3232 if (bool(OldConstInit) != bool(NewConstInit)) {
3233 const auto *OldVD = cast<VarDecl>(Old);
3234 auto *NewVD = cast<VarDecl>(New);
3235
3236 // Find the initializing declaration. Note that we might not have linked
3237 // the new declaration into the redeclaration chain yet.
3238 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3239 if (!InitDecl &&
3240 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3241 InitDecl = NewVD;
3242
3243 if (InitDecl == NewVD) {
3244 // This is the initializing declaration. If it would inherit 'constinit',
3245 // that's ill-formed. (Note that we do not apply this to the attribute
3246 // form).
3247 if (OldConstInit && OldConstInit->isConstinit())
3248 diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3249 /*AttrBeforeInit=*/true);
3250 } else if (NewConstInit) {
3251 // This is the first time we've been told that this declaration should
3252 // have a constant initializer. If we already saw the initializing
3253 // declaration, this is too late.
3254 if (InitDecl && InitDecl != NewVD) {
3255 diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3256 /*AttrBeforeInit=*/false);
3257 NewVD->dropAttr<ConstInitAttr>();
3258 }
3259 }
3260 }
3261
3262 // Attributes declared post-definition are currently ignored.
3263 checkNewAttributesAfterDef(*this, New, Old);
3264
3265 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3266 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3267 if (!OldA->isEquivalent(NewA)) {
3268 // This redeclaration changes __asm__ label.
3269 Diag(New->getLocation(), diag::err_different_asm_label);
3270 Diag(OldA->getLocation(), diag::note_previous_declaration);
3271 }
3272 } else if (Old->isUsed()) {
3273 // This redeclaration adds an __asm__ label to a declaration that has
3274 // already been ODR-used.
3275 Diag(New->getLocation(), diag::err_late_asm_label_name)
3276 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3277 }
3278 }
3279
3280 // Re-declaration cannot add abi_tag's.
3281 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3282 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3283 for (const auto &NewTag : NewAbiTagAttr->tags()) {
3284 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3285 Diag(NewAbiTagAttr->getLocation(),
3286 diag::err_new_abi_tag_on_redeclaration)
3287 << NewTag;
3288 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3289 }
3290 }
3291 } else {
3292 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3293 Diag(Old->getLocation(), diag::note_previous_declaration);
3294 }
3295 }
3296
3297 // This redeclaration adds a section attribute.
3298 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3299 if (auto *VD = dyn_cast<VarDecl>(New)) {
3300 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3301 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3302 Diag(Old->getLocation(), diag::note_previous_declaration);
3303 }
3304 }
3305 }
3306
3307 // Redeclaration adds code-seg attribute.
3308 const auto *NewCSA = New->getAttr<CodeSegAttr>();
3309 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3310 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3311 Diag(New->getLocation(), diag::warn_mismatched_section)
3312 << 0 /*codeseg*/;
3313 Diag(Old->getLocation(), diag::note_previous_declaration);
3314 }
3315
3316 if (!Old->hasAttrs())
3317 return;
3318
3319 bool foundAny = New->hasAttrs();
3320
3321 // Ensure that any moving of objects within the allocated map is done before
3322 // we process them.
3323 if (!foundAny) New->setAttrs(AttrVec());
3324
3325 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3326 // Ignore deprecated/unavailable/availability attributes if requested.
3328 if (isa<DeprecatedAttr>(I) ||
3331 switch (AMK) {
3333 continue;
3334
3339 LocalAMK = AMK;
3340 break;
3341 }
3342 }
3343
3344 // Already handled.
3345 if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3346 continue;
3347
3349 if (auto *FD = dyn_cast<FunctionDecl>(New);
3350 FD &&
3351 FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
3352 continue; // Don't propagate inferred noreturn attributes to explicit
3353 }
3354
3355 if (mergeDeclAttribute(*this, New, I, LocalAMK))
3356 foundAny = true;
3357 }
3358
3359 if (mergeAlignedAttrs(*this, New, Old))
3360 foundAny = true;
3361
3362 if (!foundAny) New->dropAttrs();
3363}
3364
3366 for (const Attr *A : D->attrs())
3367 checkAttrIsTypeDependent(D, A);
3368}
3369
3370// Returns the number of added attributes.
3371template <class T>
3372static unsigned propagateAttribute(ParmVarDecl *To, const ParmVarDecl *From,
3373 Sema &S) {
3374 unsigned found = 0;
3375 for (const auto *I : From->specific_attrs<T>()) {
3376 if (!DeclHasAttr(To, I)) {
3377 T *newAttr = cast<T>(I->clone(S.Context));
3378 newAttr->setInherited(true);
3379 To->addAttr(newAttr);
3380 ++found;
3381 }
3382 }
3383 return found;
3384}
3385
3386template <class F>
3387static void propagateAttributes(ParmVarDecl *To, const ParmVarDecl *From,
3388 F &&propagator) {
3389 if (!From->hasAttrs()) {
3390 return;
3391 }
3392
3393 bool foundAny = To->hasAttrs();
3394
3395 // Ensure that any moving of objects within the allocated map is
3396 // done before we process them.
3397 if (!foundAny)
3398 To->setAttrs(AttrVec());
3399
3400 foundAny |= std::forward<F>(propagator)(To, From) != 0;
3401
3402 if (!foundAny)
3403 To->dropAttrs();
3404}
3405
3406/// mergeParamDeclAttributes - Copy attributes from the old parameter
3407/// to the new one.
3409 const ParmVarDecl *oldDecl,
3410 Sema &S) {
3411 // C++11 [dcl.attr.depend]p2:
3412 // The first declaration of a function shall specify the
3413 // carries_dependency attribute for its declarator-id if any declaration
3414 // of the function specifies the carries_dependency attribute.
3415 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3416 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3417 S.Diag(CDA->getLocation(),
3418 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3419 // Find the first declaration of the parameter.
3420 // FIXME: Should we build redeclaration chains for function parameters?
3421 const FunctionDecl *FirstFD =
3422 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3423 const ParmVarDecl *FirstVD =
3424 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3425 S.Diag(FirstVD->getLocation(),
3426 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3427 }
3428
3430 newDecl, oldDecl, [&S](ParmVarDecl *To, const ParmVarDecl *From) {
3431 unsigned found = 0;
3432 found += propagateAttribute<InheritableParamAttr>(To, From, S);
3433 // Propagate the lifetimebound attribute from parameters to the
3434 // most recent declaration. Note that this doesn't include the implicit
3435 // 'this' parameter, as the attribute is applied to the function type in
3436 // that case.
3437 found += propagateAttribute<LifetimeBoundAttr>(To, From, S);
3438 return found;
3439 });
3440}
3441
3443 const ASTContext &Ctx) {
3444
3445 auto NoSizeInfo = [&Ctx](QualType Ty) {
3446 if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3447 return true;
3448 if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))
3449 return VAT->getSizeModifier() == ArraySizeModifier::Star;
3450 return false;
3451 };
3452
3453 // `type[]` is equivalent to `type *` and `type[*]`.
3454 if (NoSizeInfo(Old) && NoSizeInfo(New))
3455 return true;
3456
3457 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3458 if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3459 const auto *OldVAT = Ctx.getAsVariableArrayType(Old);
3460 const auto *NewVAT = Ctx.getAsVariableArrayType(New);
3461 if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^
3462 (NewVAT->getSizeModifier() == ArraySizeModifier::Star))
3463 return false;
3464 return true;
3465 }
3466
3467 // Only compare size, ignore Size modifiers and CVR.
3468 if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3469 return Ctx.getAsConstantArrayType(Old)->getSize() ==
3471 }
3472
3473 // Don't try to compare dependent sized array
3474 if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) {
3475 return true;
3476 }
3477
3478 return Old == New;
3479}
3480
3481static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3482 const ParmVarDecl *OldParam,
3483 Sema &S) {
3484 if (auto Oldnullability = OldParam->getType()->getNullability()) {
3485 if (auto Newnullability = NewParam->getType()->getNullability()) {
3486 if (*Oldnullability != *Newnullability) {
3487 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3489 *Newnullability,
3491 != 0))
3493 *Oldnullability,
3495 != 0));
3496 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3497 }
3498 } else {
3499 QualType NewT = NewParam->getType();
3500 NewT = S.Context.getAttributedType(*Oldnullability, NewT, NewT);
3501 NewParam->setType(NewT);
3502 }
3503 }
3504 const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
3505 const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
3506 if (OldParamDT && NewParamDT &&
3507 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3508 QualType OldParamOT = OldParamDT->getOriginalType();
3509 QualType NewParamOT = NewParamDT->getOriginalType();
3510 if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) {
3511 S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
3512 << NewParam << NewParamOT;
3513 S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
3514 << OldParamOT;
3515 }
3516 }
3517}
3518
3519namespace {
3520
3521/// Used in MergeFunctionDecl to keep track of function parameters in
3522/// C.
3523struct GNUCompatibleParamWarning {
3524 ParmVarDecl *OldParm;
3525 ParmVarDecl *NewParm;
3526 QualType PromotedType;
3527};
3528
3529} // end anonymous namespace
3530
3531// Determine whether the previous declaration was a definition, implicit
3532// declaration, or a declaration.
3533template <typename T>
3534static std::pair<diag::kind, SourceLocation>
3536 diag::kind PrevDiag;
3537 SourceLocation OldLocation = Old->getLocation();
3538 if (Old->isThisDeclarationADefinition())
3539 PrevDiag = diag::note_previous_definition;
3540 else if (Old->isImplicit()) {
3541 PrevDiag = diag::note_previous_implicit_declaration;
3542 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3543 if (FD->getBuiltinID())
3544 PrevDiag = diag::note_previous_builtin_declaration;
3545 }
3546 if (OldLocation.isInvalid())
3547 OldLocation = New->getLocation();
3548 } else
3549 PrevDiag = diag::note_previous_declaration;
3550 return std::make_pair(PrevDiag, OldLocation);
3551}
3552
3553/// canRedefineFunction - checks if a function can be redefined. Currently,
3554/// only extern inline functions can be redefined, and even then only in
3555/// GNU89 mode.
3556static bool canRedefineFunction(const FunctionDecl *FD,
3557 const LangOptions& LangOpts) {
3558 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3559 !LangOpts.CPlusPlus &&
3560 FD->isInlineSpecified() &&
3561 FD->getStorageClass() == SC_Extern);
3562}
3563
3564const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3565 const AttributedType *AT = T->getAs<AttributedType>();
3566 while (AT && !AT->isCallingConv())
3567 AT = AT->getModifiedType()->getAs<AttributedType>();
3568 return AT;
3569}
3570
3571template <typename T>
3572static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3573 const DeclContext *DC = Old->getDeclContext();
3574 if (DC->isRecord())
3575 return false;
3576
3577 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3578 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3579 return true;
3580 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3581 return true;
3582 return false;
3583}
3584
3585template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3586static bool isExternC(VarTemplateDecl *) { return false; }
3587static bool isExternC(FunctionTemplateDecl *) { return false; }
3588
3589/// Check whether a redeclaration of an entity introduced by a
3590/// using-declaration is valid, given that we know it's not an overload
3591/// (nor a hidden tag declaration).
3592template<typename ExpectedDecl>
3594 ExpectedDecl *New) {
3595 // C++11 [basic.scope.declarative]p4:
3596 // Given a set of declarations in a single declarative region, each of
3597 // which specifies the same unqualified name,
3598 // -- they shall all refer to the same entity, or all refer to functions
3599 // and function templates; or
3600 // -- exactly one declaration shall declare a class name or enumeration
3601 // name that is not a typedef name and the other declarations shall all
3602 // refer to the same variable or enumerator, or all refer to functions
3603 // and function templates; in this case the class name or enumeration
3604 // name is hidden (3.3.10).
3605
3606 // C++11 [namespace.udecl]p14:
3607 // If a function declaration in namespace scope or block scope has the
3608 // same name and the same parameter-type-list as a function introduced
3609 // by a using-declaration, and the declarations do not declare the same
3610 // function, the program is ill-formed.
3611
3612 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3613 if (Old &&
3614 !Old->getDeclContext()->getRedeclContext()->Equals(
3615 New->getDeclContext()->getRedeclContext()) &&
3616 !(isExternC(Old) && isExternC(New)))
3617 Old = nullptr;
3618
3619 if (!Old) {
3620 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3621 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3622 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3623 return true;
3624 }
3625 return false;
3626}
3627
3629 const FunctionDecl *B) {
3630 assert(A->getNumParams() == B->getNumParams());
3631
3632 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3633 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3634 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3635 if (AttrA == AttrB)
3636 return true;
3637 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3638 AttrA->isDynamic() == AttrB->isDynamic();
3639 };
3640
3641 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3642}
3643
3644/// If necessary, adjust the semantic declaration context for a qualified
3645/// declaration to name the correct inline namespace within the qualifier.
3647 DeclaratorDecl *OldD) {
3648 // The only case where we need to update the DeclContext is when
3649 // redeclaration lookup for a qualified name finds a declaration
3650 // in an inline namespace within the context named by the qualifier:
3651 //
3652 // inline namespace N { int f(); }
3653 // int ::f(); // Sema DC needs adjusting from :: to N::.
3654 //
3655 // For unqualified declarations, the semantic context *can* change
3656 // along the redeclaration chain (for local extern declarations,
3657 // extern "C" declarations, and friend declarations in particular).
3658 if (!NewD->getQualifier())
3659 return;
3660
3661 // NewD is probably already in the right context.
3662 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3663 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3664 if (NamedDC->Equals(SemaDC))
3665 return;
3666
3667 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3668 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3669 "unexpected context for redeclaration");
3670
3671 auto *LexDC = NewD->getLexicalDeclContext();
3672 auto FixSemaDC = [=](NamedDecl *D) {
3673 if (!D)
3674 return;
3675 D->setDeclContext(SemaDC);
3676 D->setLexicalDeclContext(LexDC);
3677 };
3678
3679 FixSemaDC(NewD);
3680 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3681 FixSemaDC(FD->getDescribedFunctionTemplate());
3682 else if (auto *VD = dyn_cast<VarDecl>(NewD))
3683 FixSemaDC(VD->getDescribedVarTemplate());
3684}
3685
3687 bool MergeTypeWithOld, bool NewDeclIsDefn) {
3688 // Verify the old decl was also a function.
3689 FunctionDecl *Old = OldD->getAsFunction();
3690 if (!Old) {
3691 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3692 // We don't need to check the using friend pattern from other module unit
3693 // since we should have diagnosed such cases in its unit already.
3694 if (New->getFriendObjectKind() && !OldD->isInAnotherModuleUnit()) {
3695 Diag(New->getLocation(), diag::err_using_decl_friend);
3696 Diag(Shadow->getTargetDecl()->getLocation(),
3697 diag::note_using_decl_target);
3698 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3699 << 0;
3700 return true;
3701 }
3702
3703 // Check whether the two declarations might declare the same function or
3704 // function template.
3705 if (FunctionTemplateDecl *NewTemplate =
3706 New->getDescribedFunctionTemplate()) {
3708 NewTemplate))
3709 return true;
3710 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3711 ->getAsFunction();
3712 } else {
3713 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3714 return true;
3715 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3716 }
3717 } else {
3718 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3719 << New->getDeclName();
3720 notePreviousDefinition(OldD, New->getLocation());
3721 return true;
3722 }
3723 }
3724
3725 // If the old declaration was found in an inline namespace and the new
3726 // declaration was qualified, update the DeclContext to match.
3728
3729 // If the old declaration is invalid, just give up here.
3730 if (Old->isInvalidDecl())
3731 return true;
3732
3733 // Disallow redeclaration of some builtins.
3734 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3735 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3736 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3737 << Old << Old->getType();
3738 return true;
3739 }
3740
3741 diag::kind PrevDiag;
3742 SourceLocation OldLocation;
3743 std::tie(PrevDiag, OldLocation) =
3745
3746 // Don't complain about this if we're in GNU89 mode and the old function
3747 // is an extern inline function.
3748 // Don't complain about specializations. They are not supposed to have
3749 // storage classes.
3750 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3751 New->getStorageClass() == SC_Static &&
3752 Old->hasExternalFormalLinkage() &&
3753 !New->getTemplateSpecializationInfo() &&
3755 if (getLangOpts().MicrosoftExt) {
3756 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3757 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3758 } else {
3759 Diag(New->getLocation(), diag::err_static_non_static) << New;
3760 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3761 return true;
3762 }
3763 }
3764
3765 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3766 if (!Old->hasAttr<InternalLinkageAttr>()) {
3767 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3768 << ILA;
3769 Diag(Old->getLocation(), diag::note_previous_declaration);
3770 New->dropAttr<InternalLinkageAttr>();
3771 }
3772
3773 if (auto *EA = New->getAttr<ErrorAttr>()) {
3774 if (!Old->hasAttr<ErrorAttr>()) {
3775 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3776 Diag(Old->getLocation(), diag::note_previous_declaration);
3777 New->dropAttr<ErrorAttr>();
3778 }
3779 }
3780
3782 return true;
3783
3784 if (!getLangOpts().CPlusPlus) {
3785 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3786 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3787 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3788 << New << OldOvl;
3789
3790 // Try our best to find a decl that actually has the overloadable
3791 // attribute for the note. In most cases (e.g. programs with only one
3792 // broken declaration/definition), this won't matter.
3793 //
3794 // FIXME: We could do this if we juggled some extra state in
3795 // OverloadableAttr, rather than just removing it.
3796 const Decl *DiagOld = Old;
3797 if (OldOvl) {
3798 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3799 const auto *A = D->getAttr<OverloadableAttr>();
3800 return A && !A->isImplicit();
3801 });
3802 // If we've implicitly added *all* of the overloadable attrs to this
3803 // chain, emitting a "previous redecl" note is pointless.
3804 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3805 }
3806
3807 if (DiagOld)
3808 Diag(DiagOld->getLocation(),
3809 diag::note_attribute_overloadable_prev_overload)
3810 << OldOvl;
3811
3812 if (OldOvl)
3813 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3814 else
3815 New->dropAttr<OverloadableAttr>();
3816 }
3817 }
3818
3819 // It is not permitted to redeclare an SME function with different SME
3820 // attributes.
3821 if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
3822 Diag(New->getLocation(), diag::err_sme_attr_mismatch)
3823 << New->getType() << Old->getType();
3824 Diag(OldLocation, diag::note_previous_declaration);
3825 return true;
3826 }
3827
3828 // If a function is first declared with a calling convention, but is later
3829 // declared or defined without one, all following decls assume the calling
3830 // convention of the first.
3831 //
3832 // It's OK if a function is first declared without a calling convention,
3833 // but is later declared or defined with the default calling convention.
3834 //
3835 // To test if either decl has an explicit calling convention, we look for
3836 // AttributedType sugar nodes on the type as written. If they are missing or
3837 // were canonicalized away, we assume the calling convention was implicit.
3838 //
3839 // Note also that we DO NOT return at this point, because we still have
3840 // other tests to run.
3841 QualType OldQType = Context.getCanonicalType(Old->getType());
3842 QualType NewQType = Context.getCanonicalType(New->getType());
3843 const FunctionType *OldType = cast<FunctionType>(OldQType);
3844 const FunctionType *NewType = cast<FunctionType>(NewQType);
3845 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3846 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3847 bool RequiresAdjustment = false;
3848
3849 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3851 const FunctionType *FT =
3852 First->getType().getCanonicalType()->castAs<FunctionType>();
3854 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3855 if (!NewCCExplicit) {
3856 // Inherit the CC from the previous declaration if it was specified
3857 // there but not here.
3858 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3859 RequiresAdjustment = true;
3860 } else if (Old->getBuiltinID()) {
3861 // Builtin attribute isn't propagated to the new one yet at this point,
3862 // so we check if the old one is a builtin.
3863
3864 // Calling Conventions on a Builtin aren't really useful and setting a
3865 // default calling convention and cdecl'ing some builtin redeclarations is
3866 // common, so warn and ignore the calling convention on the redeclaration.
3867 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3868 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3870 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3871 RequiresAdjustment = true;
3872 } else {
3873 // Calling conventions aren't compatible, so complain.
3874 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3875 Diag(New->getLocation(), diag::err_cconv_change)
3876 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3877 << !FirstCCExplicit
3878 << (!FirstCCExplicit ? "" :
3880
3881 // Put the note on the first decl, since it is the one that matters.
3882 Diag(First->getLocation(), diag::note_previous_declaration);
3883 return true;
3884 }
3885 }
3886
3887 // FIXME: diagnose the other way around?
3888 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3889 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3890 RequiresAdjustment = true;
3891 }
3892
3893 // If the declaration is marked with cfi_unchecked_callee but the definition
3894 // isn't, the definition is also cfi_unchecked_callee.
3895 if (auto *FPT1 = OldType->getAs<FunctionProtoType>()) {
3896 if (auto *FPT2 = NewType->getAs<FunctionProtoType>()) {
3897 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
3898 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
3899
3900 if (EPI1.CFIUncheckedCallee && !EPI2.CFIUncheckedCallee) {
3901 EPI2.CFIUncheckedCallee = true;
3902 NewQType = Context.getFunctionType(FPT2->getReturnType(),
3903 FPT2->getParamTypes(), EPI2);
3904 NewType = cast<FunctionType>(NewQType);
3905 New->setType(NewQType);
3906 }
3907 }
3908 }
3909
3910 // Merge regparm attribute.
3911 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3912 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3913 if (NewTypeInfo.getHasRegParm()) {
3914 Diag(New->getLocation(), diag::err_regparm_mismatch)
3915 << NewType->getRegParmType()
3916 << OldType->getRegParmType();
3917 Diag(OldLocation, diag::note_previous_declaration);
3918 return true;
3919 }
3920
3921 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3922 RequiresAdjustment = true;
3923 }
3924
3925 // Merge ns_returns_retained attribute.
3926 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3927 if (NewTypeInfo.getProducesResult()) {
3928 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3929 << "'ns_returns_retained'";
3930 Diag(OldLocation, diag::note_previous_declaration);
3931 return true;
3932 }
3933
3934 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3935 RequiresAdjustment = true;
3936 }
3937
3938 if (OldTypeInfo.getNoCallerSavedRegs() !=
3939 NewTypeInfo.getNoCallerSavedRegs()) {
3940 if (NewTypeInfo.getNoCallerSavedRegs()) {
3941 AnyX86NoCallerSavedRegistersAttr *Attr =
3942 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3943 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3944 Diag(OldLocation, diag::note_previous_declaration);
3945 return true;
3946 }
3947
3948 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3949 RequiresAdjustment = true;
3950 }
3951
3952 if (RequiresAdjustment) {
3953 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3954 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3955 New->setType(QualType(AdjustedType, 0));
3956 NewQType = Context.getCanonicalType(New->getType());
3957 }
3958
3959 // If this redeclaration makes the function inline, we may need to add it to
3960 // UndefinedButUsed.
3961 if (!Old->isInlined() && New->isInlined() && !New->hasAttr<GNUInlineAttr>() &&
3962 !getLangOpts().GNUInline && Old->isUsed(false) && !Old->isDefined() &&
3963 !New->isThisDeclarationADefinition() && !Old->isInAnotherModuleUnit())
3964 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3965 SourceLocation()));
3966
3967 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3968 // about it.
3969 if (New->hasAttr<GNUInlineAttr>() &&
3970 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3971 UndefinedButUsed.erase(Old->getCanonicalDecl());
3972 }
3973
3974 // If pass_object_size params don't match up perfectly, this isn't a valid
3975 // redeclaration.
3976 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3978 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3979 << New->getDeclName();
3980 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3981 return true;
3982 }
3983
3984 QualType OldQTypeForComparison = OldQType;
3985 if (Context.hasAnyFunctionEffects()) {
3986 const auto OldFX = Old->getFunctionEffects();
3987 const auto NewFX = New->getFunctionEffects();
3988 if (OldFX != NewFX) {
3989 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
3990 for (const auto &Diff : Diffs) {
3991 if (Diff.shouldDiagnoseRedeclaration(*Old, OldFX, *New, NewFX)) {
3992 Diag(New->getLocation(),
3993 diag::warn_mismatched_func_effect_redeclaration)
3994 << Diff.effectName();
3995 Diag(Old->getLocation(), diag::note_previous_declaration);
3996 }
3997 }
3998 // Following a warning, we could skip merging effects from the previous
3999 // declaration, but that would trigger an additional "conflicting types"
4000 // error.
4001 if (const auto *NewFPT = NewQType->getAs<FunctionProtoType>()) {
4003 FunctionEffectSet MergedFX =
4004 FunctionEffectSet::getUnion(OldFX, NewFX, MergeErrs);
4005 if (!MergeErrs.empty())
4006 diagnoseFunctionEffectMergeConflicts(MergeErrs, New->getLocation(),
4007 Old->getLocation());
4008
4009 FunctionProtoType::ExtProtoInfo EPI = NewFPT->getExtProtoInfo();
4010 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
4011 QualType ModQT = Context.getFunctionType(NewFPT->getReturnType(),
4012 NewFPT->getParamTypes(), EPI);
4013
4014 New->setType(ModQT);
4015 NewQType = New->getType();
4016
4017 // Revise OldQTForComparison to include the merged effects,
4018 // so as not to fail due to differences later.
4019 if (const auto *OldFPT = OldQType->getAs<FunctionProtoType>()) {
4020 EPI = OldFPT->getExtProtoInfo();
4021 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
4022 OldQTypeForComparison = Context.getFunctionType(
4023 OldFPT->getReturnType(), OldFPT->getParamTypes(), EPI);
4024 }
4025 if (OldFX.empty()) {
4026 // A redeclaration may add the attribute to a previously seen function
4027 // body which needs to be verified.
4028 maybeAddDeclWithEffects(Old, MergedFX);
4029 }
4030 }
4031 }
4032 }
4033
4034 if (getLangOpts().CPlusPlus) {
4035 OldQType = Context.getCanonicalType(Old->getType());
4036 NewQType = Context.getCanonicalType(New->getType());
4037
4038 // Go back to the type source info to compare the declared return types,
4039 // per C++1y [dcl.type.auto]p13:
4040 // Redeclarations or specializations of a function or function template
4041 // with a declared return type that uses a placeholder type shall also
4042 // use that placeholder, not a deduced type.
4043 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
4044 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
4045 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
4046 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
4047 OldDeclaredReturnType)) {
4048 QualType ResQT;
4049 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
4050 OldDeclaredReturnType->isObjCObjectPointerType())
4051 // FIXME: This does the wrong thing for a deduced return type.
4052 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
4053 if (ResQT.isNull()) {
4054 if (New->isCXXClassMember() && New->isOutOfLine())
4055 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
4056 << New << New->getReturnTypeSourceRange();
4057 else if (Old->isExternC() && New->isExternC() &&
4058 !Old->hasAttr<OverloadableAttr>() &&
4059 !New->hasAttr<OverloadableAttr>())
4060 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4061 else
4062 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
4063 << New->getReturnTypeSourceRange();
4064 Diag(OldLocation, PrevDiag) << Old << Old->getType()
4065 << Old->getReturnTypeSourceRange();
4066 return true;
4067 }
4068 else
4069 NewQType = ResQT;
4070 }
4071
4072 QualType OldReturnType = OldType->getReturnType();
4073 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
4074 if (OldReturnType != NewReturnType) {
4075 // If this function has a deduced return type and has already been
4076 // defined, copy the deduced value from the old declaration.
4077 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
4078 if (OldAT && OldAT->isDeduced()) {
4079 QualType DT = OldAT->getDeducedType();
4080 if (DT.isNull()) {
4081 New->setType(SubstAutoTypeDependent(New->getType()));
4082 NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
4083 } else {
4084 New->setType(SubstAutoType(New->getType(), DT));
4085 NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
4086 }
4087 }
4088 }
4089
4090 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
4091 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
4092 if (OldMethod && NewMethod) {
4093 // Preserve triviality.
4094 NewMethod->setTrivial(OldMethod->isTrivial());
4095
4096 // MSVC allows explicit template specialization at class scope:
4097 // 2 CXXMethodDecls referring to the same function will be injected.
4098 // We don't want a redeclaration error.
4099 bool IsClassScopeExplicitSpecialization =
4100 OldMethod->isFunctionTemplateSpecialization() &&
4102 bool isFriend = NewMethod->getFriendObjectKind();
4103
4104 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
4105 !IsClassScopeExplicitSpecialization) {
4106 // -- Member function declarations with the same name and the
4107 // same parameter types cannot be overloaded if any of them
4108 // is a static member function declaration.
4109 if (OldMethod->isStatic() != NewMethod->isStatic()) {
4110 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
4111 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4112 return true;
4113 }
4114
4115 // C++ [class.mem]p1:
4116 // [...] A member shall not be declared twice in the
4117 // member-specification, except that a nested class or member
4118 // class template can be declared and then later defined.
4119 if (!inTemplateInstantiation()) {
4120 unsigned NewDiag;
4121 if (isa<CXXConstructorDecl>(OldMethod))
4122 NewDiag = diag::err_constructor_redeclared;
4123 else if (isa<CXXDestructorDecl>(NewMethod))
4124 NewDiag = diag::err_destructor_redeclared;
4125 else if (isa<CXXConversionDecl>(NewMethod))
4126 NewDiag = diag::err_conv_function_redeclared;
4127 else
4128 NewDiag = diag::err_member_redeclared;
4129
4130 Diag(New->getLocation(), NewDiag);
4131 } else {
4132 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
4133 << New << New->getType();
4134 }
4135 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4136 return true;
4137
4138 // Complain if this is an explicit declaration of a special
4139 // member that was initially declared implicitly.
4140 //
4141 // As an exception, it's okay to befriend such methods in order
4142 // to permit the implicit constructor/destructor/operator calls.
4143 } else if (OldMethod->isImplicit()) {
4144 if (isFriend) {
4145 NewMethod->setImplicit();
4146 } else {
4147 Diag(NewMethod->getLocation(),
4148 diag::err_definition_of_implicitly_declared_member)
4149 << New << getSpecialMember(OldMethod);
4150 return true;
4151 }
4152 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
4153 Diag(NewMethod->getLocation(),
4154 diag::err_definition_of_explicitly_defaulted_member)
4155 << getSpecialMember(OldMethod);
4156 return true;
4157 }
4158 }
4159
4160 // C++1z [over.load]p2
4161 // Certain function declarations cannot be overloaded:
4162 // -- Function declarations that differ only in the return type,
4163 // the exception specification, or both cannot be overloaded.
4164
4165 // Check the exception specifications match. This may recompute the type of
4166 // both Old and New if it resolved exception specifications, so grab the
4167 // types again after this. Because this updates the type, we do this before
4168 // any of the other checks below, which may update the "de facto" NewQType
4169 // but do not necessarily update the type of New.
4171 return true;
4172
4173 // C++11 [dcl.attr.noreturn]p1:
4174 // The first declaration of a function shall specify the noreturn
4175 // attribute if any declaration of that function specifies the noreturn
4176 // attribute.
4177 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4178 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4179 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
4180 << NRA;
4181 Diag(Old->getLocation(), diag::note_previous_declaration);
4182 }
4183
4184 // C++11 [dcl.attr.depend]p2:
4185 // The first declaration of a function shall specify the
4186 // carries_dependency attribute for its declarator-id if any declaration
4187 // of the function specifies the carries_dependency attribute.
4188 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
4189 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
4190 Diag(CDA->getLocation(),
4191 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
4192 Diag(Old->getFirstDecl()->getLocation(),
4193 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
4194 }
4195
4196 // SYCL 2020 section 5.10.1, "SYCL functions and member functions linkage":
4197 // When a function is declared with SYCL_EXTERNAL, that macro must be
4198 // used on the first declaration of that function in the translation unit.
4199 // Redeclarations of the function in the same translation unit may
4200 // optionally use SYCL_EXTERNAL, but this is not required.
4201 const SYCLExternalAttr *SEA = New->getAttr<SYCLExternalAttr>();
4202 if (SEA && !Old->hasAttr<SYCLExternalAttr>()) {
4203 Diag(SEA->getLocation(), diag::warn_sycl_external_missing_on_first_decl)
4204 << SEA;
4205 Diag(Old->getLocation(), diag::note_previous_declaration);
4206 }
4207
4208 // (C++98 8.3.5p3):
4209 // All declarations for a function shall agree exactly in both the
4210 // return type and the parameter-type-list.
4211 // We also want to respect all the extended bits except noreturn.
4212
4213 // noreturn should now match unless the old type info didn't have it.
4214 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4215 auto *OldType = OldQTypeForComparison->castAs<FunctionProtoType>();
4216 const FunctionType *OldTypeForComparison
4217 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
4218 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4219 assert(OldQTypeForComparison.isCanonical());
4220 }
4221
4223 // As a special case, retain the language linkage from previous
4224 // declarations of a friend function as an extension.
4225 //
4226 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4227 // and is useful because there's otherwise no way to specify language
4228 // linkage within class scope.
4229 //
4230 // Check cautiously as the friend object kind isn't yet complete.
4231 if (New->getFriendObjectKind() != Decl::FOK_None) {
4232 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
4233 Diag(OldLocation, PrevDiag);
4234 } else {
4235 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4236 Diag(OldLocation, PrevDiag);
4237 return true;
4238 }
4239 }
4240
4241 // HLSL check parameters for matching ABI specifications.
4242 if (getLangOpts().HLSL) {
4243 if (HLSL().CheckCompatibleParameterABI(New, Old))
4244 return true;
4245
4246 // If no errors are generated when checking parameter ABIs we can check if
4247 // the two declarations have the same type ignoring the ABIs and if so,
4248 // the declarations can be merged. This case for merging is only valid in
4249 // HLSL because there are no valid cases of merging mismatched parameter
4250 // ABIs except the HLSL implicit in and explicit in.
4251 if (Context.hasSameFunctionTypeIgnoringParamABI(OldQTypeForComparison,
4252 NewQType))
4253 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4254 // Fall through for conflicting redeclarations and redefinitions.
4255 }
4256
4257 // If the function types are compatible, merge the declarations. Ignore the
4258 // exception specifier because it was already checked above in
4259 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4260 // about incompatible types under -fms-compatibility.
4261 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
4262 NewQType))
4263 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4264
4265 // If the types are imprecise (due to dependent constructs in friends or
4266 // local extern declarations), it's OK if they differ. We'll check again
4267 // during instantiation.
4268 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
4269 return false;
4270
4271 // Fall through for conflicting redeclarations and redefinitions.
4272 }
4273
4274 // C: Function types need to be compatible, not identical. This handles
4275 // duplicate function decls like "void f(int); void f(enum X);" properly.
4276 if (!getLangOpts().CPlusPlus) {
4277 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4278 // type is specified by a function definition that contains a (possibly
4279 // empty) identifier list, both shall agree in the number of parameters
4280 // and the type of each parameter shall be compatible with the type that
4281 // results from the application of default argument promotions to the
4282 // type of the corresponding identifier. ...
4283 // This cannot be handled by ASTContext::typesAreCompatible() because that
4284 // doesn't know whether the function type is for a definition or not when
4285 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4286 // we need to cover here is that the number of arguments agree as the
4287 // default argument promotion rules were already checked by
4288 // ASTContext::typesAreCompatible().
4289 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4290 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4291 if (Old->hasInheritedPrototype())
4292 Old = Old->getCanonicalDecl();
4293 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4294 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
4295 return true;
4296 }
4297
4298 // If we are merging two functions where only one of them has a prototype,
4299 // we may have enough information to decide to issue a diagnostic that the
4300 // function without a prototype will change behavior in C23. This handles
4301 // cases like:
4302 // void i(); void i(int j);
4303 // void i(int j); void i();
4304 // void i(); void i(int j) {}
4305 // See ActOnFinishFunctionBody() for other cases of the behavior change
4306 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4307 // type without a prototype.
4308 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4309 !New->isImplicit() && !Old->isImplicit()) {
4310 const FunctionDecl *WithProto, *WithoutProto;
4311 if (New->hasWrittenPrototype()) {
4312 WithProto = New;
4313 WithoutProto = Old;
4314 } else {
4315 WithProto = Old;
4316 WithoutProto = New;
4317 }
4318
4319 if (WithProto->getNumParams() != 0) {
4320 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4321 // The one without the prototype will be changing behavior in C23, so
4322 // warn about that one so long as it's a user-visible declaration.
4323 bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4324 if (WithoutProto == New)
4325 IsWithoutProtoADef = NewDeclIsDefn;
4326 else
4327 IsWithProtoADef = NewDeclIsDefn;
4328 Diag(WithoutProto->getLocation(),
4329 diag::warn_non_prototype_changes_behavior)
4330 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4331 << (WithoutProto == Old) << IsWithProtoADef;
4332
4333 // The reason the one without the prototype will be changing behavior
4334 // is because of the one with the prototype, so note that so long as
4335 // it's a user-visible declaration. There is one exception to this:
4336 // when the new declaration is a definition without a prototype, the
4337 // old declaration with a prototype is not the cause of the issue,
4338 // and that does not need to be noted because the one with a
4339 // prototype will not change behavior in C23.
4340 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4341 !IsWithoutProtoADef)
4342 Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
4343 }
4344 }
4345 }
4346
4347 if (Context.typesAreCompatible(OldQType, NewQType)) {
4348 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4349 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4350 const FunctionProtoType *OldProto = nullptr;
4351 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
4352 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
4353 // The old declaration provided a function prototype, but the
4354 // new declaration does not. Merge in the prototype.
4355 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4356 NewQType = Context.getFunctionType(NewFuncType->getReturnType(),
4357 OldProto->getParamTypes(),
4358 OldProto->getExtProtoInfo());
4359 New->setType(NewQType);
4360 New->setHasInheritedPrototype();
4361
4362 // Synthesize parameters with the same types.
4364 for (const auto &ParamType : OldProto->param_types()) {
4366 Context, New, SourceLocation(), SourceLocation(), nullptr,
4367 ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4368 Param->setScopeInfo(0, Params.size());
4369 Param->setImplicit();
4370 Params.push_back(Param);
4371 }
4372
4373 New->setParams(Params);
4374 }
4375
4376 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4377 }
4378 }
4379
4380 // Check if the function types are compatible when pointer size address
4381 // spaces are ignored.
4382 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4383 return false;
4384
4385 // GNU C permits a K&R definition to follow a prototype declaration
4386 // if the declared types of the parameters in the K&R definition
4387 // match the types in the prototype declaration, even when the
4388 // promoted types of the parameters from the K&R definition differ
4389 // from the types in the prototype. GCC then keeps the types from
4390 // the prototype.
4391 //
4392 // If a variadic prototype is followed by a non-variadic K&R definition,
4393 // the K&R definition becomes variadic. This is sort of an edge case, but
4394 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4395 // C99 6.9.1p8.
4396 if (!getLangOpts().CPlusPlus &&
4397 Old->hasPrototype() && !New->hasPrototype() &&
4398 New->getType()->getAs<FunctionProtoType>() &&
4399 Old->getNumParams() == New->getNumParams()) {
4402 const FunctionProtoType *OldProto
4403 = Old->getType()->getAs<FunctionProtoType>();
4404 const FunctionProtoType *NewProto
4405 = New->getType()->getAs<FunctionProtoType>();
4406
4407 // Determine whether this is the GNU C extension.
4408 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4409 NewProto->getReturnType());
4410 bool LooseCompatible = !MergedReturn.isNull();
4411 for (unsigned Idx = 0, End = Old->getNumParams();
4412 LooseCompatible && Idx != End; ++Idx) {
4413 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4414 ParmVarDecl *NewParm = New->getParamDecl(Idx);
4415 if (Context.typesAreCompatible(OldParm->getType(),
4416 NewProto->getParamType(Idx))) {
4417 ArgTypes.push_back(NewParm->getType());
4418 } else if (Context.typesAreCompatible(OldParm->getType(),
4419 NewParm->getType(),
4420 /*CompareUnqualified=*/true)) {
4421 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4422 NewProto->getParamType(Idx) };
4423 Warnings.push_back(Warn);
4424 ArgTypes.push_back(NewParm->getType());
4425 } else
4426 LooseCompatible = false;
4427 }
4428
4429 if (LooseCompatible) {
4430 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4431 Diag(Warnings[Warn].NewParm->getLocation(),
4432 diag::ext_param_promoted_not_compatible_with_prototype)
4433 << Warnings[Warn].PromotedType
4434 << Warnings[Warn].OldParm->getType();
4435 if (Warnings[Warn].OldParm->getLocation().isValid())
4436 Diag(Warnings[Warn].OldParm->getLocation(),
4437 diag::note_previous_declaration);
4438 }
4439
4440 if (MergeTypeWithOld)
4441 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4442 OldProto->getExtProtoInfo()));
4443 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4444 }
4445
4446 // Fall through to diagnose conflicting types.
4447 }
4448
4449 // A function that has already been declared has been redeclared or
4450 // defined with a different type; show an appropriate diagnostic.
4451
4452 // If the previous declaration was an implicitly-generated builtin
4453 // declaration, then at the very least we should use a specialized note.
4454 unsigned BuiltinID;
4455 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4456 // If it's actually a library-defined builtin function like 'malloc'
4457 // or 'printf', just warn about the incompatible redeclaration.
4458 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4459 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4460 Diag(OldLocation, diag::note_previous_builtin_declaration)
4461 << Old << Old->getType();
4462 return false;
4463 }
4464
4465 PrevDiag = diag::note_previous_builtin_declaration;
4466 }
4467
4468 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4469 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4470 return true;
4471}
4472
4474 Scope *S, bool MergeTypeWithOld) {
4475 // Merge the attributes
4477
4478 // Merge "pure" flag.
4479 if (Old->isPureVirtual())
4480 New->setIsPureVirtual();
4481
4482 // Merge "used" flag.
4483 if (Old->getMostRecentDecl()->isUsed(false))
4484 New->setIsUsed();
4485
4486 // Merge attributes from the parameters. These can mismatch with K&R
4487 // declarations.
4488 if (New->getNumParams() == Old->getNumParams())
4489 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4490 ParmVarDecl *NewParam = New->getParamDecl(i);
4491 ParmVarDecl *OldParam = Old->getParamDecl(i);
4492 mergeParamDeclAttributes(NewParam, OldParam, *this);
4493 mergeParamDeclTypes(NewParam, OldParam, *this);
4494 }
4495
4496 if (getLangOpts().CPlusPlus)
4497 return MergeCXXFunctionDecl(New, Old, S);
4498
4499 // Merge the function types so the we get the composite types for the return
4500 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4501 // was visible.
4502 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4503 if (!Merged.isNull() && MergeTypeWithOld)
4504 New->setType(Merged);
4505
4506 return false;
4507}
4508
4510 ObjCMethodDecl *oldMethod) {
4511 // Merge the attributes, including deprecated/unavailable
4512 AvailabilityMergeKind MergeKind =
4514 ? (oldMethod->isOptional()
4517 : isa<ObjCImplDecl>(newMethod->getDeclContext())
4520
4521 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4522
4523 // Merge attributes from the parameters.
4525 oe = oldMethod->param_end();
4527 ni = newMethod->param_begin(), ne = newMethod->param_end();
4528 ni != ne && oi != oe; ++ni, ++oi)
4529 mergeParamDeclAttributes(*ni, *oi, *this);
4530
4531 ObjC().CheckObjCMethodOverride(newMethod, oldMethod);
4532}
4533
4535 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4536
4537 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
4538 ? diag::err_redefinition_different_type
4539 : diag::err_redeclaration_different_type)
4540 << New->getDeclName() << New->getType() << Old->getType();
4541
4542 diag::kind PrevDiag;
4543 SourceLocation OldLocation;
4544 std::tie(PrevDiag, OldLocation)
4546 S.Diag(OldLocation, PrevDiag) << Old << Old->getType();
4547 New->setInvalidDecl();
4548}
4549
4551 bool MergeTypeWithOld) {
4552 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4553 return;
4554
4555 QualType MergedT;
4556 if (getLangOpts().CPlusPlus) {
4557 if (New->getType()->isUndeducedType()) {
4558 // We don't know what the new type is until the initializer is attached.
4559 return;
4560 } else if (Context.hasSameType(New->getType(), Old->getType())) {
4561 // These could still be something that needs exception specs checked.
4562 return MergeVarDeclExceptionSpecs(New, Old);
4563 }
4564 // C++ [basic.link]p10:
4565 // [...] the types specified by all declarations referring to a given
4566 // object or function shall be identical, except that declarations for an
4567 // array object can specify array types that differ by the presence or
4568 // absence of a major array bound (8.3.4).
4569 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4570 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4571 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4572
4573 // We are merging a variable declaration New into Old. If it has an array
4574 // bound, and that bound differs from Old's bound, we should diagnose the
4575 // mismatch.
4576 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4577 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4578 PrevVD = PrevVD->getPreviousDecl()) {
4579 QualType PrevVDTy = PrevVD->getType();
4580 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4581 continue;
4582
4583 if (!Context.hasSameType(New->getType(), PrevVDTy))
4584 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4585 }
4586 }
4587
4588 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4589 if (Context.hasSameType(OldArray->getElementType(),
4590 NewArray->getElementType()))
4591 MergedT = New->getType();
4592 }
4593 // FIXME: Check visibility. New is hidden but has a complete type. If New
4594 // has no array bound, it should not inherit one from Old, if Old is not
4595 // visible.
4596 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4597 if (Context.hasSameType(OldArray->getElementType(),
4598 NewArray->getElementType()))
4599 MergedT = Old->getType();
4600 }
4601 }
4602 else if (New->getType()->isObjCObjectPointerType() &&
4603 Old->getType()->isObjCObjectPointerType()) {
4604 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4605 Old->getType());
4606 }
4607 } else {
4608 // C 6.2.7p2:
4609 // All declarations that refer to the same object or function shall have
4610 // compatible type.
4611 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4612 }
4613 if (MergedT.isNull()) {
4614 // It's OK if we couldn't merge types if either type is dependent, for a
4615 // block-scope variable. In other cases (static data members of class
4616 // templates, variable templates, ...), we require the types to be
4617 // equivalent.
4618 // FIXME: The C++ standard doesn't say anything about this.
4619 if ((New->getType()->isDependentType() ||
4620 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4621 // If the old type was dependent, we can't merge with it, so the new type
4622 // becomes dependent for now. We'll reproduce the original type when we
4623 // instantiate the TypeSourceInfo for the variable.
4624 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4625 New->setType(Context.DependentTy);
4626 return;
4627 }
4628 return diagnoseVarDeclTypeMismatch(*this, New, Old);
4629 }
4630
4631 // Don't actually update the type on the new declaration if the old
4632 // declaration was an extern declaration in a different scope.
4633 if (MergeTypeWithOld)
4634 New->setType(MergedT);
4635}
4636
4637static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4639 // C11 6.2.7p4:
4640 // For an identifier with internal or external linkage declared
4641 // in a scope in which a prior declaration of that identifier is
4642 // visible, if the prior declaration specifies internal or
4643 // external linkage, the type of the identifier at the later
4644 // declaration becomes the composite type.
4645 //
4646 // If the variable isn't visible, we do not merge with its type.
4647 if (Previous.isShadowed())
4648 return false;
4649
4650 if (S.getLangOpts().CPlusPlus) {
4651 // C++11 [dcl.array]p3:
4652 // If there is a preceding declaration of the entity in the same
4653 // scope in which the bound was specified, an omitted array bound
4654 // is taken to be the same as in that earlier declaration.
4655 return NewVD->isPreviousDeclInSameBlockScope() ||
4656 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4658 } else {
4659 // If the old declaration was function-local, don't merge with its
4660 // type unless we're in the same function.
4661 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4662 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4663 }
4664}
4665
4667 // If the new decl is already invalid, don't do any other checking.
4668 if (New->isInvalidDecl())
4669 return;
4670
4671 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4672 return;
4673
4674 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4675
4676 // Verify the old decl was also a variable or variable template.
4677 VarDecl *Old = nullptr;
4678 VarTemplateDecl *OldTemplate = nullptr;
4679 if (Previous.isSingleResult()) {
4680 if (NewTemplate) {
4681 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4682 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4683
4684 if (auto *Shadow =
4685 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4686 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4687 return New->setInvalidDecl();
4688 } else {
4689 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4690
4691 if (auto *Shadow =
4692 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4693 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4694 return New->setInvalidDecl();
4695 }
4696 }
4697 if (!Old) {
4698 Diag(New->getLocation(), diag::err_redefinition_different_kind)
4699 << New->getDeclName();
4700 notePreviousDefinition(Previous.getRepresentativeDecl(),
4701 New->getLocation());
4702 return New->setInvalidDecl();
4703 }
4704
4705 // If the old declaration was found in an inline namespace and the new
4706 // declaration was qualified, update the DeclContext to match.
4708
4709 // Ensure the template parameters are compatible.
4710 if (NewTemplate &&
4712 OldTemplate->getTemplateParameters(),
4713 /*Complain=*/true, TPL_TemplateMatch))
4714 return New->setInvalidDecl();
4715
4716 // C++ [class.mem]p1:
4717 // A member shall not be declared twice in the member-specification [...]
4718 //
4719 // Here, we need only consider static data members.
4720 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4721 Diag(New->getLocation(), diag::err_duplicate_member)
4722 << New->getIdentifier();
4723 Diag(Old->getLocation(), diag::note_previous_declaration);
4724 New->setInvalidDecl();
4725 }
4726
4728 // Warn if an already-defined variable is made a weak_import in a subsequent
4729 // declaration
4730 if (New->hasAttr<WeakImportAttr>())
4731 for (auto *D = Old; D; D = D->getPreviousDecl()) {
4732 if (D->isThisDeclarationADefinition() != VarDecl::DeclarationOnly) {
4733 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4734 Diag(D->getLocation(), diag::note_previous_definition);
4735 // Remove weak_import attribute on new declaration.
4736 New->dropAttr<WeakImportAttr>();
4737 break;
4738 }
4739 }
4740
4741 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4742 if (!Old->hasAttr<InternalLinkageAttr>()) {
4743 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4744 << ILA;
4745 Diag(Old->getLocation(), diag::note_previous_declaration);
4746 New->dropAttr<InternalLinkageAttr>();
4747 }
4748
4749 // Merge the types.
4750 VarDecl *MostRecent = Old->getMostRecentDecl();
4751 if (MostRecent != Old) {
4752 MergeVarDeclTypes(New, MostRecent,
4753 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4754 if (New->isInvalidDecl())
4755 return;
4756 }
4757
4759 if (New->isInvalidDecl())
4760 return;
4761
4762 diag::kind PrevDiag;
4763 SourceLocation OldLocation;
4764 std::tie(PrevDiag, OldLocation) =
4766
4767 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4768 if (New->getStorageClass() == SC_Static &&
4769 !New->isStaticDataMember() &&
4770 Old->hasExternalFormalLinkage()) {
4771 if (getLangOpts().MicrosoftExt) {
4772 Diag(New->getLocation(), diag::ext_static_non_static)
4773 << New->getDeclName();
4774 Diag(OldLocation, PrevDiag);
4775 } else {
4776 Diag(New->getLocation(), diag::err_static_non_static)
4777 << New->getDeclName();
4778 Diag(OldLocation, PrevDiag);
4779 return New->setInvalidDecl();
4780 }
4781 }
4782 // C99 6.2.2p4:
4783 // For an identifier declared with the storage-class specifier
4784 // extern in a scope in which a prior declaration of that
4785 // identifier is visible,23) if the prior declaration specifies
4786 // internal or external linkage, the linkage of the identifier at
4787 // the later declaration is the same as the linkage specified at
4788 // the prior declaration. If no prior declaration is visible, or
4789 // if the prior declaration specifies no linkage, then the
4790 // identifier has external linkage.
4791 if (New->hasExternalStorage() && Old->hasLinkage())
4792 /* Okay */;
4793 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4794 !New->isStaticDataMember() &&
4796 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4797 Diag(OldLocation, PrevDiag);
4798 return New->setInvalidDecl();
4799 }
4800
4801 // Check if extern is followed by non-extern and vice-versa.
4802 if (New->hasExternalStorage() &&
4803 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4804 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4805 Diag(OldLocation, PrevDiag);
4806 return New->setInvalidDecl();
4807 }
4808 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4809 !New->hasExternalStorage()) {
4810 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4811 Diag(OldLocation, PrevDiag);
4812 return New->setInvalidDecl();
4813 }
4814
4816 return;
4817
4818 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4819
4820 // FIXME: The test for external storage here seems wrong? We still
4821 // need to check for mismatches.
4822 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4823 // Don't complain about out-of-line definitions of static members.
4824 !(Old->getLexicalDeclContext()->isRecord() &&
4825 !New->getLexicalDeclContext()->isRecord())) {
4826 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4827 Diag(OldLocation, PrevDiag);
4828 return New->setInvalidDecl();
4829 }
4830
4831 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4832 if (VarDecl *Def = Old->getDefinition()) {
4833 // C++1z [dcl.fcn.spec]p4:
4834 // If the definition of a variable appears in a translation unit before
4835 // its first declaration as inline, the program is ill-formed.
4836 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4837 Diag(Def->getLocation(), diag::note_previous_definition);
4838 }
4839 }
4840
4841 // If this redeclaration makes the variable inline, we may need to add it to
4842 // UndefinedButUsed.
4843 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4844 !Old->getDefinition() && !New->isThisDeclarationADefinition() &&
4845 !Old->isInAnotherModuleUnit())
4846 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4847 SourceLocation()));
4848
4849 if (New->getTLSKind() != Old->getTLSKind()) {
4850 if (!Old->getTLSKind()) {
4851 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4852 Diag(OldLocation, PrevDiag);
4853 } else if (!New->getTLSKind()) {
4854 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4855 Diag(OldLocation, PrevDiag);
4856 } else {
4857 // Do not allow redeclaration to change the variable between requiring
4858 // static and dynamic initialization.
4859 // FIXME: GCC allows this, but uses the TLS keyword on the first
4860 // declaration to determine the kind. Do we need to be compatible here?
4861 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4862 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4863 Diag(OldLocation, PrevDiag);
4864 }
4865 }
4866
4867 // C++ doesn't have tentative definitions, so go right ahead and check here.
4868 if (getLangOpts().CPlusPlus) {
4869 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4870 Old->getCanonicalDecl()->isConstexpr()) {
4871 // This definition won't be a definition any more once it's been merged.
4872 Diag(New->getLocation(),
4873 diag::warn_deprecated_redundant_constexpr_static_def);
4874 } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4875 VarDecl *Def = Old->getDefinition();
4876 if (Def && checkVarDeclRedefinition(Def, New))
4877 return;
4878 }
4879 } else {
4880 // C++ may not have a tentative definition rule, but it has a different
4881 // rule about what constitutes a definition in the first place. See
4882 // [basic.def]p2 for details, but the basic idea is: if the old declaration
4883 // contains the extern specifier and doesn't have an initializer, it's fine
4884 // in C++.
4885 if (Old->getStorageClass() != SC_Extern || Old->hasInit()) {
4886 Diag(New->getLocation(), diag::warn_cxx_compat_tentative_definition)
4887 << New;
4888 Diag(Old->getLocation(), diag::note_previous_declaration);
4889 }
4890 }
4891
4893 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4894 Diag(OldLocation, PrevDiag);
4895 New->setInvalidDecl();
4896 return;
4897 }
4898
4899 // Merge "used" flag.
4900 if (Old->getMostRecentDecl()->isUsed(false))
4901 New->setIsUsed();
4902
4903 // Keep a chain of previous declarations.
4904 New->setPreviousDecl(Old);
4905 if (NewTemplate)
4906 NewTemplate->setPreviousDecl(OldTemplate);
4907
4908 // Inherit access appropriately.
4909 New->setAccess(Old->getAccess());
4910 if (NewTemplate)
4911 NewTemplate->setAccess(New->getAccess());
4912
4913 if (Old->isInline())
4914 New->setImplicitlyInline();
4915}
4916
4919 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4920 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4921 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4922 auto FOld = SrcMgr.getFileEntryRefForID(FOldDecLoc.first);
4923 auto &HSI = PP.getHeaderSearchInfo();
4924 StringRef HdrFilename =
4925 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4926
4927 auto noteFromModuleOrInclude = [&](Module *Mod,
4928 SourceLocation IncLoc) -> bool {
4929 // Redefinition errors with modules are common with non modular mapped
4930 // headers, example: a non-modular header H in module A that also gets
4931 // included directly in a TU. Pointing twice to the same header/definition
4932 // is confusing, try to get better diagnostics when modules is on.
4933 if (IncLoc.isValid()) {
4934 if (Mod) {
4935 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4936 << HdrFilename.str() << Mod->getFullModuleName();
4937 if (!Mod->DefinitionLoc.isInvalid())
4938 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4939 << Mod->getFullModuleName();
4940 } else {
4941 Diag(IncLoc, diag::note_redefinition_include_same_file)
4942 << HdrFilename.str();
4943 }
4944 return true;
4945 }
4946
4947 return false;
4948 };
4949
4950 // Is it the same file and same offset? Provide more information on why
4951 // this leads to a redefinition error.
4952 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4953 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4954 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4955 bool EmittedDiag =
4956 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4957 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4958
4959 // If the header has no guards, emit a note suggesting one.
4960 if (FOld && !HSI.isFileMultipleIncludeGuarded(*FOld))
4961 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4962
4963 if (EmittedDiag)
4964 return;
4965 }
4966
4967 // Redefinition coming from different files or couldn't do better above.
4968 if (Old->getLocation().isValid())
4969 Diag(Old->getLocation(), diag::note_previous_definition);
4970}
4971
4973 if (!hasVisibleDefinition(Old) &&
4974 (New->getFormalLinkage() == Linkage::Internal || New->isInline() ||
4976 New->getDescribedVarTemplate() || New->getNumTemplateParameterLists() ||
4977 New->getDeclContext()->isDependentContext() ||
4978 New->hasAttr<SelectAnyAttr>())) {
4979 // The previous definition is hidden, and multiple definitions are
4980 // permitted (in separate TUs). Demote this to a declaration.
4981 New->demoteThisDefinitionToDeclaration();
4982
4983 // Make the canonical definition visible.
4984 if (auto *OldTD = Old->getDescribedVarTemplate())
4987 return false;
4988 } else {
4989 Diag(New->getLocation(), diag::err_redefinition) << New;
4990 notePreviousDefinition(Old, New->getLocation());
4991 New->setInvalidDecl();
4992 return true;
4993 }
4994}
4995
4997 DeclSpec &DS,
4998 const ParsedAttributesView &DeclAttrs,
4999 RecordDecl *&AnonRecord) {
5001 S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);
5002}
5003
5004// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
5005// disambiguate entities defined in different scopes.
5006// While the VS2015 ABI fixes potential miscompiles, it is also breaks
5007// compatibility.
5008// We will pick our mangling number depending on which version of MSVC is being
5009// targeted.
5010static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
5014}
5015
5016void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
5017 if (!Context.getLangOpts().CPlusPlus)
5018 return;
5019
5020 if (isa<CXXRecordDecl>(Tag->getParent())) {
5021 // If this tag is the direct child of a class, number it if
5022 // it is anonymous.
5023 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
5024 return;
5026 Context.getManglingNumberContext(Tag->getParent());
5027 Context.setManglingNumber(
5028 Tag, MCtx.getManglingNumber(
5029 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
5030 return;
5031 }
5032
5033 // If this tag isn't a direct child of a class, number it if it is local.
5035 Decl *ManglingContextDecl;
5036 std::tie(MCtx, ManglingContextDecl) =
5037 getCurrentMangleNumberContext(Tag->getDeclContext());
5038 if (MCtx) {
5039 Context.setManglingNumber(
5040 Tag, MCtx->getManglingNumber(
5041 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
5042 }
5043}
5044
5045namespace {
5046struct NonCLikeKind {
5047 enum {
5048 None,
5049 BaseClass,
5050 DefaultMemberInit,
5051 Lambda,
5052 Friend,
5053 OtherMember,
5054 Invalid,
5055 } Kind = None;
5056 SourceRange Range;
5057
5058 explicit operator bool() { return Kind != None; }
5059};
5060}
5061
5062/// Determine whether a class is C-like, according to the rules of C++
5063/// [dcl.typedef] for anonymous classes with typedef names for linkage.
5064static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
5065 if (RD->isInvalidDecl())
5066 return {NonCLikeKind::Invalid, {}};
5067
5068 // C++ [dcl.typedef]p9: [P1766R1]
5069 // An unnamed class with a typedef name for linkage purposes shall not
5070 //
5071 // -- have any base classes
5072 if (RD->getNumBases())
5073 return {NonCLikeKind::BaseClass,
5075 RD->bases_end()[-1].getEndLoc())};
5076 bool Invalid = false;
5077 for (Decl *D : RD->decls()) {
5078 // Don't complain about things we already diagnosed.
5079 if (D->isInvalidDecl()) {
5080 Invalid = true;
5081 continue;
5082 }
5083
5084 // -- have any [...] default member initializers
5085 if (auto *FD = dyn_cast<FieldDecl>(D)) {
5086 if (FD->hasInClassInitializer()) {
5087 auto *Init = FD->getInClassInitializer();
5088 return {NonCLikeKind::DefaultMemberInit,
5089 Init ? Init->getSourceRange() : D->getSourceRange()};
5090 }
5091 continue;
5092 }
5093
5094 // FIXME: We don't allow friend declarations. This violates the wording of
5095 // P1766, but not the intent.
5096 if (isa<FriendDecl>(D))
5097 return {NonCLikeKind::Friend, D->getSourceRange()};
5098
5099 // -- declare any members other than non-static data members, member
5100 // enumerations, or member classes,
5102 isa<EnumDecl>(D))
5103 continue;
5104 auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
5105 if (!MemberRD) {
5106 if (D->isImplicit())
5107 continue;
5108 return {NonCLikeKind::OtherMember, D->getSourceRange()};
5109 }
5110
5111 // -- contain a lambda-expression,
5112 if (MemberRD->isLambda())
5113 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
5114
5115 // and all member classes shall also satisfy these requirements
5116 // (recursively).
5117 if (MemberRD->isThisDeclarationADefinition()) {
5118 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
5119 return Kind;
5120 }
5121 }
5122
5123 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
5124}
5125
5127 TypedefNameDecl *NewTD) {
5128 if (TagFromDeclSpec->isInvalidDecl())
5129 return;
5130
5131 // Do nothing if the tag already has a name for linkage purposes.
5132 if (TagFromDeclSpec->hasNameForLinkage())
5133 return;
5134
5135 // A well-formed anonymous tag must always be a TagUseKind::Definition.
5136 assert(TagFromDeclSpec->isThisDeclarationADefinition());
5137
5138 // The type must match the tag exactly; no qualifiers allowed.
5139 if (!Context.hasSameType(NewTD->getUnderlyingType(),
5140 Context.getCanonicalTagType(TagFromDeclSpec))) {
5141 if (getLangOpts().CPlusPlus)
5142 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
5143 return;
5144 }
5145
5146 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
5147 // An unnamed class with a typedef name for linkage purposes shall [be
5148 // C-like].
5149 //
5150 // FIXME: Also diagnose if we've already computed the linkage. That ideally
5151 // shouldn't happen, but there are constructs that the language rule doesn't
5152 // disallow for which we can't reasonably avoid computing linkage early.
5153 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
5154 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
5155 : NonCLikeKind();
5156 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
5157 if (NonCLike || ChangesLinkage) {
5158 if (NonCLike.Kind == NonCLikeKind::Invalid)
5159 return;
5160
5161 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
5162 if (ChangesLinkage) {
5163 // If the linkage changes, we can't accept this as an extension.
5164 if (NonCLike.Kind == NonCLikeKind::None)
5165 DiagID = diag::err_typedef_changes_linkage;
5166 else
5167 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
5168 }
5169
5170 SourceLocation FixitLoc =
5171 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
5172 llvm::SmallString<40> TextToInsert;
5173 TextToInsert += ' ';
5174 TextToInsert += NewTD->getIdentifier()->getName();
5175
5176 Diag(FixitLoc, DiagID)
5177 << isa<TypeAliasDecl>(NewTD)
5178 << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
5179 if (NonCLike.Kind != NonCLikeKind::None) {
5180 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
5181 << NonCLike.Kind - 1 << NonCLike.Range;
5182 }
5183 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
5184 << NewTD << isa<TypeAliasDecl>(NewTD);
5185
5186 if (ChangesLinkage)
5187 return;
5188 }
5189
5190 // Otherwise, set this as the anon-decl typedef for the tag.
5191 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
5192
5193 // Now that we have a name for the tag, process API notes again.
5194 ProcessAPINotes(TagFromDeclSpec);
5195}
5196
5197static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {
5199 switch (T) {
5201 return 0;
5203 return 1;
5205 return 2;
5207 return 3;
5208 case DeclSpec::TST_enum:
5209 if (const auto *ED = dyn_cast<EnumDecl>(DS.getRepAsDecl())) {
5210 if (ED->isScopedUsingClassTag())
5211 return 5;
5212 if (ED->isScoped())
5213 return 6;
5214 }
5215 return 4;
5216 default:
5217 llvm_unreachable("unexpected type specifier");
5218 }
5219}
5220
5222 DeclSpec &DS,
5223 const ParsedAttributesView &DeclAttrs,
5224 MultiTemplateParamsArg TemplateParams,
5225 bool IsExplicitInstantiation,
5226 RecordDecl *&AnonRecord,
5227 SourceLocation EllipsisLoc) {
5228 Decl *TagD = nullptr;
5229 TagDecl *Tag = nullptr;
5235 TagD = DS.getRepAsDecl();
5236
5237 if (!TagD) // We probably had an error
5238 return nullptr;
5239
5240 // Note that the above type specs guarantee that the
5241 // type rep is a Decl, whereas in many of the others
5242 // it's a Type.
5243 if (isa<TagDecl>(TagD))
5244 Tag = cast<TagDecl>(TagD);
5245 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
5246 Tag = CTD->getTemplatedDecl();
5247 }
5248
5249 if (Tag) {
5250 handleTagNumbering(Tag, S);
5251 Tag->setFreeStanding();
5252 if (Tag->isInvalidDecl())
5253 return Tag;
5254 }
5255
5256 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5257 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5258 // or incomplete types shall not be restrict-qualified."
5259 if (TypeQuals & DeclSpec::TQ_restrict)
5261 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5262 << DS.getSourceRange();
5263 }
5264
5265 if (DS.isInlineSpecified())
5266 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
5267 << getLangOpts().CPlusPlus17;
5268
5269 if (DS.hasConstexprSpecifier()) {
5270 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5271 // and definitions of functions and variables.
5272 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5273 // the declaration of a function or function template
5274 if (Tag)
5275 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
5277 << static_cast<int>(DS.getConstexprSpecifier());
5278 else if (getLangOpts().C23)
5279 Diag(DS.getConstexprSpecLoc(), diag::err_c23_constexpr_not_variable);
5280 else
5281 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
5282 << static_cast<int>(DS.getConstexprSpecifier());
5283 // Don't emit warnings after this error.
5284 return TagD;
5285 }
5286
5288
5289 if (DS.isFriendSpecified()) {
5290 // If we're dealing with a decl but not a TagDecl, assume that
5291 // whatever routines created it handled the friendship aspect.
5292 if (TagD && !Tag)
5293 return nullptr;
5294 return ActOnFriendTypeDecl(S, DS, TemplateParams, EllipsisLoc);
5295 }
5296
5297 assert(EllipsisLoc.isInvalid() &&
5298 "Friend ellipsis but not friend-specified?");
5299
5300 // Track whether this decl-specifier declares anything.
5301 bool DeclaresAnything = true;
5302
5303 // Handle anonymous struct definitions.
5304 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
5305 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5307 if (getLangOpts().CPlusPlus ||
5308 Record->getDeclContext()->isRecord()) {
5309 // If CurContext is a DeclContext that can contain statements,
5310 // RecursiveASTVisitor won't visit the decls that
5311 // BuildAnonymousStructOrUnion() will put into CurContext.
5312 // Also store them here so that they can be part of the
5313 // DeclStmt that gets created in this case.
5314 // FIXME: Also return the IndirectFieldDecls created by
5315 // BuildAnonymousStructOr union, for the same reason?
5316 if (CurContext->isFunctionOrMethod())
5317 AnonRecord = Record;
5318 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5319 Context.getPrintingPolicy());
5320 }
5321
5322 DeclaresAnything = false;
5323 }
5324 }
5325
5326 // C11 6.7.2.1p2:
5327 // A struct-declaration that does not declare an anonymous structure or
5328 // anonymous union shall contain a struct-declarator-list.
5329 //
5330 // This rule also existed in C89 and C99; the grammar for struct-declaration
5331 // did not permit a struct-declaration without a struct-declarator-list.
5332 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5334 // Check for Microsoft C extension: anonymous struct/union member.
5335 // Handle 2 kinds of anonymous struct/union:
5336 // struct STRUCT;
5337 // union UNION;
5338 // and
5339 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5340 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5341 if ((Tag && Tag->getDeclName()) ||
5343 RecordDecl *Record = Tag ? dyn_cast<RecordDecl>(Tag)
5344 : DS.getRepAsType().get()->getAsRecordDecl();
5345 if (Record && getLangOpts().MicrosoftExt) {
5346 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5347 << Record->isUnion() << DS.getSourceRange();
5349 }
5350
5351 DeclaresAnything = false;
5352 }
5353 }
5354
5355 // Skip all the checks below if we have a type error.
5357 (TagD && TagD->isInvalidDecl()))
5358 return TagD;
5359
5360 if (getLangOpts().CPlusPlus &&
5362 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5363 if (Enum->enumerators().empty() && !Enum->getIdentifier() &&
5364 !Enum->isInvalidDecl())
5365 DeclaresAnything = false;
5366
5367 if (!DS.isMissingDeclaratorOk()) {
5368 // Customize diagnostic for a typedef missing a name.
5370 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5371 << DS.getSourceRange();
5372 else
5373 DeclaresAnything = false;
5374 }
5375
5376 if (DS.isModulePrivateSpecified() &&
5377 Tag && Tag->getDeclContext()->isFunctionOrMethod())
5378 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5379 << Tag->getTagKind()
5381
5383
5384 // C 6.7/2:
5385 // A declaration [...] shall declare at least a declarator [...], a tag,
5386 // or the members of an enumeration.
5387 // C++ [dcl.dcl]p3:
5388 // [If there are no declarators], and except for the declaration of an
5389 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5390 // names into the program, or shall redeclare a name introduced by a
5391 // previous declaration.
5392 if (!DeclaresAnything) {
5393 // In C, we allow this as a (popular) extension / bug. Don't bother
5394 // producing further diagnostics for redundant qualifiers after this.
5395 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5396 ? diag::err_no_declarators
5397 : diag::ext_no_declarators)
5398 << DS.getSourceRange();
5399 return TagD;
5400 }
5401
5402 // C++ [dcl.stc]p1:
5403 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5404 // init-declarator-list of the declaration shall not be empty.
5405 // C++ [dcl.fct.spec]p1:
5406 // If a cv-qualifier appears in a decl-specifier-seq, the
5407 // init-declarator-list of the declaration shall not be empty.
5408 //
5409 // Spurious qualifiers here appear to be valid in C.
5410 unsigned DiagID = diag::warn_standalone_specifier;
5411 if (getLangOpts().CPlusPlus)
5412 DiagID = diag::ext_standalone_specifier;
5413
5414 // Note that a linkage-specification sets a storage class, but
5415 // 'extern "C" struct foo;' is actually valid and not theoretically
5416 // useless.
5417 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5418 if (SCS == DeclSpec::SCS_mutable)
5419 // Since mutable is not a viable storage class specifier in C, there is
5420 // no reason to treat it as an extension. Instead, diagnose as an error.
5421 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5422 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5423 Diag(DS.getStorageClassSpecLoc(), DiagID)
5425 }
5426
5430 if (DS.getTypeQualifiers()) {
5432 Diag(DS.getConstSpecLoc(), DiagID) << "const";
5434 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5435 // Restrict is covered above.
5437 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5439 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5440 }
5441
5442 // Warn about ignored type attributes, for example:
5443 // __attribute__((aligned)) struct A;
5444 // Attributes should be placed after tag to apply to type declaration.
5445 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5446 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5447 if (TypeSpecType == DeclSpec::TST_class ||
5448 TypeSpecType == DeclSpec::TST_struct ||
5449 TypeSpecType == DeclSpec::TST_interface ||
5450 TypeSpecType == DeclSpec::TST_union ||
5451 TypeSpecType == DeclSpec::TST_enum) {
5452
5453 auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) {
5454 unsigned DiagnosticId = diag::warn_declspec_attribute_ignored;
5455 if (AL.isAlignas() && !getLangOpts().CPlusPlus)
5456 DiagnosticId = diag::warn_attribute_ignored;
5457 else if (AL.isRegularKeywordAttribute())
5458 DiagnosticId = diag::err_declspec_keyword_has_no_effect;
5459 else
5460 DiagnosticId = diag::warn_declspec_attribute_ignored;
5461 Diag(AL.getLoc(), DiagnosticId)
5462 << AL << GetDiagnosticTypeSpecifierID(DS);
5463 };
5464
5465 llvm::for_each(DS.getAttributes(), EmitAttributeDiagnostic);
5466 llvm::for_each(DeclAttrs, EmitAttributeDiagnostic);
5467 }
5468 }
5469
5470 return TagD;
5471}
5472
5473/// We are trying to inject an anonymous member into the given scope;
5474/// check if there's an existing declaration that can't be overloaded.
5475///
5476/// \return true if this is a forbidden redeclaration
5477static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S,
5478 DeclContext *Owner,
5479 DeclarationName Name,
5480 SourceLocation NameLoc, bool IsUnion,
5481 StorageClass SC) {
5482 LookupResult R(SemaRef, Name, NameLoc,
5486 if (!SemaRef.LookupName(R, S)) return false;
5487
5488 // Pick a representative declaration.
5490 assert(PrevDecl && "Expected a non-null Decl");
5491
5492 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5493 return false;
5494
5495 if (SC == StorageClass::SC_None &&
5496 PrevDecl->isPlaceholderVar(SemaRef.getLangOpts()) &&
5497 (Owner->isFunctionOrMethod() || Owner->isRecord())) {
5498 if (!Owner->isRecord())
5499 SemaRef.DiagPlaceholderVariableDefinition(NameLoc);
5500 return false;
5501 }
5502
5503 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5504 << IsUnion << Name;
5505 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5506
5507 return true;
5508}
5509
5511 if (auto *RD = dyn_cast_if_present<RecordDecl>(D))
5513}
5514
5516 if (!getLangOpts().CPlusPlus)
5517 return;
5518
5519 // This function can be parsed before we have validated the
5520 // structure as an anonymous struct
5521 if (Record->isAnonymousStructOrUnion())
5522 return;
5523
5524 const NamedDecl *First = 0;
5525 for (const Decl *D : Record->decls()) {
5526 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
5527 if (!ND || !ND->isPlaceholderVar(getLangOpts()))
5528 continue;
5529 if (!First)
5530 First = ND;
5531 else
5533 }
5534}
5535
5536/// InjectAnonymousStructOrUnionMembers - Inject the members of the
5537/// anonymous struct or union AnonRecord into the owning context Owner
5538/// and scope S. This routine will be invoked just after we realize
5539/// that an unnamed union or struct is actually an anonymous union or
5540/// struct, e.g.,
5541///
5542/// @code
5543/// union {
5544/// int i;
5545/// float f;
5546/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5547/// // f into the surrounding scope.x
5548/// @endcode
5549///
5550/// This routine is recursive, injecting the names of nested anonymous
5551/// structs/unions into the owning context and scope as well.
5552static bool
5554 RecordDecl *AnonRecord, AccessSpecifier AS,
5555 StorageClass SC,
5556 SmallVectorImpl<NamedDecl *> &Chaining) {
5557 bool Invalid = false;
5558
5559 // Look every FieldDecl and IndirectFieldDecl with a name.
5560 for (auto *D : AnonRecord->decls()) {
5561 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5562 cast<NamedDecl>(D)->getDeclName()) {
5563 ValueDecl *VD = cast<ValueDecl>(D);
5564 // C++ [class.union]p2:
5565 // The names of the members of an anonymous union shall be
5566 // distinct from the names of any other entity in the
5567 // scope in which the anonymous union is declared.
5568
5569 bool FieldInvalid = CheckAnonMemberRedeclaration(
5570 SemaRef, S, Owner, VD->getDeclName(), VD->getLocation(),
5571 AnonRecord->isUnion(), SC);
5572 if (FieldInvalid)
5573 Invalid = true;
5574
5575 // Inject the IndirectFieldDecl even if invalid, because later
5576 // diagnostics may depend on it being present, see findDefaultInitializer.
5577
5578 // C++ [class.union]p2:
5579 // For the purpose of name lookup, after the anonymous union
5580 // definition, the members of the anonymous union are
5581 // considered to have been defined in the scope in which the
5582 // anonymous union is declared.
5583 unsigned OldChainingSize = Chaining.size();
5584 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5585 Chaining.append(IF->chain_begin(), IF->chain_end());
5586 else
5587 Chaining.push_back(VD);
5588
5589 assert(Chaining.size() >= 2);
5590 NamedDecl **NamedChain =
5591 new (SemaRef.Context) NamedDecl *[Chaining.size()];
5592 for (unsigned i = 0; i < Chaining.size(); i++)
5593 NamedChain[i] = Chaining[i];
5594
5596 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5597 VD->getType(), {NamedChain, Chaining.size()});
5598
5599 for (const auto *Attr : VD->attrs())
5600 IndirectField->addAttr(Attr->clone(SemaRef.Context));
5601
5602 IndirectField->setAccess(AS);
5603 IndirectField->setImplicit();
5604 IndirectField->setInvalidDecl(FieldInvalid);
5605 SemaRef.PushOnScopeChains(IndirectField, S);
5606
5607 // That includes picking up the appropriate access specifier.
5608 if (AS != AS_none)
5609 IndirectField->setAccess(AS);
5610
5611 Chaining.resize(OldChainingSize);
5612 }
5613 }
5614
5615 return Invalid;
5616}
5617
5618/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5619/// a VarDecl::StorageClass. Any error reporting is up to the caller:
5620/// illegal input values are mapped to SC_None.
5621static StorageClass
5623 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5624 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5625 "Parser allowed 'typedef' as storage class VarDecl.");
5626 switch (StorageClassSpec) {
5629 if (DS.isExternInLinkageSpec())
5630 return SC_None;
5631 return SC_Extern;
5632 case DeclSpec::SCS_static: return SC_Static;
5633 case DeclSpec::SCS_auto: return SC_Auto;
5636 // Illegal SCSs map to None: error reporting is up to the caller.
5637 case DeclSpec::SCS_mutable: // Fall through.
5638 case DeclSpec::SCS_typedef: return SC_None;
5639 }
5640 llvm_unreachable("unknown storage class specifier");
5641}
5642
5644 assert(Record->hasInClassInitializer());
5645
5646 for (const auto *I : Record->decls()) {
5647 const auto *FD = dyn_cast<FieldDecl>(I);
5648 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5649 FD = IFD->getAnonField();
5650 if (FD && FD->hasInClassInitializer())
5651 return FD->getLocation();
5652 }
5653
5654 llvm_unreachable("couldn't find in-class initializer");
5655}
5656
5658 SourceLocation DefaultInitLoc) {
5659 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5660 return;
5661
5662 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5663 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5664}
5665
5667 CXXRecordDecl *AnonUnion) {
5668 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5669 return;
5670
5672}
5673
5675 AccessSpecifier AS,
5677 const PrintingPolicy &Policy) {
5678 DeclContext *Owner = Record->getDeclContext();
5679
5680 // Diagnose whether this anonymous struct/union is an extension.
5681 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5682 Diag(Record->getLocation(), diag::ext_anonymous_union);
5683 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5684 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5685 else if (!Record->isUnion() && !getLangOpts().C11)
5686 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5687
5688 // C and C++ require different kinds of checks for anonymous
5689 // structs/unions.
5690 bool Invalid = false;
5691 if (getLangOpts().CPlusPlus) {
5692 const char *PrevSpec = nullptr;
5693 if (Record->isUnion()) {
5694 // C++ [class.union]p6:
5695 // C++17 [class.union.anon]p2:
5696 // Anonymous unions declared in a named namespace or in the
5697 // global namespace shall be declared static.
5698 unsigned DiagID;
5699 DeclContext *OwnerScope = Owner->getRedeclContext();
5701 (OwnerScope->isTranslationUnit() ||
5702 (OwnerScope->isNamespace() &&
5703 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5704 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5705 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5706
5707 // Recover by adding 'static'.
5709 PrevSpec, DiagID, Policy);
5710 }
5711 // C++ [class.union]p6:
5712 // A storage class is not allowed in a declaration of an
5713 // anonymous union in a class scope.
5715 isa<RecordDecl>(Owner)) {
5717 diag::err_anonymous_union_with_storage_spec)
5719
5720 // Recover by removing the storage specifier.
5723 PrevSpec, DiagID, Context.getPrintingPolicy());
5724 }
5725 }
5726
5727 // Ignore const/volatile/restrict qualifiers.
5728 if (DS.getTypeQualifiers()) {
5730 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5731 << Record->isUnion() << "const"
5735 diag::ext_anonymous_struct_union_qualified)
5736 << Record->isUnion() << "volatile"
5740 diag::ext_anonymous_struct_union_qualified)
5741 << Record->isUnion() << "restrict"
5745 diag::ext_anonymous_struct_union_qualified)
5746 << Record->isUnion() << "_Atomic"
5750 diag::ext_anonymous_struct_union_qualified)
5751 << Record->isUnion() << "__unaligned"
5753
5755 }
5756
5757 // C++ [class.union]p2:
5758 // The member-specification of an anonymous union shall only
5759 // define non-static data members. [Note: nested types and
5760 // functions cannot be declared within an anonymous union. ]
5761 for (auto *Mem : Record->decls()) {
5762 // Ignore invalid declarations; we already diagnosed them.
5763 if (Mem->isInvalidDecl())
5764 continue;
5765
5766 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5767 // C++ [class.union]p3:
5768 // An anonymous union shall not have private or protected
5769 // members (clause 11).
5770 assert(FD->getAccess() != AS_none);
5771 if (FD->getAccess() != AS_public) {
5772 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5773 << Record->isUnion() << (FD->getAccess() == AS_protected);
5774 Invalid = true;
5775 }
5776
5777 // C++ [class.union]p1
5778 // An object of a class with a non-trivial constructor, a non-trivial
5779 // copy constructor, a non-trivial destructor, or a non-trivial copy
5780 // assignment operator cannot be a member of a union, nor can an
5781 // array of such objects.
5782 if (CheckNontrivialField(FD))
5783 Invalid = true;
5784 } else if (Mem->isImplicit()) {
5785 // Any implicit members are fine.
5786 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5787 // This is a type that showed up in an
5788 // elaborated-type-specifier inside the anonymous struct or
5789 // union, but which actually declares a type outside of the
5790 // anonymous struct or union. It's okay.
5791 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5792 if (!MemRecord->isAnonymousStructOrUnion() &&
5793 MemRecord->getDeclName()) {
5794 // Visual C++ allows type definition in anonymous struct or union.
5795 if (getLangOpts().MicrosoftExt)
5796 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5797 << Record->isUnion();
5798 else {
5799 // This is a nested type declaration.
5800 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5801 << Record->isUnion();
5802 Invalid = true;
5803 }
5804 } else {
5805 // This is an anonymous type definition within another anonymous type.
5806 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5807 // not part of standard C++.
5808 Diag(MemRecord->getLocation(),
5809 diag::ext_anonymous_record_with_anonymous_type)
5810 << Record->isUnion();
5811 }
5812 } else if (isa<AccessSpecDecl>(Mem)) {
5813 // Any access specifier is fine.
5814 } else if (isa<StaticAssertDecl>(Mem)) {
5815 // In C++1z, static_assert declarations are also fine.
5816 } else {
5817 // We have something that isn't a non-static data
5818 // member. Complain about it.
5819 unsigned DK = diag::err_anonymous_record_bad_member;
5820 if (isa<TypeDecl>(Mem))
5821 DK = diag::err_anonymous_record_with_type;
5822 else if (isa<FunctionDecl>(Mem))
5823 DK = diag::err_anonymous_record_with_function;
5824 else if (isa<VarDecl>(Mem))
5825 DK = diag::err_anonymous_record_with_static;
5826
5827 // Visual C++ allows type definition in anonymous struct or union.
5828 if (getLangOpts().MicrosoftExt &&
5829 DK == diag::err_anonymous_record_with_type)
5830 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5831 << Record->isUnion();
5832 else {
5833 Diag(Mem->getLocation(), DK) << Record->isUnion();
5834 Invalid = true;
5835 }
5836 }
5837 }
5838
5839 // C++11 [class.union]p8 (DR1460):
5840 // At most one variant member of a union may have a
5841 // brace-or-equal-initializer.
5842 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5843 Owner->isRecord())
5846 }
5847
5848 if (!Record->isUnion() && !Owner->isRecord()) {
5849 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5850 << getLangOpts().CPlusPlus;
5851 Invalid = true;
5852 }
5853
5854 // C++ [dcl.dcl]p3:
5855 // [If there are no declarators], and except for the declaration of an
5856 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5857 // names into the program
5858 // C++ [class.mem]p2:
5859 // each such member-declaration shall either declare at least one member
5860 // name of the class or declare at least one unnamed bit-field
5861 //
5862 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5863 if (getLangOpts().CPlusPlus && Record->field_empty())
5864 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5865
5866 // Mock up a declarator.
5870 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5871
5872 // Create a declaration for this anonymous struct/union.
5873 NamedDecl *Anon = nullptr;
5874 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5875 Anon = FieldDecl::Create(
5876 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5877 /*IdentifierInfo=*/nullptr, Context.getCanonicalTagType(Record), TInfo,
5878 /*BitWidth=*/nullptr, /*Mutable=*/false,
5879 /*InitStyle=*/ICIS_NoInit);
5880 Anon->setAccess(AS);
5881 ProcessDeclAttributes(S, Anon, Dc);
5882
5883 if (getLangOpts().CPlusPlus)
5884 FieldCollector->Add(cast<FieldDecl>(Anon));
5885 } else {
5886 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5887 if (SCSpec == DeclSpec::SCS_mutable) {
5888 // mutable can only appear on non-static class members, so it's always
5889 // an error here
5890 Diag(Record->getLocation(), diag::err_mutable_nonmember);
5891 Invalid = true;
5892 SC = SC_None;
5893 }
5894
5895 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5896 Record->getLocation(), /*IdentifierInfo=*/nullptr,
5897 Context.getCanonicalTagType(Record), TInfo, SC);
5898 if (Invalid)
5899 Anon->setInvalidDecl();
5900
5901 ProcessDeclAttributes(S, Anon, Dc);
5902
5903 // Default-initialize the implicit variable. This initialization will be
5904 // trivial in almost all cases, except if a union member has an in-class
5905 // initializer:
5906 // union { int n = 0; };
5908 }
5909 Anon->setImplicit();
5910
5911 // Mark this as an anonymous struct/union type.
5912 Record->setAnonymousStructOrUnion(true);
5913
5914 // Add the anonymous struct/union object to the current
5915 // context. We'll be referencing this object when we refer to one of
5916 // its members.
5917 Owner->addDecl(Anon);
5918
5919 // Inject the members of the anonymous struct/union into the owning
5920 // context and into the identifier resolver chain for name lookup
5921 // purposes.
5923 Chain.push_back(Anon);
5924
5925 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, SC,
5926 Chain))
5927 Invalid = true;
5928
5929 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5930 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5932 Decl *ManglingContextDecl;
5933 std::tie(MCtx, ManglingContextDecl) =
5934 getCurrentMangleNumberContext(NewVD->getDeclContext());
5935 if (MCtx) {
5936 Context.setManglingNumber(
5937 NewVD, MCtx->getManglingNumber(
5938 NewVD, getMSManglingNumber(getLangOpts(), S)));
5939 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5940 }
5941 }
5942 }
5943
5944 if (Invalid)
5945 Anon->setInvalidDecl();
5946
5947 return Anon;
5948}
5949
5951 RecordDecl *Record) {
5952 assert(Record && "expected a record!");
5953
5954 // Mock up a declarator.
5957 assert(TInfo && "couldn't build declarator info for anonymous struct");
5958
5959 auto *ParentDecl = cast<RecordDecl>(CurContext);
5960 CanQualType RecTy = Context.getCanonicalTagType(Record);
5961
5962 // Create a declaration for this anonymous struct.
5963 NamedDecl *Anon =
5964 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5965 /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5966 /*BitWidth=*/nullptr, /*Mutable=*/false,
5967 /*InitStyle=*/ICIS_NoInit);
5968 Anon->setImplicit();
5969
5970 // Add the anonymous struct object to the current context.
5971 CurContext->addDecl(Anon);
5972
5973 // Inject the members of the anonymous struct into the current
5974 // context and into the identifier resolver chain for name lookup
5975 // purposes.
5977 Chain.push_back(Anon);
5978
5979 RecordDecl *RecordDef = Record->getDefinition();
5980 if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5981 diag::err_field_incomplete_or_sizeless) ||
5983 *this, S, CurContext, RecordDef, AS_none,
5985 Anon->setInvalidDecl();
5986 ParentDecl->setInvalidDecl();
5987 }
5988
5989 return Anon;
5990}
5991
5995
5998 DeclarationNameInfo NameInfo;
5999 NameInfo.setLoc(Name.StartLocation);
6000
6001 switch (Name.getKind()) {
6002
6005 NameInfo.setName(Name.Identifier);
6006 return NameInfo;
6007
6009 // C++ [temp.deduct.guide]p3:
6010 // The simple-template-id shall name a class template specialization.
6011 // The template-name shall be the same identifier as the template-name
6012 // of the simple-template-id.
6013 // These together intend to imply that the template-name shall name a
6014 // class template.
6015 // FIXME: template<typename T> struct X {};
6016 // template<typename T> using Y = X<T>;
6017 // Y(int) -> Y<int>;
6018 // satisfies these rules but does not name a class template.
6019 TemplateName TN = Name.TemplateName.get().get();
6020 auto *Template = TN.getAsTemplateDecl();
6022 Diag(Name.StartLocation,
6023 diag::err_deduction_guide_name_not_class_template)
6024 << (int)getTemplateNameKindForDiagnostics(TN) << TN;
6025 if (Template)
6027 return DeclarationNameInfo();
6028 }
6029
6030 NameInfo.setName(
6031 Context.DeclarationNames.getCXXDeductionGuideName(Template));
6032 return NameInfo;
6033 }
6034
6036 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
6040 return NameInfo;
6041
6043 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
6044 Name.Identifier));
6046 return NameInfo;
6047
6049 TypeSourceInfo *TInfo;
6051 if (Ty.isNull())
6052 return DeclarationNameInfo();
6053 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
6054 Context.getCanonicalType(Ty)));
6055 NameInfo.setNamedTypeInfo(TInfo);
6056 return NameInfo;
6057 }
6058
6060 TypeSourceInfo *TInfo;
6061 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
6062 if (Ty.isNull())
6063 return DeclarationNameInfo();
6064 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
6065 Context.getCanonicalType(Ty)));
6066 NameInfo.setNamedTypeInfo(TInfo);
6067 return NameInfo;
6068 }
6069
6071 // In well-formed code, we can only have a constructor
6072 // template-id that refers to the current context, so go there
6073 // to find the actual type being constructed.
6074 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
6075 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
6076 return DeclarationNameInfo();
6077
6078 // Determine the type of the class being constructed.
6079 CanQualType CurClassType = Context.getCanonicalTagType(CurClass);
6080
6081 // FIXME: Check two things: that the template-id names the same type as
6082 // CurClassType, and that the template-id does not occur when the name
6083 // was qualified.
6084
6085 NameInfo.setName(
6086 Context.DeclarationNames.getCXXConstructorName(CurClassType));
6087 // FIXME: should we retrieve TypeSourceInfo?
6088 NameInfo.setNamedTypeInfo(nullptr);
6089 return NameInfo;
6090 }
6091
6093 TypeSourceInfo *TInfo;
6094 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
6095 if (Ty.isNull())
6096 return DeclarationNameInfo();
6097 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
6098 Context.getCanonicalType(Ty)));
6099 NameInfo.setNamedTypeInfo(TInfo);
6100 return NameInfo;
6101 }
6102
6104 TemplateName TName = Name.TemplateId->Template.get();
6105 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
6106 return Context.getNameForTemplate(TName, TNameLoc);
6107 }
6108
6109 } // switch (Name.getKind())
6110
6111 llvm_unreachable("Unknown name kind");
6112}
6113
6115 do {
6116 if (Ty->isPointerOrReferenceType())
6117 Ty = Ty->getPointeeType();
6118 else if (Ty->isArrayType())
6120 else
6121 return Ty.withoutLocalFastQualifiers();
6122 } while (true);
6123}
6124
6125/// hasSimilarParameters - Determine whether the C++ functions Declaration
6126/// and Definition have "nearly" matching parameters. This heuristic is
6127/// used to improve diagnostics in the case where an out-of-line function
6128/// definition doesn't match any declaration within the class or namespace.
6129/// Also sets Params to the list of indices to the parameters that differ
6130/// between the declaration and the definition. If hasSimilarParameters
6131/// returns true and Params is empty, then all of the parameters match.
6135 SmallVectorImpl<unsigned> &Params) {
6136 Params.clear();
6137 if (Declaration->param_size() != Definition->param_size())
6138 return false;
6139 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
6140 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
6141 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
6142
6143 // The parameter types are identical
6144 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
6145 continue;
6146
6147 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
6148 QualType DefParamBaseTy = getCoreType(DefParamTy);
6149 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
6150 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
6151
6152 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
6153 (DeclTyName && DeclTyName == DefTyName))
6154 Params.push_back(Idx);
6155 else // The two parameters aren't even close
6156 return false;
6157 }
6158
6159 return true;
6160}
6161
6162/// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
6163/// declarator needs to be rebuilt in the current instantiation.
6164/// Any bits of declarator which appear before the name are valid for
6165/// consideration here. That's specifically the type in the decl spec
6166/// and the base type in any member-pointer chunks.
6168 DeclarationName Name) {
6169 // The types we specifically need to rebuild are:
6170 // - typenames, typeofs, and decltypes
6171 // - types which will become injected class names
6172 // Of course, we also need to rebuild any type referencing such a
6173 // type. It's safest to just say "dependent", but we call out a
6174 // few cases here.
6175
6176 DeclSpec &DS = D.getMutableDeclSpec();
6177 switch (DS.getTypeSpecType()) {
6181#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
6182#include "clang/Basic/TransformTypeTraits.def"
6183 case DeclSpec::TST_atomic: {
6184 // Grab the type from the parser.
6185 TypeSourceInfo *TSI = nullptr;
6186 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
6187 if (T.isNull() || !T->isInstantiationDependentType()) break;
6188
6189 // Make sure there's a type source info. This isn't really much
6190 // of a waste; most dependent types should have type source info
6191 // attached already.
6192 if (!TSI)
6194
6195 // Rebuild the type in the current instantiation.
6197 if (!TSI) return true;
6198
6199 // Store the new type back in the decl spec.
6200 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
6201 DS.UpdateTypeRep(LocType);
6202 break;
6203 }
6204
6208 Expr *E = DS.getRepAsExpr();
6210 if (Result.isInvalid()) return true;
6211 DS.UpdateExprRep(Result.get());
6212 break;
6213 }
6214
6215 default:
6216 // Nothing to do for these decl specs.
6217 break;
6218 }
6219
6220 // It doesn't matter what order we do this in.
6221 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
6222 DeclaratorChunk &Chunk = D.getTypeObject(I);
6223
6224 // The only type information in the declarator which can come
6225 // before the declaration name is the base type of a member
6226 // pointer.
6228 continue;
6229
6230 // Rebuild the scope specifier in-place.
6231 CXXScopeSpec &SS = Chunk.Mem.Scope();
6233 return true;
6234 }
6235
6236 return false;
6237}
6238
6239/// Returns true if the declaration is declared in a system header or from a
6240/// system macro.
6241static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
6242 return SM.isInSystemHeader(D->getLocation()) ||
6243 SM.isInSystemMacro(D->getLocation());
6244}
6245
6247 // Avoid warning twice on the same identifier, and don't warn on redeclaration
6248 // of system decl.
6249 if (D->getPreviousDecl() || D->isImplicit())
6250 return;
6253 !isFromSystemHeader(Context.getSourceManager(), D)) {
6254 Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
6255 << D << static_cast<int>(Status);
6256 }
6257}
6258
6261
6262 // Check if we are in an `omp begin/end declare variant` scope. Handle this
6263 // declaration only if the `bind_to_declaration` extension is set.
6265 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
6266 if (OpenMP().getOMPTraitInfoForSurroundingScope()->isExtensionActive(
6267 llvm::omp::TraitProperty::
6268 implementation_extension_bind_to_declaration))
6270 S, D, MultiTemplateParamsArg(), Bases);
6271
6273
6274 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
6275 Dcl && Dcl->getDeclContext()->isFileContext())
6277
6278 if (!Bases.empty())
6280 Bases);
6281
6282 return Dcl;
6283}
6284
6286 DeclarationNameInfo NameInfo) {
6287 DeclarationName Name = NameInfo.getName();
6288
6289 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
6290 while (Record && Record->isAnonymousStructOrUnion())
6291 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
6292 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6293 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
6294 return true;
6295 }
6296
6297 return false;
6298}
6299
6301 DeclarationName Name,
6302 SourceLocation Loc,
6303 TemplateIdAnnotation *TemplateId,
6304 bool IsMemberSpecialization) {
6305 assert(SS.isValid() && "diagnoseQualifiedDeclaration called for declaration "
6306 "without nested-name-specifier");
6307 DeclContext *Cur = CurContext;
6308 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
6309 Cur = Cur->getParent();
6310
6311 // If the user provided a superfluous scope specifier that refers back to the
6312 // class in which the entity is already declared, diagnose and ignore it.
6313 //
6314 // class X {
6315 // void X::f();
6316 // };
6317 //
6318 // Note, it was once ill-formed to give redundant qualification in all
6319 // contexts, but that rule was removed by DR482.
6320 if (Cur->Equals(DC)) {
6321 if (Cur->isRecord()) {
6322 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6323 : diag::err_member_extra_qualification)
6324 << Name << FixItHint::CreateRemoval(SS.getRange());
6325 SS.clear();
6326 } else {
6327 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
6328 }
6329 return false;
6330 }
6331
6332 // Check whether the qualifying scope encloses the scope of the original
6333 // declaration. For a template-id, we perform the checks in
6334 // CheckTemplateSpecializationScope.
6335 if (!Cur->Encloses(DC) && !(TemplateId || IsMemberSpecialization)) {
6336 if (Cur->isRecord())
6337 Diag(Loc, diag::err_member_qualification)
6338 << Name << SS.getRange();
6339 else if (isa<TranslationUnitDecl>(DC))
6340 Diag(Loc, diag::err_invalid_declarator_global_scope)
6341 << Name << SS.getRange();
6342 else if (isa<FunctionDecl>(Cur))
6343 Diag(Loc, diag::err_invalid_declarator_in_function)
6344 << Name << SS.getRange();
6345 else if (isa<BlockDecl>(Cur))
6346 Diag(Loc, diag::err_invalid_declarator_in_block)
6347 << Name << SS.getRange();
6348 else if (isa<ExportDecl>(Cur)) {
6349 if (!isa<NamespaceDecl>(DC))
6350 Diag(Loc, diag::err_export_non_namespace_scope_name)
6351 << Name << SS.getRange();
6352 else
6353 // The cases that DC is not NamespaceDecl should be handled in
6354 // CheckRedeclarationExported.
6355 return false;
6356 } else
6357 Diag(Loc, diag::err_invalid_declarator_scope)
6358 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
6359
6360 return true;
6361 }
6362
6363 if (Cur->isRecord()) {
6364 // Cannot qualify members within a class.
6365 Diag(Loc, diag::err_member_qualification)
6366 << Name << SS.getRange();
6367 SS.clear();
6368
6369 // C++ constructors and destructors with incorrect scopes can break
6370 // our AST invariants by having the wrong underlying types. If
6371 // that's the case, then drop this declaration entirely.
6374 !Context.hasSameType(
6375 Name.getCXXNameType(),
6376 Context.getCanonicalTagType(cast<CXXRecordDecl>(Cur))))
6377 return true;
6378
6379 return false;
6380 }
6381
6382 // C++23 [temp.names]p5:
6383 // The keyword template shall not appear immediately after a declarative
6384 // nested-name-specifier.
6385 //
6386 // First check the template-id (if any), and then check each component of the
6387 // nested-name-specifier in reverse order.
6388 //
6389 // FIXME: nested-name-specifiers in friend declarations are declarative,
6390 // but we don't call diagnoseQualifiedDeclaration for them. We should.
6391 if (TemplateId && TemplateId->TemplateKWLoc.isValid())
6392 Diag(Loc, diag::ext_template_after_declarative_nns)
6394
6396 for (TypeLoc TL = SpecLoc.getAsTypeLoc(), NextTL; TL;
6397 TL = std::exchange(NextTL, TypeLoc())) {
6398 SourceLocation TemplateKeywordLoc;
6399 switch (TL.getTypeLocClass()) {
6400 case TypeLoc::TemplateSpecialization: {
6401 auto TST = TL.castAs<TemplateSpecializationTypeLoc>();
6402 TemplateKeywordLoc = TST.getTemplateKeywordLoc();
6403 if (auto *T = TST.getTypePtr(); T->isDependentType() && T->isTypeAlias())
6404 Diag(Loc, diag::ext_alias_template_in_declarative_nns)
6405 << TST.getLocalSourceRange();
6406 break;
6407 }
6408 case TypeLoc::Decltype:
6409 case TypeLoc::PackIndexing: {
6410 const Type *T = TL.getTypePtr();
6411 // C++23 [expr.prim.id.qual]p2:
6412 // [...] A declarative nested-name-specifier shall not have a
6413 // computed-type-specifier.
6414 //
6415 // CWG2858 changed this from 'decltype-specifier' to
6416 // 'computed-type-specifier'.
6417 Diag(Loc, diag::err_computed_type_in_declarative_nns)
6418 << T->isDecltypeType() << TL.getSourceRange();
6419 break;
6420 }
6421 case TypeLoc::DependentName:
6422 NextTL =
6423 TL.castAs<DependentNameTypeLoc>().getQualifierLoc().getAsTypeLoc();
6424 break;
6425 default:
6426 break;
6427 }
6428 if (TemplateKeywordLoc.isValid())
6429 Diag(Loc, diag::ext_template_after_declarative_nns)
6430 << FixItHint::CreateRemoval(TemplateKeywordLoc);
6431 }
6432
6433 return false;
6434}
6435
6437 MultiTemplateParamsArg TemplateParamLists) {
6438 // TODO: consider using NameInfo for diagnostic.
6440 DeclarationName Name = NameInfo.getName();
6441
6442 // All of these full declarators require an identifier. If it doesn't have
6443 // one, the ParsedFreeStandingDeclSpec action should be used.
6444 if (D.isDecompositionDeclarator()) {
6445 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6446 } else if (!Name) {
6447 if (!D.isInvalidType()) // Reject this if we think it is valid.
6448 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6450 return nullptr;
6452 return nullptr;
6453
6454 DeclContext *DC = CurContext;
6455 if (D.getCXXScopeSpec().isInvalid())
6456 D.setInvalidType();
6457 else if (D.getCXXScopeSpec().isSet()) {
6460 return nullptr;
6461
6462 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6463 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
6464 if (!DC || isa<EnumDecl>(DC)) {
6465 // If we could not compute the declaration context, it's because the
6466 // declaration context is dependent but does not refer to a class,
6467 // class template, or class template partial specialization. Complain
6468 // and return early, to avoid the coming semantic disaster.
6470 diag::err_template_qualified_declarator_no_match)
6472 << D.getCXXScopeSpec().getRange();
6473 return nullptr;
6474 }
6475 bool IsDependentContext = DC->isDependentContext();
6476
6477 if (!IsDependentContext &&
6479 return nullptr;
6480
6481 // If a class is incomplete, do not parse entities inside it.
6484 diag::err_member_def_undefined_record)
6485 << Name << DC << D.getCXXScopeSpec().getRange();
6486 return nullptr;
6487 }
6488 if (!D.getDeclSpec().isFriendSpecified()) {
6489 TemplateIdAnnotation *TemplateId =
6491 ? D.getName().TemplateId
6492 : nullptr;
6494 D.getIdentifierLoc(), TemplateId,
6495 /*IsMemberSpecialization=*/false)) {
6496 if (DC->isRecord())
6497 return nullptr;
6498
6499 D.setInvalidType();
6500 }
6501 }
6502
6503 // Check whether we need to rebuild the type of the given
6504 // declaration in the current instantiation.
6505 if (EnteringContext && IsDependentContext &&
6506 TemplateParamLists.size() != 0) {
6507 ContextRAII SavedContext(*this, DC);
6508 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
6509 D.setInvalidType();
6510 }
6511 }
6512
6514 QualType R = TInfo->getType();
6515
6518 D.setInvalidType();
6519
6520 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6522
6523 // See if this is a redefinition of a variable in the same scope.
6524 if (!D.getCXXScopeSpec().isSet()) {
6525 bool IsLinkageLookup = false;
6526 bool CreateBuiltins = false;
6527
6528 // If the declaration we're planning to build will be a function
6529 // or object with linkage, then look for another declaration with
6530 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6531 //
6532 // If the declaration we're planning to build will be declared with
6533 // external linkage in the translation unit, create any builtin with
6534 // the same name.
6536 /* Do nothing*/;
6537 else if (CurContext->isFunctionOrMethod() &&
6539 R->isFunctionType())) {
6540 IsLinkageLookup = true;
6541 CreateBuiltins =
6542 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6543 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6545 CreateBuiltins = true;
6546
6547 if (IsLinkageLookup) {
6549 Previous.setRedeclarationKind(
6551 }
6552
6553 LookupName(Previous, S, CreateBuiltins);
6554 } else { // Something like "int foo::x;"
6556
6557 // C++ [dcl.meaning]p1:
6558 // When the declarator-id is qualified, the declaration shall refer to a
6559 // previously declared member of the class or namespace to which the
6560 // qualifier refers (or, in the case of a namespace, of an element of the
6561 // inline namespace set of that namespace (7.3.1)) or to a specialization
6562 // thereof; [...]
6563 //
6564 // Note that we already checked the context above, and that we do not have
6565 // enough information to make sure that Previous contains the declaration
6566 // we want to match. For example, given:
6567 //
6568 // class X {
6569 // void f();
6570 // void f(float);
6571 // };
6572 //
6573 // void X::f(int) { } // ill-formed
6574 //
6575 // In this case, Previous will point to the overload set
6576 // containing the two f's declared in X, but neither of them
6577 // matches.
6578
6580 }
6581
6582 if (auto *TPD = Previous.getAsSingle<NamedDecl>();
6583 TPD && TPD->isTemplateParameter()) {
6584 // Older versions of clang allowed the names of function/variable templates
6585 // to shadow the names of their template parameters. For the compatibility
6586 // purposes we detect such cases and issue a default-to-error warning that
6587 // can be disabled with -Wno-strict-primary-template-shadow.
6588 if (!D.isInvalidType()) {
6589 bool AllowForCompatibility = false;
6590 if (Scope *DeclParent = S->getDeclParent();
6591 Scope *TemplateParamParent = S->getTemplateParamParent()) {
6592 AllowForCompatibility = DeclParent->Contains(*TemplateParamParent) &&
6593 TemplateParamParent->isDeclScope(TPD);
6594 }
6596 AllowForCompatibility);
6597 }
6598
6599 // Just pretend that we didn't see the previous declaration.
6600 Previous.clear();
6601 }
6602
6603 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6604 // Forget that the previous declaration is the injected-class-name.
6605 Previous.clear();
6606
6607 // In C++, the previous declaration we find might be a tag type
6608 // (class or enum). In this case, the new declaration will hide the
6609 // tag type. Note that this applies to functions, function templates, and
6610 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6611 if (Previous.isSingleTagDecl() &&
6613 (TemplateParamLists.size() == 0 || R->isFunctionType()))
6614 Previous.clear();
6615
6616 // Check that there are no default arguments other than in the parameters
6617 // of a function declaration (C++ only).
6618 if (getLangOpts().CPlusPlus)
6620
6621 /// Get the innermost enclosing declaration scope.
6622 S = S->getDeclParent();
6623
6624 NamedDecl *New;
6625
6626 bool AddToScope = true;
6628 if (TemplateParamLists.size()) {
6629 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6630 return nullptr;
6631 }
6632
6633 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6634 } else if (R->isFunctionType()) {
6635 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6636 TemplateParamLists,
6637 AddToScope);
6638 } else {
6639 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6640 AddToScope);
6641 }
6642
6643 if (!New)
6644 return nullptr;
6645
6647
6648 // If this has an identifier and is not a function template specialization,
6649 // add it to the scope stack.
6650 if (New->getDeclName() && AddToScope)
6652
6653 if (OpenMP().isInOpenMPDeclareTargetContext())
6655
6656 return New;
6657}
6658
6659/// Helper method to turn variable array types into constant array
6660/// types in certain situations which would otherwise be errors (for
6661/// GCC compatibility).
6663 ASTContext &Context,
6664 bool &SizeIsNegative,
6665 llvm::APSInt &Oversized) {
6666 // This method tries to turn a variable array into a constant
6667 // array even when the size isn't an ICE. This is necessary
6668 // for compatibility with code that depends on gcc's buggy
6669 // constant expression folding, like struct {char x[(int)(char*)2];}
6670 SizeIsNegative = false;
6671 Oversized = 0;
6672
6673 if (T->isDependentType())
6674 return QualType();
6675
6677 const Type *Ty = Qs.strip(T);
6678
6679 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6680 QualType Pointee = PTy->getPointeeType();
6681 QualType FixedType =
6682 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6683 Oversized);
6684 if (FixedType.isNull()) return FixedType;
6685 FixedType = Context.getPointerType(FixedType);
6686 return Qs.apply(Context, FixedType);
6687 }
6688 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6689 QualType Inner = PTy->getInnerType();
6690 QualType FixedType =
6691 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6692 Oversized);
6693 if (FixedType.isNull()) return FixedType;
6694 FixedType = Context.getParenType(FixedType);
6695 return Qs.apply(Context, FixedType);
6696 }
6697
6698 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6699 if (!VLATy)
6700 return QualType();
6701
6702 QualType ElemTy = VLATy->getElementType();
6703 if (ElemTy->isVariablyModifiedType()) {
6704 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6705 SizeIsNegative, Oversized);
6706 if (ElemTy.isNull())
6707 return QualType();
6708 }
6709
6710 Expr::EvalResult Result;
6711 if (!VLATy->getSizeExpr() ||
6712 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6713 return QualType();
6714
6715 llvm::APSInt Res = Result.Val.getInt();
6716
6717 // Check whether the array size is negative.
6718 if (Res.isSigned() && Res.isNegative()) {
6719 SizeIsNegative = true;
6720 return QualType();
6721 }
6722
6723 // Check whether the array is too large to be addressed.
6724 unsigned ActiveSizeBits =
6725 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6726 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6727 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6728 : Res.getActiveBits();
6729 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6730 Oversized = Res;
6731 return QualType();
6732 }
6733
6734 QualType FoldedArrayType = Context.getConstantArrayType(
6735 ElemTy, Res, VLATy->getSizeExpr(), ArraySizeModifier::Normal, 0);
6736 return Qs.apply(Context, FoldedArrayType);
6737}
6738
6739static void
6741 SrcTL = SrcTL.getUnqualifiedLoc();
6742 DstTL = DstTL.getUnqualifiedLoc();
6743 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6744 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6745 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6746 DstPTL.getPointeeLoc());
6747 DstPTL.setStarLoc(SrcPTL.getStarLoc());
6748 return;
6749 }
6750 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6751 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6752 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6753 DstPTL.getInnerLoc());
6754 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6755 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6756 return;
6757 }
6758 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6759 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6760 TypeLoc SrcElemTL = SrcATL.getElementLoc();
6761 TypeLoc DstElemTL = DstATL.getElementLoc();
6762 if (VariableArrayTypeLoc SrcElemATL =
6763 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6764 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6765 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6766 } else {
6767 DstElemTL.initializeFullCopy(SrcElemTL);
6768 }
6769 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6770 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6771 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6772}
6773
6774/// Helper method to turn variable array types into constant array
6775/// types in certain situations which would otherwise be errors (for
6776/// GCC compatibility).
6777static TypeSourceInfo*
6779 ASTContext &Context,
6780 bool &SizeIsNegative,
6781 llvm::APSInt &Oversized) {
6782 QualType FixedTy
6783 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6784 SizeIsNegative, Oversized);
6785 if (FixedTy.isNull())
6786 return nullptr;
6787 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6789 FixedTInfo->getTypeLoc());
6790 return FixedTInfo;
6791}
6792
6795 unsigned FailedFoldDiagID) {
6796 bool SizeIsNegative;
6797 llvm::APSInt Oversized;
6799 TInfo, Context, SizeIsNegative, Oversized);
6800 if (FixedTInfo) {
6801 Diag(Loc, diag::ext_vla_folded_to_constant);
6802 TInfo = FixedTInfo;
6803 T = FixedTInfo->getType();
6804 return true;
6805 }
6806
6807 if (SizeIsNegative)
6808 Diag(Loc, diag::err_typecheck_negative_array_size);
6809 else if (Oversized.getBoolValue())
6810 Diag(Loc, diag::err_array_too_large) << toString(
6811 Oversized, 10, Oversized.isSigned(), /*formatAsCLiteral=*/false,
6812 /*UpperCase=*/false, /*InsertSeparators=*/true);
6813 else if (FailedFoldDiagID)
6814 Diag(Loc, FailedFoldDiagID);
6815 return false;
6816}
6817
6818void
6820 if (!getLangOpts().CPlusPlus &&
6822 // Don't need to track declarations in the TU in C.
6823 return;
6824
6825 // Note that we have a locally-scoped external with this name.
6826 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6827}
6828
6830 // FIXME: We can have multiple results via __attribute__((overloadable)).
6831 auto Result = Context.getExternCContextDecl()->lookup(Name);
6832 return Result.empty() ? nullptr : *Result.begin();
6833}
6834
6836 // FIXME: We should probably indicate the identifier in question to avoid
6837 // confusion for constructs like "virtual int a(), b;"
6838 if (DS.isVirtualSpecified())
6840 diag::err_virtual_non_function);
6841
6842 if (DS.hasExplicitSpecifier())
6844 diag::err_explicit_non_function);
6845
6846 if (DS.isNoreturnSpecified())
6848 diag::err_noreturn_non_function);
6849}
6850
6851NamedDecl*
6854 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6855 if (D.getCXXScopeSpec().isSet()) {
6856 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6857 << D.getCXXScopeSpec().getRange();
6858 D.setInvalidType();
6859 // Pretend we didn't see the scope specifier.
6860 DC = CurContext;
6861 Previous.clear();
6862 }
6863
6865
6868 (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus)
6869 ? diag::warn_ms_inline_non_function
6870 : diag::err_inline_non_function)
6871 << getLangOpts().CPlusPlus17;
6873 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6874 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6875
6879 diag::err_deduction_guide_invalid_specifier)
6880 << "typedef";
6881 else
6882 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6883 << D.getName().getSourceRange();
6884 return nullptr;
6885 }
6886
6887 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6888 if (!NewTD) return nullptr;
6889
6890 // Handle attributes prior to checking for duplicates in MergeVarDecl
6891 ProcessDeclAttributes(S, NewTD, D);
6892
6894
6895 bool Redeclaration = D.isRedeclaration();
6898 return ND;
6899}
6900
6901void
6903 // C99 6.7.7p2: If a typedef name specifies a variably modified type
6904 // then it shall have block scope.
6905 // Note that variably modified types must be fixed before merging the decl so
6906 // that redeclarations will match.
6907 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6908 QualType T = TInfo->getType();
6909 if (T->isVariablyModifiedType()) {
6911
6912 if (S->getFnParent() == nullptr) {
6913 bool SizeIsNegative;
6914 llvm::APSInt Oversized;
6915 TypeSourceInfo *FixedTInfo =
6917 SizeIsNegative,
6918 Oversized);
6919 if (FixedTInfo) {
6920 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6921 NewTD->setTypeSourceInfo(FixedTInfo);
6922 } else {
6923 if (SizeIsNegative)
6924 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6925 else if (T->isVariableArrayType())
6926 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6927 else if (Oversized.getBoolValue())
6928 Diag(NewTD->getLocation(), diag::err_array_too_large)
6929 << toString(Oversized, 10);
6930 else
6931 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6932 NewTD->setInvalidDecl();
6933 }
6934 }
6935 }
6936}
6937
6938NamedDecl*
6941
6942 // Find the shadowed declaration before filtering for scope.
6943 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6944
6945 // Merge the decl with the existing one if appropriate. If the decl is
6946 // in an outer scope, it isn't the same thing.
6947 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6948 /*AllowInlineNamespace*/false);
6950 if (!Previous.empty()) {
6951 Redeclaration = true;
6952 MergeTypedefNameDecl(S, NewTD, Previous);
6953 } else {
6955 }
6956
6957 if (ShadowedDecl && !Redeclaration)
6958 CheckShadow(NewTD, ShadowedDecl, Previous);
6959
6960 // If this is the C FILE type, notify the AST context.
6961 if (IdentifierInfo *II = NewTD->getIdentifier())
6962 if (!NewTD->isInvalidDecl() &&
6964 switch (II->getNotableIdentifierID()) {
6965 case tok::NotableIdentifierKind::FILE:
6966 Context.setFILEDecl(NewTD);
6967 break;
6968 case tok::NotableIdentifierKind::jmp_buf:
6969 Context.setjmp_bufDecl(NewTD);
6970 break;
6971 case tok::NotableIdentifierKind::sigjmp_buf:
6972 Context.setsigjmp_bufDecl(NewTD);
6973 break;
6974 case tok::NotableIdentifierKind::ucontext_t:
6975 Context.setucontext_tDecl(NewTD);
6976 break;
6977 case tok::NotableIdentifierKind::float_t:
6978 case tok::NotableIdentifierKind::double_t:
6979 NewTD->addAttr(AvailableOnlyInDefaultEvalMethodAttr::Create(Context));
6980 break;
6981 default:
6982 break;
6983 }
6984 }
6985
6986 return NewTD;
6987}
6988
6989/// Determines whether the given declaration is an out-of-scope
6990/// previous declaration.
6991///
6992/// This routine should be invoked when name lookup has found a
6993/// previous declaration (PrevDecl) that is not in the scope where a
6994/// new declaration by the same name is being introduced. If the new
6995/// declaration occurs in a local scope, previous declarations with
6996/// linkage may still be considered previous declarations (C99
6997/// 6.2.2p4-5, C++ [basic.link]p6).
6998///
6999/// \param PrevDecl the previous declaration found by name
7000/// lookup
7001///
7002/// \param DC the context in which the new declaration is being
7003/// declared.
7004///
7005/// \returns true if PrevDecl is an out-of-scope previous declaration
7006/// for a new delcaration with the same name.
7007static bool
7009 ASTContext &Context) {
7010 if (!PrevDecl)
7011 return false;
7012
7013 if (!PrevDecl->hasLinkage())
7014 return false;
7015
7016 if (Context.getLangOpts().CPlusPlus) {
7017 // C++ [basic.link]p6:
7018 // If there is a visible declaration of an entity with linkage
7019 // having the same name and type, ignoring entities declared
7020 // outside the innermost enclosing namespace scope, the block
7021 // scope declaration declares that same entity and receives the
7022 // linkage of the previous declaration.
7023 DeclContext *OuterContext = DC->getRedeclContext();
7024 if (!OuterContext->isFunctionOrMethod())
7025 // This rule only applies to block-scope declarations.
7026 return false;
7027
7028 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
7029 if (PrevOuterContext->isRecord())
7030 // We found a member function: ignore it.
7031 return false;
7032
7033 // Find the innermost enclosing namespace for the new and
7034 // previous declarations.
7035 OuterContext = OuterContext->getEnclosingNamespaceContext();
7036 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
7037
7038 // The previous declaration is in a different namespace, so it
7039 // isn't the same function.
7040 if (!OuterContext->Equals(PrevOuterContext))
7041 return false;
7042 }
7043
7044 return true;
7045}
7046
7048 CXXScopeSpec &SS = D.getCXXScopeSpec();
7049 if (!SS.isSet()) return;
7051}
7052
7054 if (Decl->getType().hasAddressSpace())
7055 return;
7056 if (Decl->getType()->isDependentType())
7057 return;
7058 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
7059 QualType Type = Var->getType();
7060 if (Type->isSamplerT() || Type->isVoidType())
7061 return;
7063 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
7064 // __opencl_c_program_scope_global_variables feature, the address space
7065 // for a variable at program scope or a static or extern variable inside
7066 // a function are inferred to be __global.
7067 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
7068 Var->hasGlobalStorage())
7069 ImplAS = LangAS::opencl_global;
7070 // If the original type from a decayed type is an array type and that array
7071 // type has no address space yet, deduce it now.
7072 if (auto DT = dyn_cast<DecayedType>(Type)) {
7073 auto OrigTy = DT->getOriginalType();
7074 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
7075 // Add the address space to the original array type and then propagate
7076 // that to the element type through `getAsArrayType`.
7077 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
7078 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
7079 // Re-generate the decayed type.
7080 Type = Context.getDecayedType(OrigTy);
7081 }
7082 }
7083 Type = Context.getAddrSpaceQualType(Type, ImplAS);
7084 // Apply any qualifiers (including address space) from the array type to
7085 // the element type. This implements C99 6.7.3p8: "If the specification of
7086 // an array type includes any type qualifiers, the element type is so
7087 // qualified, not the array type."
7088 if (Type->isArrayType())
7089 Type = QualType(Context.getAsArrayType(Type), 0);
7090 Decl->setType(Type);
7091 }
7092}
7093
7094static void checkWeakAttr(Sema &S, NamedDecl &ND) {
7095 // 'weak' only applies to declarations with external linkage.
7096 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
7097 if (!ND.isExternallyVisible()) {
7098 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
7099 ND.dropAttr<WeakAttr>();
7100 }
7101 }
7102}
7103
7104static void checkWeakRefAttr(Sema &S, NamedDecl &ND) {
7105 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
7106 if (ND.isExternallyVisible()) {
7107 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
7108 ND.dropAttrs<WeakRefAttr, AliasAttr>();
7109 }
7110 }
7111}
7112
7113static void checkAliasAttr(Sema &S, NamedDecl &ND) {
7114 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
7115 if (VD->hasInit()) {
7116 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
7117 assert(VD->isThisDeclarationADefinition() &&
7118 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
7119 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
7120 VD->dropAttr<AliasAttr>();
7121 }
7122 }
7123 }
7124}
7125
7126static void checkSelectAnyAttr(Sema &S, NamedDecl &ND) {
7127 // 'selectany' only applies to externally visible variable declarations.
7128 // It does not apply to functions.
7129 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
7130 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
7131 S.Diag(Attr->getLocation(),
7132 diag::err_attribute_selectany_non_extern_data);
7133 ND.dropAttr<SelectAnyAttr>();
7134 }
7135 }
7136}
7137
7139 if (HybridPatchableAttr *Attr = ND.getAttr<HybridPatchableAttr>()) {
7140 if (!ND.isExternallyVisible())
7141 S.Diag(Attr->getLocation(),
7142 diag::warn_attribute_hybrid_patchable_non_extern);
7143 }
7144}
7145
7147 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
7148 auto *VD = dyn_cast<VarDecl>(&ND);
7149 bool IsAnonymousNS = false;
7150 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
7151 if (VD) {
7152 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
7153 while (NS && !IsAnonymousNS) {
7154 IsAnonymousNS = NS->isAnonymousNamespace();
7155 NS = dyn_cast<NamespaceDecl>(NS->getParent());
7156 }
7157 }
7158 // dll attributes require external linkage. Static locals may have external
7159 // linkage but still cannot be explicitly imported or exported.
7160 // In Microsoft mode, a variable defined in anonymous namespace must have
7161 // external linkage in order to be exported.
7162 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
7163 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
7164 (!AnonNSInMicrosoftMode &&
7165 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
7166 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
7167 << &ND << Attr;
7168 ND.setInvalidDecl();
7169 }
7170 }
7171}
7172
7174 // Check the attributes on the function type and function params, if any.
7175 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
7176 FD = FD->getMostRecentDecl();
7177 // Don't declare this variable in the second operand of the for-statement;
7178 // GCC miscompiles that by ending its lifetime before evaluating the
7179 // third operand. See gcc.gnu.org/PR86769.
7181 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
7182 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7183 TL = ATL.getModifiedLoc()) {
7184 // The [[lifetimebound]] attribute can be applied to the implicit object
7185 // parameter of a non-static member function (other than a ctor or dtor)
7186 // by applying it to the function type.
7187 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
7188 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
7189 int NoImplicitObjectError = -1;
7190 if (!MD)
7191 NoImplicitObjectError = 0;
7192 else if (MD->isStatic())
7193 NoImplicitObjectError = 1;
7194 else if (MD->isExplicitObjectMemberFunction())
7195 NoImplicitObjectError = 2;
7196 if (NoImplicitObjectError != -1) {
7197 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
7198 << NoImplicitObjectError << A->getRange();
7199 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
7200 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
7201 << isa<CXXDestructorDecl>(MD) << A->getRange();
7202 } else if (MD->getReturnType()->isVoidType()) {
7203 S.Diag(
7204 MD->getLocation(),
7205 diag::
7206 err_lifetimebound_implicit_object_parameter_void_return_type);
7207 }
7208 }
7209 }
7210
7211 for (unsigned int I = 0; I < FD->getNumParams(); ++I) {
7212 const ParmVarDecl *P = FD->getParamDecl(I);
7213
7214 // The [[lifetimebound]] attribute can be applied to a function parameter
7215 // only if the function returns a value.
7216 if (auto *A = P->getAttr<LifetimeBoundAttr>()) {
7217 if (!isa<CXXConstructorDecl>(FD) && FD->getReturnType()->isVoidType()) {
7218 S.Diag(A->getLocation(),
7219 diag::err_lifetimebound_parameter_void_return_type);
7220 }
7221 }
7222 }
7223 }
7224}
7225
7227 if (ND.hasAttr<ModularFormatAttr>() && !ND.hasAttr<FormatAttr>())
7228 S.Diag(ND.getLocation(), diag::err_modular_format_attribute_no_format);
7229}
7230
7232 // Ensure that an auto decl is deduced otherwise the checks below might cache
7233 // the wrong linkage.
7234 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
7235
7236 checkWeakAttr(S, ND);
7237 checkWeakRefAttr(S, ND);
7238 checkAliasAttr(S, ND);
7239 checkSelectAnyAttr(S, ND);
7241 checkInheritableAttr(S, ND);
7244}
7245
7247 NamedDecl *NewDecl,
7248 bool IsSpecialization,
7249 bool IsDefinition) {
7250 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
7251 return;
7252
7253 bool IsTemplate = false;
7254 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
7255 OldDecl = OldTD->getTemplatedDecl();
7256 IsTemplate = true;
7257 if (!IsSpecialization)
7258 IsDefinition = false;
7259 }
7260 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
7261 NewDecl = NewTD->getTemplatedDecl();
7262 IsTemplate = true;
7263 }
7264
7265 if (!OldDecl || !NewDecl)
7266 return;
7267
7268 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
7269 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
7270 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
7271 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
7272
7273 // dllimport and dllexport are inheritable attributes so we have to exclude
7274 // inherited attribute instances.
7275 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
7276 (NewExportAttr && !NewExportAttr->isInherited());
7277
7278 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
7279 // the only exception being explicit specializations.
7280 // Implicitly generated declarations are also excluded for now because there
7281 // is no other way to switch these to use dllimport or dllexport.
7282 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
7283
7284 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
7285 // Allow with a warning for free functions and global variables.
7286 bool JustWarn = false;
7287 if (!OldDecl->isCXXClassMember()) {
7288 auto *VD = dyn_cast<VarDecl>(OldDecl);
7289 if (VD && !VD->getDescribedVarTemplate())
7290 JustWarn = true;
7291 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
7292 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
7293 JustWarn = true;
7294 }
7295
7296 // We cannot change a declaration that's been used because IR has already
7297 // been emitted. Dllimported functions will still work though (modulo
7298 // address equality) as they can use the thunk.
7299 if (OldDecl->isUsed())
7300 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
7301 JustWarn = false;
7302
7303 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7304 : diag::err_attribute_dll_redeclaration;
7305 S.Diag(NewDecl->getLocation(), DiagID)
7306 << NewDecl
7307 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7308 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7309 if (!JustWarn) {
7310 NewDecl->setInvalidDecl();
7311 return;
7312 }
7313 }
7314
7315 // A redeclaration is not allowed to drop a dllimport attribute, the only
7316 // exceptions being inline function definitions (except for function
7317 // templates), local extern declarations, qualified friend declarations or
7318 // special MSVC extension: in the last case, the declaration is treated as if
7319 // it were marked dllexport.
7320 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7321 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7322 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
7323 // Ignore static data because out-of-line definitions are diagnosed
7324 // separately.
7325 IsStaticDataMember = VD->isStaticDataMember();
7326 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7328 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
7329 IsInline = FD->isInlined();
7330 IsQualifiedFriend = FD->getQualifier() &&
7331 FD->getFriendObjectKind() == Decl::FOK_Declared;
7332 }
7333
7334 if (OldImportAttr && !HasNewAttr &&
7335 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7336 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7337 if (IsMicrosoftABI && IsDefinition) {
7338 if (IsSpecialization) {
7339 S.Diag(
7340 NewDecl->getLocation(),
7341 diag::err_attribute_dllimport_function_specialization_definition);
7342 S.Diag(OldImportAttr->getLocation(), diag::note_attribute);
7343 NewDecl->dropAttr<DLLImportAttr>();
7344 } else {
7345 S.Diag(NewDecl->getLocation(),
7346 diag::warn_redeclaration_without_import_attribute)
7347 << NewDecl;
7348 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7349 NewDecl->dropAttr<DLLImportAttr>();
7350 NewDecl->addAttr(DLLExportAttr::CreateImplicit(
7351 S.Context, NewImportAttr->getRange()));
7352 }
7353 } else if (IsMicrosoftABI && IsSpecialization) {
7354 assert(!IsDefinition);
7355 // MSVC allows this. Keep the inherited attribute.
7356 } else {
7357 S.Diag(NewDecl->getLocation(),
7358 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7359 << NewDecl << OldImportAttr;
7360 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7361 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
7362 OldDecl->dropAttr<DLLImportAttr>();
7363 NewDecl->dropAttr<DLLImportAttr>();
7364 }
7365 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7366 // In MinGW, seeing a function declared inline drops the dllimport
7367 // attribute.
7368 OldDecl->dropAttr<DLLImportAttr>();
7369 NewDecl->dropAttr<DLLImportAttr>();
7370 S.Diag(NewDecl->getLocation(),
7371 diag::warn_dllimport_dropped_from_inline_function)
7372 << NewDecl << OldImportAttr;
7373 }
7374
7375 // A specialization of a class template member function is processed here
7376 // since it's a redeclaration. If the parent class is dllexport, the
7377 // specialization inherits that attribute. This doesn't happen automatically
7378 // since the parent class isn't instantiated until later.
7379 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
7380 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7381 !NewImportAttr && !NewExportAttr) {
7382 if (const DLLExportAttr *ParentExportAttr =
7383 MD->getParent()->getAttr<DLLExportAttr>()) {
7384 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
7385 NewAttr->setInherited(true);
7386 NewDecl->addAttr(NewAttr);
7387 }
7388 }
7389 }
7390}
7391
7392/// Given that we are within the definition of the given function,
7393/// will that definition behave like C99's 'inline', where the
7394/// definition is discarded except for optimization purposes?
7396 // Try to avoid calling GetGVALinkageForFunction.
7397
7398 // All cases of this require the 'inline' keyword.
7399 if (!FD->isInlined()) return false;
7400
7401 // This is only possible in C++ with the gnu_inline attribute.
7402 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7403 return false;
7404
7405 // Okay, go ahead and call the relatively-more-expensive function.
7407}
7408
7409/// Determine whether a variable is extern "C" prior to attaching
7410/// an initializer. We can't just call isExternC() here, because that
7411/// will also compute and cache whether the declaration is externally
7412/// visible, which might change when we attach the initializer.
7413///
7414/// This can only be used if the declaration is known to not be a
7415/// redeclaration of an internal linkage declaration.
7416///
7417/// For instance:
7418///
7419/// auto x = []{};
7420///
7421/// Attaching the initializer here makes this declaration not externally
7422/// visible, because its type has internal linkage.
7423///
7424/// FIXME: This is a hack.
7425template<typename T>
7426static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7427 if (S.getLangOpts().CPlusPlus) {
7428 // In C++, the overloadable attribute negates the effects of extern "C".
7429 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7430 return false;
7431
7432 // So do CUDA's host/device attributes.
7433 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7434 D->template hasAttr<CUDAHostAttr>()))
7435 return false;
7436 }
7437 return D->isExternC();
7438}
7439
7440static bool shouldConsiderLinkage(const VarDecl *VD) {
7441 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7444 return VD->hasExternalStorage();
7445 if (DC->isFileContext())
7446 return true;
7447 if (DC->isRecord())
7448 return false;
7449 if (DC->getDeclKind() == Decl::HLSLBuffer)
7450 return false;
7451
7453 return false;
7454 llvm_unreachable("Unexpected context");
7455}
7456
7457static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7458 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7459 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7461 return true;
7462 if (DC->isRecord())
7463 return false;
7464 llvm_unreachable("Unexpected context");
7465}
7466
7467static bool hasParsedAttr(Scope *S, const Declarator &PD,
7468 ParsedAttr::Kind Kind) {
7469 // Check decl attributes on the DeclSpec.
7470 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
7471 return true;
7472
7473 // Walk the declarator structure, checking decl attributes that were in a type
7474 // position to the decl itself.
7475 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7476 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
7477 return true;
7478 }
7479
7480 // Finally, check attributes on the decl itself.
7481 return PD.getAttributes().hasAttribute(Kind) ||
7483}
7484
7486 if (!DC->isFunctionOrMethod())
7487 return false;
7488
7489 // If this is a local extern function or variable declared within a function
7490 // template, don't add it into the enclosing namespace scope until it is
7491 // instantiated; it might have a dependent type right now.
7492 if (DC->isDependentContext())
7493 return true;
7494
7495 // C++11 [basic.link]p7:
7496 // When a block scope declaration of an entity with linkage is not found to
7497 // refer to some other declaration, then that entity is a member of the
7498 // innermost enclosing namespace.
7499 //
7500 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7501 // semantically-enclosing namespace, not a lexically-enclosing one.
7502 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
7503 DC = DC->getParent();
7504 return true;
7505}
7506
7507/// Returns true if given declaration has external C language linkage.
7508static bool isDeclExternC(const Decl *D) {
7509 if (const auto *FD = dyn_cast<FunctionDecl>(D))
7510 return FD->isExternC();
7511 if (const auto *VD = dyn_cast<VarDecl>(D))
7512 return VD->isExternC();
7513
7514 llvm_unreachable("Unknown type of decl!");
7515}
7516
7517/// Returns true if there hasn't been any invalid type diagnosed.
7518static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7519 DeclContext *DC = NewVD->getDeclContext();
7520 QualType R = NewVD->getType();
7521
7522 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7523 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7524 // argument.
7525 if (R->isImageType() || R->isPipeType()) {
7526 Se.Diag(NewVD->getLocation(),
7527 diag::err_opencl_type_can_only_be_used_as_function_parameter)
7528 << R;
7529 NewVD->setInvalidDecl();
7530 return false;
7531 }
7532
7533 // OpenCL v1.2 s6.9.r:
7534 // The event type cannot be used to declare a program scope variable.
7535 // OpenCL v2.0 s6.9.q:
7536 // The clk_event_t and reserve_id_t types cannot be declared in program
7537 // scope.
7538 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7539 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7540 Se.Diag(NewVD->getLocation(),
7541 diag::err_invalid_type_for_program_scope_var)
7542 << R;
7543 NewVD->setInvalidDecl();
7544 return false;
7545 }
7546 }
7547
7548 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7549 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7550 Se.getLangOpts())) {
7551 QualType NR = R.getCanonicalType();
7552 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7553 NR->isReferenceType()) {
7556 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7557 << NR->isReferenceType();
7558 NewVD->setInvalidDecl();
7559 return false;
7560 }
7561 NR = NR->getPointeeType();
7562 }
7563 }
7564
7565 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7566 Se.getLangOpts())) {
7567 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7568 // half array type (unless the cl_khr_fp16 extension is enabled).
7569 if (Se.Context.getBaseElementType(R)->isHalfType()) {
7570 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7571 NewVD->setInvalidDecl();
7572 return false;
7573 }
7574 }
7575
7576 // OpenCL v1.2 s6.9.r:
7577 // The event type cannot be used with the __local, __constant and __global
7578 // address space qualifiers.
7579 if (R->isEventT()) {
7581 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7582 NewVD->setInvalidDecl();
7583 return false;
7584 }
7585 }
7586
7587 if (R->isSamplerT()) {
7588 // OpenCL v1.2 s6.9.b p4:
7589 // The sampler type cannot be used with the __local and __global address
7590 // space qualifiers.
7593 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7594 NewVD->setInvalidDecl();
7595 }
7596
7597 // OpenCL v1.2 s6.12.14.1:
7598 // A global sampler must be declared with either the constant address
7599 // space qualifier or with the const qualifier.
7600 if (DC->isTranslationUnit() &&
7602 R.isConstQualified())) {
7603 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7604 NewVD->setInvalidDecl();
7605 }
7606 if (NewVD->isInvalidDecl())
7607 return false;
7608 }
7609
7610 return true;
7611}
7612
7613template <typename AttrTy>
7614static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7615 const TypedefNameDecl *TND = TT->getDecl();
7616 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7617 AttrTy *Clone = Attribute->clone(S.Context);
7618 Clone->setInherited(true);
7619 D->addAttr(Clone);
7620 }
7621}
7622
7623// This function emits warning and a corresponding note based on the
7624// ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7625// declarations of an annotated type must be const qualified.
7627 QualType VarType = VD->getType().getCanonicalType();
7628
7629 // Ignore local declarations (for now) and those with const qualification.
7630 // TODO: Local variables should not be allowed if their type declaration has
7631 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7632 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7633 return;
7634
7635 if (VarType->isArrayType()) {
7636 // Retrieve element type for array declarations.
7637 VarType = S.getASTContext().getBaseElementType(VarType);
7638 }
7639
7640 const RecordDecl *RD = VarType->getAsRecordDecl();
7641
7642 // Check if the record declaration is present and if it has any attributes.
7643 if (RD == nullptr)
7644 return;
7645
7646 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7647 S.Diag(VD->getLocation(), diag::warn_var_decl_not_read_only) << RD;
7648 S.Diag(ConstDecl->getLocation(), diag::note_enforce_read_only_placement);
7649 return;
7650 }
7651}
7652
7654 assert((isa<FunctionDecl>(NewD) || isa<VarDecl>(NewD)) &&
7655 "NewD is not a function or variable");
7656
7657 if (PendingExportedNames.empty())
7658 return;
7659 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(NewD)) {
7660 if (getLangOpts().CPlusPlus && !FD->isExternC())
7661 return;
7662 }
7663 IdentifierInfo *IdentName = NewD->getIdentifier();
7664 if (IdentName == nullptr)
7665 return;
7666 auto PendingName = PendingExportedNames.find(IdentName);
7667 if (PendingName != PendingExportedNames.end()) {
7668 auto &Label = PendingName->second;
7669 if (!Label.Used) {
7670 Label.Used = true;
7671 if (NewD->hasExternalFormalLinkage())
7672 mergeVisibilityType(NewD, Label.NameLoc, VisibilityAttr::Default);
7673 else
7674 Diag(Label.NameLoc, diag::warn_pragma_not_applied) << "export" << NewD;
7675 }
7676 }
7677}
7678
7679// Checks if VD is declared at global scope or with C language linkage.
7680static bool isMainVar(DeclarationName Name, VarDecl *VD) {
7681 return Name.getAsIdentifierInfo() &&
7682 Name.getAsIdentifierInfo()->isStr("main") &&
7683 !VD->getDescribedVarTemplate() &&
7684 (VD->getDeclContext()->getRedeclContext()->isTranslationUnit() ||
7685 VD->isExternC());
7686}
7687
7688void Sema::CheckAsmLabel(Scope *S, Expr *E, StorageClass SC,
7689 TypeSourceInfo *TInfo, VarDecl *NewVD) {
7690
7691 // Quickly return if the function does not have an `asm` attribute.
7692 if (E == nullptr)
7693 return;
7694
7695 // The parser guarantees this is a string.
7696 StringLiteral *SE = cast<StringLiteral>(E);
7697 StringRef Label = SE->getString();
7698 QualType R = TInfo->getType();
7699 if (S->getFnParent() != nullptr) {
7700 switch (SC) {
7701 case SC_None:
7702 case SC_Auto:
7703 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7704 break;
7705 case SC_Register:
7706 // Local Named register
7707 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7709 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7710 break;
7711 case SC_Static:
7712 case SC_Extern:
7713 case SC_PrivateExtern:
7714 break;
7715 }
7716 } else if (SC == SC_Register) {
7717 // Global Named register
7718 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7719 const auto &TI = Context.getTargetInfo();
7720 bool HasSizeMismatch;
7721
7722 if (!TI.isValidGCCRegisterName(Label))
7723 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7724 else if (!TI.validateGlobalRegisterVariable(Label, Context.getTypeSize(R),
7725 HasSizeMismatch))
7726 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7727 else if (HasSizeMismatch)
7728 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7729 }
7730
7731 if (!R->isIntegralType(Context) && !R->isPointerType()) {
7732 Diag(TInfo->getTypeLoc().getBeginLoc(),
7733 diag::err_asm_unsupported_register_type)
7734 << TInfo->getTypeLoc().getSourceRange();
7735 NewVD->setInvalidDecl(true);
7736 }
7737 }
7738}
7739
7741 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7742 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7743 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7744 QualType R = TInfo->getType();
7746
7748 bool IsPlaceholderVariable = false;
7749
7750 if (D.isDecompositionDeclarator()) {
7751 // Take the name of the first declarator as our name for diagnostic
7752 // purposes.
7753 auto &Decomp = D.getDecompositionDeclarator();
7754 if (!Decomp.bindings().empty()) {
7755 II = Decomp.bindings()[0].Name;
7756 Name = II;
7757 }
7758 } else if (!II) {
7759 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7760 return nullptr;
7761 }
7762
7763
7766 if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) &&
7767 SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) {
7768
7769 IsPlaceholderVariable = true;
7770
7771 if (!Previous.empty()) {
7772 NamedDecl *PrevDecl = *Previous.begin();
7773 bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals(
7774 DC->getRedeclContext());
7775 if (SameDC && isDeclInScope(PrevDecl, CurContext, S, false)) {
7776 IsPlaceholderVariable = !isa<ParmVarDecl>(PrevDecl);
7777 if (IsPlaceholderVariable)
7779 }
7780 }
7781 }
7782
7783 // dllimport globals without explicit storage class are treated as extern. We
7784 // have to change the storage class this early to get the right DeclContext.
7785 if (SC == SC_None && !DC->isRecord() &&
7786 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7787 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7788 SC = SC_Extern;
7789
7790 DeclContext *OriginalDC = DC;
7791 bool IsLocalExternDecl = SC == SC_Extern &&
7793
7794 if (SCSpec == DeclSpec::SCS_mutable) {
7795 // mutable can only appear on non-static class members, so it's always
7796 // an error here
7797 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7798 D.setInvalidType();
7799 SC = SC_None;
7800 }
7801
7802 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7803 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7805 // In C++11, the 'register' storage class specifier is deprecated.
7806 // Suppress the warning in system macros, it's used in macros in some
7807 // popular C system headers, such as in glibc's htonl() macro.
7809 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7810 : diag::warn_deprecated_register)
7812 }
7813
7815
7816 if (!DC->isRecord() && S->getFnParent() == nullptr) {
7817 // C99 6.9p2: The storage-class specifiers auto and register shall not
7818 // appear in the declaration specifiers in an external declaration.
7819 // Global Register+Asm is a GNU extension we support.
7820 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7821 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7822 D.setInvalidType();
7823 }
7824 }
7825
7826 // If this variable has a VLA type and an initializer, try to
7827 // fold to a constant-sized type. This is otherwise invalid.
7828 if (D.hasInitializer() && R->isVariableArrayType())
7830 /*DiagID=*/0);
7831
7832 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) {
7833 const AutoType *AT = TL.getTypePtr();
7834 CheckConstrainedAuto(AT, TL.getConceptNameLoc());
7835 }
7836
7837 bool IsMemberSpecialization = false;
7838 bool IsVariableTemplateSpecialization = false;
7839 bool IsPartialSpecialization = false;
7840 bool IsVariableTemplate = false;
7841 VarDecl *NewVD = nullptr;
7842 VarTemplateDecl *NewTemplate = nullptr;
7843 TemplateParameterList *TemplateParams = nullptr;
7844 if (!getLangOpts().CPlusPlus) {
7846 II, R, TInfo, SC);
7847
7848 if (R->getContainedDeducedType())
7849 ParsingInitForAutoVars.insert(NewVD);
7850
7851 if (D.isInvalidType())
7852 NewVD->setInvalidDecl();
7853
7855 NewVD->hasLocalStorage())
7856 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7858 } else {
7859 bool Invalid = false;
7860 // Match up the template parameter lists with the scope specifier, then
7861 // determine whether we have a template or a template specialization.
7864 D.getCXXScopeSpec(),
7866 ? D.getName().TemplateId
7867 : nullptr,
7868 TemplateParamLists,
7869 /*never a friend*/ false, IsMemberSpecialization, Invalid);
7870
7871 if (TemplateParams) {
7872 if (DC->isDependentContext()) {
7873 ContextRAII SavedContext(*this, DC);
7875 Invalid = true;
7876 }
7877
7878 if (!TemplateParams->size() &&
7880 // There is an extraneous 'template<>' for this variable. Complain
7881 // about it, but allow the declaration of the variable.
7882 Diag(TemplateParams->getTemplateLoc(),
7883 diag::err_template_variable_noparams)
7884 << II
7885 << SourceRange(TemplateParams->getTemplateLoc(),
7886 TemplateParams->getRAngleLoc());
7887 TemplateParams = nullptr;
7888 } else {
7889 // Check that we can declare a template here.
7890 if (CheckTemplateDeclScope(S, TemplateParams))
7891 return nullptr;
7892
7894 // This is an explicit specialization or a partial specialization.
7895 IsVariableTemplateSpecialization = true;
7896 IsPartialSpecialization = TemplateParams->size() > 0;
7897 } else { // if (TemplateParams->size() > 0)
7898 // This is a template declaration.
7899 IsVariableTemplate = true;
7900
7901 // Only C++1y supports variable templates (N3651).
7902 DiagCompat(D.getIdentifierLoc(), diag_compat::variable_template);
7903 }
7904 }
7905 } else {
7906 // Check that we can declare a member specialization here.
7907 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7908 CheckTemplateDeclScope(S, TemplateParamLists.back()))
7909 return nullptr;
7910 assert((Invalid ||
7912 "should have a 'template<>' for this decl");
7913 }
7914
7915 bool IsExplicitSpecialization =
7916 IsVariableTemplateSpecialization && !IsPartialSpecialization;
7917
7918 // C++ [temp.expl.spec]p2:
7919 // The declaration in an explicit-specialization shall not be an
7920 // export-declaration. An explicit specialization shall not use a
7921 // storage-class-specifier other than thread_local.
7922 //
7923 // We use the storage-class-specifier from DeclSpec because we may have
7924 // added implicit 'extern' for declarations with __declspec(dllimport)!
7925 if (SCSpec != DeclSpec::SCS_unspecified &&
7926 (IsExplicitSpecialization || IsMemberSpecialization)) {
7928 diag::ext_explicit_specialization_storage_class)
7930 }
7931
7932 if (CurContext->isRecord()) {
7933 if (SC == SC_Static) {
7934 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7935 // Walk up the enclosing DeclContexts to check for any that are
7936 // incompatible with static data members.
7937 const DeclContext *FunctionOrMethod = nullptr;
7938 const CXXRecordDecl *AnonStruct = nullptr;
7939 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7940 if (Ctxt->isFunctionOrMethod()) {
7941 FunctionOrMethod = Ctxt;
7942 break;
7943 }
7944 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7945 if (ParentDecl && !ParentDecl->getDeclName()) {
7946 AnonStruct = ParentDecl;
7947 break;
7948 }
7949 }
7950 if (FunctionOrMethod) {
7951 // C++ [class.static.data]p5: A local class shall not have static
7952 // data members.
7954 diag::err_static_data_member_not_allowed_in_local_class)
7955 << Name << RD->getDeclName() << RD->getTagKind();
7956 } else if (AnonStruct) {
7957 // C++ [class.static.data]p4: Unnamed classes and classes contained
7958 // directly or indirectly within unnamed classes shall not contain
7959 // static data members.
7961 diag::err_static_data_member_not_allowed_in_anon_struct)
7962 << Name << AnonStruct->getTagKind();
7963 Invalid = true;
7964 } else if (RD->isUnion()) {
7965 // C++98 [class.union]p1: If a union contains a static data member,
7966 // the program is ill-formed. C++11 drops this restriction.
7968 diag_compat::static_data_member_in_union)
7969 << Name;
7970 }
7971 }
7972 } else if (IsVariableTemplate || IsPartialSpecialization) {
7973 // There is no such thing as a member field template.
7974 Diag(D.getIdentifierLoc(), diag::err_template_member)
7975 << II << TemplateParams->getSourceRange();
7976 // Recover by pretending this is a static data member template.
7977 SC = SC_Static;
7978 }
7979 } else if (DC->isRecord()) {
7980 // This is an out-of-line definition of a static data member.
7981 switch (SC) {
7982 case SC_None:
7983 break;
7984 case SC_Static:
7986 diag::err_static_out_of_line)
7989 break;
7990 case SC_Auto:
7991 case SC_Register:
7992 case SC_Extern:
7993 // [dcl.stc] p2: The auto or register specifiers shall be applied only
7994 // to names of variables declared in a block or to function parameters.
7995 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7996 // of class members
7997
7999 diag::err_storage_class_for_static_member)
8002 break;
8003 case SC_PrivateExtern:
8004 llvm_unreachable("C storage class in c++!");
8005 }
8006 }
8007
8008 if (IsVariableTemplateSpecialization) {
8009 SourceLocation TemplateKWLoc =
8010 TemplateParamLists.size() > 0
8011 ? TemplateParamLists[0]->getTemplateLoc()
8012 : SourceLocation();
8014 S, D, TInfo, Previous, TemplateKWLoc, TemplateParams, SC,
8016 if (Res.isInvalid())
8017 return nullptr;
8018 NewVD = cast<VarDecl>(Res.get());
8019 AddToScope = false;
8020 } else if (D.isDecompositionDeclarator()) {
8022 D.getIdentifierLoc(), R, TInfo, SC,
8023 Bindings);
8024 } else
8025 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
8026 D.getIdentifierLoc(), II, R, TInfo, SC);
8027
8028 // If this is supposed to be a variable template, create it as such.
8029 if (IsVariableTemplate) {
8030 NewTemplate =
8032 TemplateParams, NewVD);
8033 NewVD->setDescribedVarTemplate(NewTemplate);
8034 }
8035
8036 // If this decl has an auto type in need of deduction, make a note of the
8037 // Decl so we can diagnose uses of it in its own initializer.
8038 if (R->getContainedDeducedType())
8039 ParsingInitForAutoVars.insert(NewVD);
8040
8041 if (D.isInvalidType() || Invalid) {
8042 NewVD->setInvalidDecl();
8043 if (NewTemplate)
8044 NewTemplate->setInvalidDecl();
8045 }
8046
8047 SetNestedNameSpecifier(*this, NewVD, D);
8048
8049 // If we have any template parameter lists that don't directly belong to
8050 // the variable (matching the scope specifier), store them.
8051 // An explicit variable template specialization does not own any template
8052 // parameter lists.
8053 unsigned VDTemplateParamLists =
8054 (TemplateParams && !IsExplicitSpecialization) ? 1 : 0;
8055 if (TemplateParamLists.size() > VDTemplateParamLists)
8057 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
8058 }
8059
8060 if (D.getDeclSpec().isInlineSpecified()) {
8061 if (!getLangOpts().CPlusPlus) {
8062 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
8063 << 0;
8064 } else if (CurContext->isFunctionOrMethod()) {
8065 // 'inline' is not allowed on block scope variable declaration.
8067 diag::err_inline_declaration_block_scope) << Name
8069 } else {
8071 getLangOpts().CPlusPlus17 ? diag::compat_cxx17_inline_variable
8072 : diag::compat_pre_cxx17_inline_variable);
8073 NewVD->setInlineSpecified();
8074 }
8075 }
8076
8077 // Set the lexical context. If the declarator has a C++ scope specifier, the
8078 // lexical context will be different from the semantic context.
8080 if (NewTemplate)
8081 NewTemplate->setLexicalDeclContext(CurContext);
8082
8083 if (IsLocalExternDecl) {
8085 for (auto *B : Bindings)
8086 B->setLocalExternDecl();
8087 else
8088 NewVD->setLocalExternDecl();
8089 }
8090
8091 bool EmitTLSUnsupportedError = false;
8093 // C++11 [dcl.stc]p4:
8094 // When thread_local is applied to a variable of block scope the
8095 // storage-class-specifier static is implied if it does not appear
8096 // explicitly.
8097 // Core issue: 'static' is not implied if the variable is declared
8098 // 'extern'.
8099 if (NewVD->hasLocalStorage() &&
8100 (SCSpec != DeclSpec::SCS_unspecified ||
8102 !DC->isFunctionOrMethod()))
8104 diag::err_thread_non_global)
8106 else if (!Context.getTargetInfo().isTLSSupported()) {
8107 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8108 // Postpone error emission until we've collected attributes required to
8109 // figure out whether it's a host or device variable and whether the
8110 // error should be ignored.
8111 EmitTLSUnsupportedError = true;
8112 // We still need to mark the variable as TLS so it shows up in AST with
8113 // proper storage class for other tools to use even if we're not going
8114 // to emit any code for it.
8115 NewVD->setTSCSpec(TSCS);
8116 } else
8118 diag::err_thread_unsupported);
8119 } else
8120 NewVD->setTSCSpec(TSCS);
8121 }
8122
8123 switch (D.getDeclSpec().getConstexprSpecifier()) {
8125 break;
8126
8129 diag::err_constexpr_wrong_decl_kind)
8130 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
8131 [[fallthrough]];
8132
8134 NewVD->setConstexpr(true);
8135 // C++1z [dcl.spec.constexpr]p1:
8136 // A static data member declared with the constexpr specifier is
8137 // implicitly an inline variable.
8138 if (NewVD->isStaticDataMember() &&
8140 Context.getTargetInfo().getCXXABI().isMicrosoft()))
8141 NewVD->setImplicitlyInline();
8142 break;
8143
8145 if (!NewVD->hasGlobalStorage())
8147 diag::err_constinit_local_variable);
8148 else
8149 NewVD->addAttr(
8150 ConstInitAttr::Create(Context, D.getDeclSpec().getConstexprSpecLoc(),
8151 ConstInitAttr::Keyword_constinit));
8152 break;
8153 }
8154
8155 // C99 6.7.4p3
8156 // An inline definition of a function with external linkage shall
8157 // not contain a definition of a modifiable object with static or
8158 // thread storage duration...
8159 // We only apply this when the function is required to be defined
8160 // elsewhere, i.e. when the function is not 'extern inline'. Note
8161 // that a local variable with thread storage duration still has to
8162 // be marked 'static'. Also note that it's possible to get these
8163 // semantics in C++ using __attribute__((gnu_inline)).
8164 if (SC == SC_Static && S->getFnParent() != nullptr &&
8165 !NewVD->getType().isConstQualified()) {
8167 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
8169 diag::warn_static_local_in_extern_inline);
8171 }
8172 }
8173
8175 if (IsVariableTemplateSpecialization)
8176 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
8177 << (IsPartialSpecialization ? 1 : 0)
8180 else if (IsMemberSpecialization)
8181 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
8182 << 2
8184 else if (NewVD->hasLocalStorage())
8185 Diag(NewVD->getLocation(), diag::err_module_private_local)
8186 << 0 << NewVD
8190 else {
8191 NewVD->setModulePrivate();
8192 if (NewTemplate)
8193 NewTemplate->setModulePrivate();
8194 for (auto *B : Bindings)
8195 B->setModulePrivate();
8196 }
8197 }
8198
8199 if (getLangOpts().OpenCL) {
8201
8203 if (TSC != TSCS_unspecified) {
8205 diag::err_opencl_unknown_type_specifier)
8207 << DeclSpec::getSpecifierName(TSC) << 1;
8208 NewVD->setInvalidDecl();
8209 }
8210 }
8211
8212 // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
8213 // address space if the table has local storage (semantic checks elsewhere
8214 // will produce an error anyway).
8215 if (const auto *ATy = dyn_cast<ArrayType>(NewVD->getType())) {
8216 if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&
8217 !NewVD->hasLocalStorage()) {
8218 QualType Type = Context.getAddrSpaceQualType(
8219 NewVD->getType(), Context.getLangASForBuiltinAddressSpace(1));
8220 NewVD->setType(Type);
8221 }
8222 }
8223
8224 if (Expr *E = D.getAsmLabel()) {
8225 // The parser guarantees this is a string.
8227 StringRef Label = SE->getString();
8228
8229 // Insert the asm attribute.
8230 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, SE->getStrTokenLoc(0)));
8231 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8232 llvm::DenseMap<IdentifierInfo *, AsmLabelAttr *>::iterator I =
8234 if (I != ExtnameUndeclaredIdentifiers.end()) {
8235 if (isDeclExternC(NewVD)) {
8236 NewVD->addAttr(I->second);
8238 } else
8239 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
8240 << /*Variable*/ 1 << NewVD;
8241 }
8242 }
8243
8244 // Handle attributes prior to checking for duplicates in MergeVarDecl
8245 ProcessDeclAttributes(S, NewVD, D);
8246
8247 if (getLangOpts().HLSL)
8249
8250 if (getLangOpts().OpenACC)
8252
8253 // FIXME: This is probably the wrong location to be doing this and we should
8254 // probably be doing this for more attributes (especially for function
8255 // pointer attributes such as format, warn_unused_result, etc.). Ideally
8256 // the code to copy attributes would be generated by TableGen.
8257 if (R->isFunctionPointerType())
8258 if (const auto *TT = R->getAs<TypedefType>())
8260
8261 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8262 if (EmitTLSUnsupportedError &&
8264 (getLangOpts().OpenMPIsTargetDevice &&
8265 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
8267 diag::err_thread_unsupported);
8268
8269 if (EmitTLSUnsupportedError &&
8270 (LangOpts.SYCLIsDevice ||
8271 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)))
8272 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
8273 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
8274 // storage [duration]."
8275 if (SC == SC_None && S->getFnParent() != nullptr &&
8276 (NewVD->hasAttr<CUDASharedAttr>() ||
8277 NewVD->hasAttr<CUDAConstantAttr>())) {
8278 NewVD->setStorageClass(SC_Static);
8279 }
8280 }
8281
8282 // Ensure that dllimport globals without explicit storage class are treated as
8283 // extern. The storage class is set above using parsed attributes. Now we can
8284 // check the VarDecl itself.
8285 assert(!NewVD->hasAttr<DLLImportAttr>() ||
8286 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
8287 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
8288
8289 // In auto-retain/release, infer strong retension for variables of
8290 // retainable type.
8291 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewVD))
8292 NewVD->setInvalidDecl();
8293
8294 // Check the ASM label here, as we need to know all other attributes of the
8295 // Decl first. Otherwise, we can't know if the asm label refers to the
8296 // host or device in a CUDA context. The device has other registers than
8297 // host and we must know where the function will be placed.
8298 CheckAsmLabel(S, D.getAsmLabel(), SC, TInfo, NewVD);
8299
8300 // Find the shadowed declaration before filtering for scope.
8301 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
8303 : nullptr;
8304
8305 // Don't consider existing declarations that are in a different
8306 // scope and are out-of-semantic-context declarations (if the new
8307 // declaration has linkage).
8310 IsMemberSpecialization ||
8311 IsVariableTemplateSpecialization);
8312
8313 // Check whether the previous declaration is in the same block scope. This
8314 // affects whether we merge types with it, per C++11 [dcl.array]p3.
8315 if (getLangOpts().CPlusPlus &&
8316 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
8318 Previous.isSingleResult() && !Previous.isShadowed() &&
8319 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
8320
8321 if (!getLangOpts().CPlusPlus) {
8323 } else {
8324 // If this is an explicit specialization of a static data member, check it.
8325 if (IsMemberSpecialization && !IsVariableTemplate &&
8326 !IsVariableTemplateSpecialization && !NewVD->isInvalidDecl() &&
8328 NewVD->setInvalidDecl();
8329
8330 // Merge the decl with the existing one if appropriate.
8331 if (!Previous.empty()) {
8332 if (Previous.isSingleResult() &&
8333 isa<FieldDecl>(Previous.getFoundDecl()) &&
8334 D.getCXXScopeSpec().isSet()) {
8335 // The user tried to define a non-static data member
8336 // out-of-line (C++ [dcl.meaning]p1).
8337 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
8338 << D.getCXXScopeSpec().getRange();
8339 Previous.clear();
8340 NewVD->setInvalidDecl();
8341 }
8342 } else if (D.getCXXScopeSpec().isSet() &&
8343 !IsVariableTemplateSpecialization) {
8344 // No previous declaration in the qualifying scope.
8345 Diag(D.getIdentifierLoc(), diag::err_no_member)
8346 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
8347 << D.getCXXScopeSpec().getRange();
8348 NewVD->setInvalidDecl();
8349 }
8350
8351 if (!IsPlaceholderVariable)
8353
8354 // CheckVariableDeclaration will set NewVD as invalid if something is in
8355 // error like WebAssembly tables being declared as arrays with a non-zero
8356 // size, but then parsing continues and emits further errors on that line.
8357 // To avoid that we check here if it happened and return nullptr.
8358 if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())
8359 return nullptr;
8360
8361 if (NewTemplate) {
8362 VarTemplateDecl *PrevVarTemplate =
8363 NewVD->getPreviousDecl()
8365 : nullptr;
8366
8367 // Check the template parameter list of this declaration, possibly
8368 // merging in the template parameter list from the previous variable
8369 // template declaration.
8371 TemplateParams,
8372 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8373 : nullptr,
8374 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8375 DC->isDependentContext())
8377 : TPC_Other))
8378 NewVD->setInvalidDecl();
8379
8380 // If we are providing an explicit specialization of a static variable
8381 // template, make a note of that.
8382 if (PrevVarTemplate &&
8383 PrevVarTemplate->getInstantiatedFromMemberTemplate())
8384 PrevVarTemplate->setMemberSpecialization();
8385 }
8386 }
8387
8388 // Diagnose shadowed variables iff this isn't a redeclaration.
8389 if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration())
8390 CheckShadow(NewVD, ShadowedDecl, Previous);
8391
8392 ProcessPragmaWeak(S, NewVD);
8393 ProcessPragmaExport(NewVD);
8394
8395 // If this is the first declaration of an extern C variable, update
8396 // the map of such variables.
8397 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8398 isIncompleteDeclExternC(*this, NewVD))
8400
8401 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8403 Decl *ManglingContextDecl;
8404 std::tie(MCtx, ManglingContextDecl) =
8406 if (MCtx) {
8407 Context.setManglingNumber(
8408 NewVD, MCtx->getManglingNumber(
8409 NewVD, getMSManglingNumber(getLangOpts(), S)));
8410 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
8411 }
8412 }
8413
8414 // Special handling of variable named 'main'.
8415 if (!getLangOpts().Freestanding && isMainVar(Name, NewVD)) {
8416 // C++ [basic.start.main]p3:
8417 // A program that declares
8418 // - a variable main at global scope, or
8419 // - an entity named main with C language linkage (in any namespace)
8420 // is ill-formed
8421 if (getLangOpts().CPlusPlus)
8422 Diag(D.getBeginLoc(), diag::err_main_global_variable)
8423 << NewVD->isExternC();
8424
8425 // In C, and external-linkage variable named main results in undefined
8426 // behavior.
8427 else if (NewVD->hasExternalFormalLinkage())
8428 Diag(D.getBeginLoc(), diag::warn_main_redefined);
8429 }
8430
8431 if (D.isRedeclaration() && !Previous.empty()) {
8432 NamedDecl *Prev = Previous.getRepresentativeDecl();
8433 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
8435 }
8436
8437 if (NewTemplate) {
8438 if (NewVD->isInvalidDecl())
8439 NewTemplate->setInvalidDecl();
8440 ActOnDocumentableDecl(NewTemplate);
8441 return NewTemplate;
8442 }
8443
8444 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8446
8448
8449 return NewVD;
8450}
8451
8452/// Enum describing the %select options in diag::warn_decl_shadow.
8462
8463/// Determine what kind of declaration we're shadowing.
8465 const DeclContext *OldDC) {
8466 if (isa<TypeAliasDecl>(ShadowedDecl))
8467 return SDK_Using;
8468 else if (isa<TypedefDecl>(ShadowedDecl))
8469 return SDK_Typedef;
8470 else if (isa<BindingDecl>(ShadowedDecl))
8471 return SDK_StructuredBinding;
8472 else if (isa<RecordDecl>(OldDC))
8473 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8474
8475 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8476}
8477
8478/// Return the location of the capture if the given lambda captures the given
8479/// variable \p VD, or an invalid source location otherwise.
8481 const ValueDecl *VD) {
8482 for (const Capture &Capture : LSI->Captures) {
8484 return Capture.getLocation();
8485 }
8486 return SourceLocation();
8487}
8488
8490 const LookupResult &R) {
8491 // Only diagnose if we're shadowing an unambiguous field or variable.
8493 return false;
8494
8495 // Return false if warning is ignored.
8496 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
8497}
8498
8500 const LookupResult &R) {
8502 return nullptr;
8503
8504 // Don't diagnose declarations at file scope.
8505 if (D->hasGlobalStorage() && !D->isStaticLocal())
8506 return nullptr;
8507
8508 NamedDecl *ShadowedDecl = R.getFoundDecl();
8509 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8510 : nullptr;
8511}
8512
8514 const LookupResult &R) {
8515 // Don't warn if typedef declaration is part of a class
8516 if (D->getDeclContext()->isRecord())
8517 return nullptr;
8518
8520 return nullptr;
8521
8522 NamedDecl *ShadowedDecl = R.getFoundDecl();
8523 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
8524}
8525
8527 const LookupResult &R) {
8529 return nullptr;
8530
8531 NamedDecl *ShadowedDecl = R.getFoundDecl();
8532 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8533 : nullptr;
8534}
8535
8537 const LookupResult &R) {
8538 DeclContext *NewDC = D->getDeclContext();
8539
8540 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
8541 if (const auto *MD =
8542 dyn_cast<CXXMethodDecl>(getFunctionLevelDeclContext())) {
8543 // Fields aren't shadowed in C++ static members or in member functions
8544 // with an explicit object parameter.
8545 if (MD->isStatic() || MD->isExplicitObjectMemberFunction())
8546 return;
8547 }
8548 // Fields shadowed by constructor parameters are a special case. Usually
8549 // the constructor initializes the field with the parameter.
8550 if (isa<CXXConstructorDecl>(NewDC))
8551 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
8552 // Remember that this was shadowed so we can either warn about its
8553 // modification or its existence depending on warning settings.
8554 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
8555 return;
8556 }
8557 }
8558
8559 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
8560 if (shadowedVar->isExternC()) {
8561 // For shadowing external vars, make sure that we point to the global
8562 // declaration, not a locally scoped extern declaration.
8563 for (auto *I : shadowedVar->redecls())
8564 if (I->isFileVarDecl()) {
8565 ShadowedDecl = I;
8566 break;
8567 }
8568 }
8569
8570 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8571
8572 unsigned WarningDiag = diag::warn_decl_shadow;
8573 SourceLocation CaptureLoc;
8574 if (isa<VarDecl>(D) && NewDC && isa<CXXMethodDecl>(NewDC)) {
8575 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
8576 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
8577 // Handle both VarDecl and BindingDecl in lambda contexts
8578 if (isa<VarDecl, BindingDecl>(ShadowedDecl)) {
8579 const auto *VD = cast<ValueDecl>(ShadowedDecl);
8580 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
8581 if (RD->getLambdaCaptureDefault() == LCD_None) {
8582 // Try to avoid warnings for lambdas with an explicit capture
8583 // list. Warn only when the lambda captures the shadowed decl
8584 // explicitly.
8585 CaptureLoc = getCaptureLocation(LSI, VD);
8586 if (CaptureLoc.isInvalid())
8587 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8588 } else {
8589 // Remember that this was shadowed so we can avoid the warning if
8590 // the shadowed decl isn't captured and the warning settings allow
8591 // it.
8593 ->ShadowingDecls.push_back({D, VD});
8594 return;
8595 }
8596 }
8597 if (isa<FieldDecl>(ShadowedDecl)) {
8598 // If lambda can capture this, then emit default shadowing warning,
8599 // Otherwise it is not really a shadowing case since field is not
8600 // available in lambda's body.
8601 // At this point we don't know that lambda can capture this, so
8602 // remember that this was shadowed and delay until we know.
8604 ->ShadowingDecls.push_back({D, ShadowedDecl});
8605 return;
8606 }
8607 }
8608 // Apply scoping logic to both VarDecl and BindingDecl with local storage
8609 if (isa<VarDecl, BindingDecl>(ShadowedDecl)) {
8610 bool HasLocalStorage = false;
8611 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl))
8612 HasLocalStorage = VD->hasLocalStorage();
8613 else if (const auto *BD = dyn_cast<BindingDecl>(ShadowedDecl))
8614 HasLocalStorage =
8615 cast<VarDecl>(BD->getDecomposedDecl())->hasLocalStorage();
8616
8617 if (HasLocalStorage) {
8618 // A variable can't shadow a local variable or binding in an enclosing
8619 // scope, if they are separated by a non-capturing declaration
8620 // context.
8621 for (DeclContext *ParentDC = NewDC;
8622 ParentDC && !ParentDC->Equals(OldDC);
8623 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
8624 // Only block literals, captured statements, and lambda expressions
8625 // can capture; other scopes don't.
8626 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
8627 !isLambdaCallOperator(ParentDC))
8628 return;
8629 }
8630 }
8631 }
8632 }
8633 }
8634
8635 // Never warn about shadowing a placeholder variable.
8636 if (ShadowedDecl->isPlaceholderVar(getLangOpts()))
8637 return;
8638
8639 // Only warn about certain kinds of shadowing for class members.
8640 if (NewDC) {
8641 // In particular, don't warn about shadowing non-class members.
8642 if (NewDC->isRecord() && !OldDC->isRecord())
8643 return;
8644
8645 // Skip shadowing check if we're in a class scope, dealing with an enum
8646 // constant in a different context.
8647 DeclContext *ReDC = NewDC->getRedeclContext();
8648 if (ReDC->isRecord() && isa<EnumConstantDecl>(D) && !OldDC->Equals(ReDC))
8649 return;
8650
8651 // TODO: should we warn about static data members shadowing
8652 // static data members from base classes?
8653
8654 // TODO: don't diagnose for inaccessible shadowed members.
8655 // This is hard to do perfectly because we might friend the
8656 // shadowing context, but that's just a false negative.
8657 }
8658
8659 DeclarationName Name = R.getLookupName();
8660
8661 // Emit warning and note.
8662 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8663 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8664 if (!CaptureLoc.isInvalid())
8665 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8666 << Name << /*explicitly*/ 1;
8667 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8668}
8669
8671 for (const auto &Shadow : LSI->ShadowingDecls) {
8672 const NamedDecl *ShadowedDecl = Shadow.ShadowedDecl;
8673 // Try to avoid the warning when the shadowed decl isn't captured.
8674 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8675 if (isa<VarDecl, BindingDecl>(ShadowedDecl)) {
8676 const auto *VD = cast<ValueDecl>(ShadowedDecl);
8677 SourceLocation CaptureLoc = getCaptureLocation(LSI, VD);
8678 Diag(Shadow.VD->getLocation(),
8679 CaptureLoc.isInvalid() ? diag::warn_decl_shadow_uncaptured_local
8680 : diag::warn_decl_shadow)
8681 << Shadow.VD->getDeclName()
8682 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8683 if (CaptureLoc.isValid())
8684 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8685 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8686 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8687 } else if (isa<FieldDecl>(ShadowedDecl)) {
8688 Diag(Shadow.VD->getLocation(),
8689 LSI->isCXXThisCaptured() ? diag::warn_decl_shadow
8690 : diag::warn_decl_shadow_uncaptured_local)
8691 << Shadow.VD->getDeclName()
8692 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8693 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8694 }
8695 }
8696}
8697
8699 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8700 return;
8701
8702 LookupResult R(*this, D->getDeclName(), D->getLocation(),
8705 LookupName(R, S);
8706 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8707 CheckShadow(D, ShadowedDecl, R);
8708}
8709
8710/// Check if 'E', which is an expression that is about to be modified, refers
8711/// to a constructor parameter that shadows a field.
8713 // Quickly ignore expressions that can't be shadowing ctor parameters.
8714 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8715 return;
8716 E = E->IgnoreParenImpCasts();
8717 auto *DRE = dyn_cast<DeclRefExpr>(E);
8718 if (!DRE)
8719 return;
8720 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8721 auto I = ShadowingDecls.find(D);
8722 if (I == ShadowingDecls.end())
8723 return;
8724 const NamedDecl *ShadowedDecl = I->second;
8725 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8726 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8727 Diag(D->getLocation(), diag::note_var_declared_here) << D;
8728 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8729
8730 // Avoid issuing multiple warnings about the same decl.
8731 ShadowingDecls.erase(I);
8732}
8733
8734/// Check for conflict between this global or extern "C" declaration and
8735/// previous global or extern "C" declarations. This is only used in C++.
8736template<typename T>
8738 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8739 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8740 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8741
8742 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8743 // The common case: this global doesn't conflict with any extern "C"
8744 // declaration.
8745 return false;
8746 }
8747
8748 if (Prev) {
8749 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8750 // Both the old and new declarations have C language linkage. This is a
8751 // redeclaration.
8752 Previous.clear();
8753 Previous.addDecl(Prev);
8754 return true;
8755 }
8756
8757 // This is a global, non-extern "C" declaration, and there is a previous
8758 // non-global extern "C" declaration. Diagnose if this is a variable
8759 // declaration.
8760 if (!isa<VarDecl>(ND))
8761 return false;
8762 } else {
8763 // The declaration is extern "C". Check for any declaration in the
8764 // translation unit which might conflict.
8765 if (IsGlobal) {
8766 // We have already performed the lookup into the translation unit.
8767 IsGlobal = false;
8768 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8769 I != E; ++I) {
8770 if (isa<VarDecl>(*I)) {
8771 Prev = *I;
8772 break;
8773 }
8774 }
8775 } else {
8777 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8778 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8779 I != E; ++I) {
8780 if (isa<VarDecl>(*I)) {
8781 Prev = *I;
8782 break;
8783 }
8784 // FIXME: If we have any other entity with this name in global scope,
8785 // the declaration is ill-formed, but that is a defect: it breaks the
8786 // 'stat' hack, for instance. Only variables can have mangled name
8787 // clashes with extern "C" declarations, so only they deserve a
8788 // diagnostic.
8789 }
8790 }
8791
8792 if (!Prev)
8793 return false;
8794 }
8795
8796 // Use the first declaration's location to ensure we point at something which
8797 // is lexically inside an extern "C" linkage-spec.
8798 assert(Prev && "should have found a previous declaration to diagnose");
8799 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8800 Prev = FD->getFirstDecl();
8801 else
8802 Prev = cast<VarDecl>(Prev)->getFirstDecl();
8803
8804 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8805 << IsGlobal << ND;
8806 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8807 << IsGlobal;
8808 return false;
8809}
8810
8811/// Apply special rules for handling extern "C" declarations. Returns \c true
8812/// if we have found that this is a redeclaration of some prior entity.
8813///
8814/// Per C++ [dcl.link]p6:
8815/// Two declarations [for a function or variable] with C language linkage
8816/// with the same name that appear in different scopes refer to the same
8817/// [entity]. An entity with C language linkage shall not be declared with
8818/// the same name as an entity in global scope.
8819template<typename T>
8822 if (!S.getLangOpts().CPlusPlus) {
8823 // In C, when declaring a global variable, look for a corresponding 'extern'
8824 // variable declared in function scope. We don't need this in C++, because
8825 // we find local extern decls in the surrounding file-scope DeclContext.
8826 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8827 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8828 Previous.clear();
8829 Previous.addDecl(Prev);
8830 return true;
8831 }
8832 }
8833 return false;
8834 }
8835
8836 // A declaration in the translation unit can conflict with an extern "C"
8837 // declaration.
8838 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8839 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8840
8841 // An extern "C" declaration can conflict with a declaration in the
8842 // translation unit or can be a redeclaration of an extern "C" declaration
8843 // in another scope.
8844 if (isIncompleteDeclExternC(S,ND))
8845 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8846
8847 // Neither global nor extern "C": nothing to do.
8848 return false;
8849}
8850
8851static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc,
8852 QualType T) {
8853 QualType CanonT = SemaRef.Context.getCanonicalType(T);
8854 // C23 6.7.1p5: An object declared with storage-class specifier constexpr or
8855 // any of its members, even recursively, shall not have an atomic type, or a
8856 // variably modified type, or a type that is volatile or restrict qualified.
8857 if (CanonT->isVariablyModifiedType()) {
8858 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8859 return true;
8860 }
8861
8862 // Arrays are qualified by their element type, so get the base type (this
8863 // works on non-arrays as well).
8864 CanonT = SemaRef.Context.getBaseElementType(CanonT);
8865
8866 if (CanonT->isAtomicType() || CanonT.isVolatileQualified() ||
8867 CanonT.isRestrictQualified()) {
8868 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8869 return true;
8870 }
8871
8872 if (CanonT->isRecordType()) {
8873 const RecordDecl *RD = CanonT->getAsRecordDecl();
8874 if (!RD->isInvalidDecl() &&
8875 llvm::any_of(RD->fields(), [&SemaRef, VarLoc](const FieldDecl *F) {
8876 return CheckC23ConstexprVarType(SemaRef, VarLoc, F->getType());
8877 }))
8878 return true;
8879 }
8880
8881 return false;
8882}
8883
8885 // If the decl is already known invalid, don't check it.
8886 if (NewVD->isInvalidDecl())
8887 return;
8888
8889 QualType T = NewVD->getType();
8890
8891 // Defer checking an 'auto' type until its initializer is attached.
8892 if (T->isUndeducedType())
8893 return;
8894
8895 if (NewVD->hasAttrs())
8897
8898 if (T->isObjCObjectType()) {
8899 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8900 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8901 T = Context.getObjCObjectPointerType(T);
8902 NewVD->setType(T);
8903 }
8904
8905 // Emit an error if an address space was applied to decl with local storage.
8906 // This includes arrays of objects with address space qualifiers, but not
8907 // automatic variables that point to other address spaces.
8908 // ISO/IEC TR 18037 S5.1.2
8909 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8910 T.getAddressSpace() != LangAS::Default) {
8911 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8912 NewVD->setInvalidDecl();
8913 return;
8914 }
8915
8916 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8917 // scope.
8918 if (getLangOpts().OpenCLVersion == 120 &&
8919 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8920 getLangOpts()) &&
8921 NewVD->isStaticLocal()) {
8922 Diag(NewVD->getLocation(), diag::err_static_function_scope);
8923 NewVD->setInvalidDecl();
8924 return;
8925 }
8926
8927 if (getLangOpts().OpenCL) {
8928 if (!diagnoseOpenCLTypes(*this, NewVD))
8929 return;
8930
8931 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8932 if (NewVD->hasAttr<BlocksAttr>()) {
8933 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8934 return;
8935 }
8936
8937 if (T->isBlockPointerType()) {
8938 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8939 // can't use 'extern' storage class.
8940 if (!T.isConstQualified()) {
8941 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8942 << 0 /*const*/;
8943 NewVD->setInvalidDecl();
8944 return;
8945 }
8946 if (NewVD->hasExternalStorage()) {
8947 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8948 NewVD->setInvalidDecl();
8949 return;
8950 }
8951 }
8952
8953 // FIXME: Adding local AS in C++ for OpenCL might make sense.
8954 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8955 NewVD->hasExternalStorage()) {
8956 if (!T->isSamplerT() && !T->isDependentType() &&
8957 !(T.getAddressSpace() == LangAS::opencl_constant ||
8958 (T.getAddressSpace() == LangAS::opencl_global &&
8959 getOpenCLOptions().areProgramScopeVariablesSupported(
8960 getLangOpts())))) {
8961 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8962 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8963 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8964 << Scope << "global or constant";
8965 else
8966 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8967 << Scope << "constant";
8968 NewVD->setInvalidDecl();
8969 return;
8970 }
8971 } else {
8972 if (T.getAddressSpace() == LangAS::opencl_global) {
8973 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8974 << 1 /*is any function*/ << "global";
8975 NewVD->setInvalidDecl();
8976 return;
8977 }
8978 // When this extension is enabled, 'local' variables are permitted in
8979 // non-kernel functions and within nested scopes of kernel functions,
8980 // bypassing standard OpenCL address space restrictions.
8981 bool AllowFunctionScopeLocalVariables =
8982 T.getAddressSpace() == LangAS::opencl_local &&
8984 "__cl_clang_function_scope_local_variables", getLangOpts());
8985 if (AllowFunctionScopeLocalVariables) {
8986 // Direct pass: No further diagnostics needed for this specific case.
8987 } else if (T.getAddressSpace() == LangAS::opencl_constant ||
8988 T.getAddressSpace() == LangAS::opencl_local) {
8990 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8991 // in functions.
8992 if (FD && !FD->hasAttr<DeviceKernelAttr>()) {
8993 if (T.getAddressSpace() == LangAS::opencl_constant)
8994 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8995 << 0 /*non-kernel only*/ << "constant";
8996 else
8997 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8998 << 0 /*non-kernel only*/ << "local";
8999 NewVD->setInvalidDecl();
9000 return;
9001 }
9002 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
9003 // in the outermost scope of a kernel function.
9004 if (FD && FD->hasAttr<DeviceKernelAttr>()) {
9005 if (!getCurScope()->isFunctionScope()) {
9006 if (T.getAddressSpace() == LangAS::opencl_constant)
9007 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
9008 << "constant";
9009 else
9010 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
9011 << "local";
9012 NewVD->setInvalidDecl();
9013 return;
9014 }
9015 }
9016 } else if (T.getAddressSpace() != LangAS::opencl_private &&
9017 // If we are parsing a template we didn't deduce an addr
9018 // space yet.
9019 T.getAddressSpace() != LangAS::Default) {
9020 // Do not allow other address spaces on automatic variable.
9021 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
9022 NewVD->setInvalidDecl();
9023 return;
9024 }
9025 }
9026 }
9027
9028 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
9029 && !NewVD->hasAttr<BlocksAttr>()) {
9030 if (getLangOpts().getGC() != LangOptions::NonGC)
9031 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
9032 else {
9033 assert(!getLangOpts().ObjCAutoRefCount);
9034 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
9035 }
9036 }
9037
9038 // WebAssembly tables must be static with a zero length and can't be
9039 // declared within functions.
9040 if (T->isWebAssemblyTableType()) {
9041 if (getCurScope()->getParent()) { // Parent is null at top-level
9042 Diag(NewVD->getLocation(), diag::err_wasm_table_in_function);
9043 NewVD->setInvalidDecl();
9044 return;
9045 }
9046 if (NewVD->getStorageClass() != SC_Static) {
9047 Diag(NewVD->getLocation(), diag::err_wasm_table_must_be_static);
9048 NewVD->setInvalidDecl();
9049 return;
9050 }
9051 const auto *ATy = dyn_cast<ConstantArrayType>(T.getTypePtr());
9052 if (!ATy || ATy->getZExtSize() != 0) {
9053 Diag(NewVD->getLocation(),
9054 diag::err_typecheck_wasm_table_must_have_zero_length);
9055 NewVD->setInvalidDecl();
9056 return;
9057 }
9058 }
9059
9060 // zero sized static arrays are not allowed in HIP device functions
9061 if (getLangOpts().HIP && LangOpts.CUDAIsDevice) {
9062 if (FunctionDecl *FD = getCurFunctionDecl();
9063 FD &&
9064 (FD->hasAttr<CUDADeviceAttr>() || FD->hasAttr<CUDAGlobalAttr>())) {
9065 if (const ConstantArrayType *ArrayT =
9066 getASTContext().getAsConstantArrayType(T);
9067 ArrayT && ArrayT->isZeroSize()) {
9068 Diag(NewVD->getLocation(), diag::err_typecheck_zero_array_size) << 2;
9069 }
9070 }
9071 }
9072
9073 bool isVM = T->isVariablyModifiedType();
9074 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
9075 NewVD->hasAttr<BlocksAttr>())
9077
9078 if ((isVM && NewVD->hasLinkage()) ||
9079 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
9080 bool SizeIsNegative;
9081 llvm::APSInt Oversized;
9083 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
9084 QualType FixedT;
9085 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
9086 FixedT = FixedTInfo->getType();
9087 else if (FixedTInfo) {
9088 // Type and type-as-written are canonically different. We need to fix up
9089 // both types separately.
9090 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
9091 Oversized);
9092 }
9093 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
9094 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
9095 // FIXME: This won't give the correct result for
9096 // int a[10][n];
9097 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
9098
9099 if (NewVD->isFileVarDecl())
9100 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
9101 << SizeRange;
9102 else if (NewVD->isStaticLocal())
9103 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
9104 << SizeRange;
9105 else
9106 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
9107 << SizeRange;
9108 NewVD->setInvalidDecl();
9109 return;
9110 }
9111
9112 if (!FixedTInfo) {
9113 if (NewVD->isFileVarDecl())
9114 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
9115 else
9116 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
9117 NewVD->setInvalidDecl();
9118 return;
9119 }
9120
9121 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
9122 NewVD->setType(FixedT);
9123 NewVD->setTypeSourceInfo(FixedTInfo);
9124 }
9125
9126 if (T->isVoidType()) {
9127 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
9128 // of objects and functions.
9130 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
9131 << T;
9132 NewVD->setInvalidDecl();
9133 return;
9134 }
9135 }
9136
9137 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
9138 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
9139 NewVD->setInvalidDecl();
9140 return;
9141 }
9142
9143 if (!NewVD->hasLocalStorage() && T->isSizelessType() &&
9144 !T.isWebAssemblyReferenceType() && !T->isHLSLSpecificType()) {
9145 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
9146 NewVD->setInvalidDecl();
9147 return;
9148 }
9149
9150 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
9151 Diag(NewVD->getLocation(), diag::err_block_on_vm);
9152 NewVD->setInvalidDecl();
9153 return;
9154 }
9155
9156 if (getLangOpts().C23 && NewVD->isConstexpr() &&
9157 CheckC23ConstexprVarType(*this, NewVD->getLocation(), T)) {
9158 NewVD->setInvalidDecl();
9159 return;
9160 }
9161
9162 if (getLangOpts().CPlusPlus && NewVD->isConstexpr() &&
9163 !T->isDependentType() &&
9165 diag::err_constexpr_var_non_literal)) {
9166 NewVD->setInvalidDecl();
9167 return;
9168 }
9169
9170 // PPC MMA non-pointer types are not allowed as non-local variable types.
9171 if (Context.getTargetInfo().getTriple().isPPC64() &&
9172 !NewVD->isLocalVarDecl() &&
9173 PPC().CheckPPCMMAType(T, NewVD->getLocation())) {
9174 NewVD->setInvalidDecl();
9175 return;
9176 }
9177
9178 // Check that SVE types are only used in functions with SVE available.
9179 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
9181 llvm::StringMap<bool> CallerFeatureMap;
9182 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
9183 if (ARM().checkSVETypeSupport(T, NewVD->getLocation(), FD,
9184 CallerFeatureMap)) {
9185 NewVD->setInvalidDecl();
9186 return;
9187 }
9188 }
9189
9190 if (T->isRVVSizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
9192 llvm::StringMap<bool> CallerFeatureMap;
9193 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
9195 CallerFeatureMap);
9196 }
9197}
9198
9201
9202 // If the decl is already known invalid, don't check it.
9203 if (NewVD->isInvalidDecl())
9204 return false;
9205
9206 // If we did not find anything by this name, look for a non-visible
9207 // extern "C" declaration with the same name.
9208 if (Previous.empty() &&
9210 Previous.setShadowed();
9211
9212 if (!Previous.empty()) {
9213 MergeVarDecl(NewVD, Previous);
9214 return true;
9215 }
9216 return false;
9217}
9218
9221
9222 // Look for methods in base classes that this method might override.
9223 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
9224 /*DetectVirtual=*/false);
9225 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9226 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
9227 DeclarationName Name = MD->getDeclName();
9228
9230 // We really want to find the base class destructor here.
9231 Name = Context.DeclarationNames.getCXXDestructorName(
9232 Context.getCanonicalTagType(BaseRecord));
9233 }
9234
9235 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
9236 CXXMethodDecl *BaseMD =
9237 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
9238 if (!BaseMD || !BaseMD->isVirtual() ||
9239 IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
9240 /*ConsiderCudaAttrs=*/true))
9241 continue;
9242 if (!CheckExplicitObjectOverride(MD, BaseMD))
9243 continue;
9244 if (Overridden.insert(BaseMD).second) {
9245 MD->addOverriddenMethod(BaseMD);
9250 }
9251
9252 // A method can only override one function from each base class. We
9253 // don't track indirectly overridden methods from bases of bases.
9254 return true;
9255 }
9256
9257 return false;
9258 };
9259
9260 DC->lookupInBases(VisitBase, Paths);
9261 return !Overridden.empty();
9262}
9263
9264namespace {
9265 // Struct for holding all of the extra arguments needed by
9266 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
9267 struct ActOnFDArgs {
9268 Scope *S;
9269 Declarator &D;
9270 MultiTemplateParamsArg TemplateParamLists;
9271 bool AddToScope;
9272 };
9273} // end anonymous namespace
9274
9275namespace {
9276
9277// Callback to only accept typo corrections that have a non-zero edit distance.
9278// Also only accept corrections that have the same parent decl.
9279class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
9280 public:
9281 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
9282 CXXRecordDecl *Parent)
9283 : Context(Context), OriginalFD(TypoFD),
9284 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
9285
9286 bool ValidateCandidate(const TypoCorrection &candidate) override {
9287 if (candidate.getEditDistance() == 0)
9288 return false;
9289
9290 SmallVector<unsigned, 1> MismatchedParams;
9291 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
9292 CDeclEnd = candidate.end();
9293 CDecl != CDeclEnd; ++CDecl) {
9294 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9295
9296 if (FD && !FD->hasBody() &&
9297 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
9298 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
9299 CXXRecordDecl *Parent = MD->getParent();
9300 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
9301 return true;
9302 } else if (!ExpectedParent) {
9303 return true;
9304 }
9305 }
9306 }
9307
9308 return false;
9309 }
9310
9311 std::unique_ptr<CorrectionCandidateCallback> clone() override {
9312 return std::make_unique<DifferentNameValidatorCCC>(*this);
9313 }
9314
9315 private:
9316 ASTContext &Context;
9317 FunctionDecl *OriginalFD;
9318 CXXRecordDecl *ExpectedParent;
9319};
9320
9321} // end anonymous namespace
9322
9326
9327/// Generate diagnostics for an invalid function redeclaration.
9328///
9329/// This routine handles generating the diagnostic messages for an invalid
9330/// function redeclaration, including finding possible similar declarations
9331/// or performing typo correction if there are no previous declarations with
9332/// the same name.
9333///
9334/// Returns a NamedDecl iff typo correction was performed and substituting in
9335/// the new declaration name does not cause new errors.
9337 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
9338 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
9339 DeclarationName Name = NewFD->getDeclName();
9340 DeclContext *NewDC = NewFD->getDeclContext();
9341 SmallVector<unsigned, 1> MismatchedParams;
9343 TypoCorrection Correction;
9344 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
9345 unsigned DiagMsg =
9346 IsLocalFriend ? diag::err_no_matching_local_friend :
9347 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
9348 diag::err_member_decl_does_not_match;
9349 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
9350 IsLocalFriend ? Sema::LookupLocalFriendName
9353
9354 NewFD->setInvalidDecl();
9355 if (IsLocalFriend)
9356 SemaRef.LookupName(Prev, S);
9357 else
9358 SemaRef.LookupQualifiedName(Prev, NewDC);
9359 assert(!Prev.isAmbiguous() &&
9360 "Cannot have an ambiguity in previous-declaration lookup");
9361 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9362 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
9363 MD ? MD->getParent() : nullptr);
9364 if (!Prev.empty()) {
9365 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
9366 Func != FuncEnd; ++Func) {
9367 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
9368 if (FD &&
9369 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9370 // Add 1 to the index so that 0 can mean the mismatch didn't
9371 // involve a parameter
9372 unsigned ParamNum =
9373 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
9374 NearMatches.push_back(std::make_pair(FD, ParamNum));
9375 }
9376 }
9377 // If the qualified name lookup yielded nothing, try typo correction
9378 } else if ((Correction = SemaRef.CorrectTypo(
9379 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
9380 &ExtraArgs.D.getCXXScopeSpec(), CCC,
9382 IsLocalFriend ? nullptr : NewDC))) {
9383 // Set up everything for the call to ActOnFunctionDeclarator
9384 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
9385 ExtraArgs.D.getIdentifierLoc());
9386 Previous.clear();
9387 Previous.setLookupName(Correction.getCorrection());
9388 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
9389 CDeclEnd = Correction.end();
9390 CDecl != CDeclEnd; ++CDecl) {
9391 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9392 if (FD && !FD->hasBody() &&
9393 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9394 Previous.addDecl(FD);
9395 }
9396 }
9397 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
9398
9399 NamedDecl *Result;
9400 // Retry building the function declaration with the new previous
9401 // declarations, and with errors suppressed.
9402 {
9403 // Trap errors.
9404 Sema::SFINAETrap Trap(SemaRef);
9405
9406 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
9407 // pieces need to verify the typo-corrected C++ declaration and hopefully
9408 // eliminate the need for the parameter pack ExtraArgs.
9409 Result = SemaRef.ActOnFunctionDeclarator(
9410 ExtraArgs.S, ExtraArgs.D,
9411 Correction.getCorrectionDecl()->getDeclContext(),
9412 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
9413 ExtraArgs.AddToScope);
9414
9415 if (Trap.hasErrorOccurred())
9416 Result = nullptr;
9417 }
9418
9419 if (Result) {
9420 // Determine which correction we picked.
9421 Decl *Canonical = Result->getCanonicalDecl();
9422 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9423 I != E; ++I)
9424 if ((*I)->getCanonicalDecl() == Canonical)
9425 Correction.setCorrectionDecl(*I);
9426
9427 // Let Sema know about the correction.
9429 SemaRef.diagnoseTypo(
9430 Correction,
9431 SemaRef.PDiag(IsLocalFriend
9432 ? diag::err_no_matching_local_friend_suggest
9433 : diag::err_member_decl_does_not_match_suggest)
9434 << Name << NewDC << IsDefinition);
9435 return Result;
9436 }
9437
9438 // Pretend the typo correction never occurred
9439 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
9440 ExtraArgs.D.getIdentifierLoc());
9441 ExtraArgs.D.setRedeclaration(wasRedeclaration);
9442 Previous.clear();
9443 Previous.setLookupName(Name);
9444 }
9445
9446 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
9447 << Name << NewDC << IsDefinition << NewFD->getLocation();
9448
9449 CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD);
9450 if (NewMD && DiagMsg == diag::err_member_decl_does_not_match) {
9451 CXXRecordDecl *RD = NewMD->getParent();
9452 SemaRef.Diag(RD->getLocation(), diag::note_defined_here)
9453 << RD->getName() << RD->getLocation();
9454 }
9455
9456 bool NewFDisConst = NewMD && NewMD->isConst();
9457
9458 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
9459 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
9460 NearMatch != NearMatchEnd; ++NearMatch) {
9461 FunctionDecl *FD = NearMatch->first;
9462 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
9463 bool FDisConst = MD && MD->isConst();
9464 bool IsMember = MD || !IsLocalFriend;
9465
9466 // FIXME: These notes are poorly worded for the local friend case.
9467 if (unsigned Idx = NearMatch->second) {
9468 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
9469 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
9470 if (Loc.isInvalid()) Loc = FD->getLocation();
9471 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
9472 : diag::note_local_decl_close_param_match)
9473 << Idx << FDParam->getType()
9474 << NewFD->getParamDecl(Idx - 1)->getType();
9475 } else if (FDisConst != NewFDisConst) {
9476 auto DB = SemaRef.Diag(FD->getLocation(),
9477 diag::note_member_def_close_const_match)
9478 << NewFDisConst << FD->getSourceRange().getEnd();
9479 if (const auto &FTI = ExtraArgs.D.getFunctionTypeInfo(); !NewFDisConst)
9480 DB << FixItHint::CreateInsertion(FTI.getRParenLoc().getLocWithOffset(1),
9481 " const");
9482 else if (FTI.hasMethodTypeQualifiers() &&
9483 FTI.getConstQualifierLoc().isValid())
9484 DB << FixItHint::CreateRemoval(FTI.getConstQualifierLoc());
9485 } else {
9486 SemaRef.Diag(FD->getLocation(),
9487 IsMember ? diag::note_member_def_close_match
9488 : diag::note_local_decl_close_match);
9489 }
9490 }
9491 return nullptr;
9492}
9493
9495 switch (D.getDeclSpec().getStorageClassSpec()) {
9496 default: llvm_unreachable("Unknown storage class!");
9497 case DeclSpec::SCS_auto:
9501 diag::err_typecheck_sclass_func);
9503 D.setInvalidType();
9504 break;
9505 case DeclSpec::SCS_unspecified: break;
9508 return SC_None;
9509 return SC_Extern;
9510 case DeclSpec::SCS_static: {
9512 // C99 6.7.1p5:
9513 // The declaration of an identifier for a function that has
9514 // block scope shall have no explicit storage-class specifier
9515 // other than extern
9516 // See also (C++ [dcl.stc]p4).
9518 diag::err_static_block_func);
9519 break;
9520 } else
9521 return SC_Static;
9522 }
9524 }
9525
9526 // No explicit storage class has already been returned
9527 return SC_None;
9528}
9529
9531 DeclContext *DC, QualType &R,
9532 TypeSourceInfo *TInfo,
9533 StorageClass SC,
9534 bool &IsVirtualOkay) {
9535 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9536 DeclarationName Name = NameInfo.getName();
9537
9538 FunctionDecl *NewFD = nullptr;
9539 bool isInline = D.getDeclSpec().isInlineSpecified();
9540
9542 if (ConstexprKind == ConstexprSpecKind::Constinit ||
9543 (SemaRef.getLangOpts().C23 &&
9544 ConstexprKind == ConstexprSpecKind::Constexpr)) {
9545
9546 if (SemaRef.getLangOpts().C23)
9547 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9548 diag::err_c23_constexpr_not_variable);
9549 else
9550 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9551 diag::err_constexpr_wrong_decl_kind)
9552 << static_cast<int>(ConstexprKind);
9553 ConstexprKind = ConstexprSpecKind::Unspecified;
9555 }
9556
9557 if (!SemaRef.getLangOpts().CPlusPlus) {
9558 // Determine whether the function was written with a prototype. This is
9559 // true when:
9560 // - there is a prototype in the declarator, or
9561 // - the type R of the function is some kind of typedef or other non-
9562 // attributed reference to a type name (which eventually refers to a
9563 // function type). Note, we can't always look at the adjusted type to
9564 // check this case because attributes may cause a non-function
9565 // declarator to still have a function type. e.g.,
9566 // typedef void func(int a);
9567 // __attribute__((noreturn)) func other_func; // This has a prototype
9568 bool HasPrototype =
9570 (D.getDeclSpec().isTypeRep() &&
9571 SemaRef.GetTypeFromParser(D.getDeclSpec().getRepAsType(), nullptr)
9572 ->isFunctionProtoType()) ||
9574 assert(
9575 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9576 "Strict prototypes are required");
9577
9578 NewFD = FunctionDecl::Create(
9579 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9580 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
9582 /*TrailingRequiresClause=*/{});
9583 if (D.isInvalidType())
9584 NewFD->setInvalidDecl();
9585
9586 return NewFD;
9587 }
9588
9590 AssociatedConstraint TrailingRequiresClause(D.getTrailingRequiresClause());
9591
9592 SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R);
9593
9595 // This is a C++ constructor declaration.
9596 assert(DC->isRecord() &&
9597 "Constructors can only be declared in a member context");
9598
9599 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9601 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9603 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9604 InheritedConstructor(), TrailingRequiresClause);
9605
9606 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9607 // This is a C++ destructor declaration.
9608 if (DC->isRecord()) {
9609 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9612 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
9613 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9614 /*isImplicitlyDeclared=*/false, ConstexprKind,
9615 TrailingRequiresClause);
9616 // User defined destructors start as not selected if the class definition is still
9617 // not done.
9618 if (Record->isBeingDefined())
9619 NewDD->setIneligibleOrNotSelected(true);
9620
9621 // If the destructor needs an implicit exception specification, set it
9622 // now. FIXME: It'd be nice to be able to create the right type to start
9623 // with, but the type needs to reference the destructor declaration.
9624 if (SemaRef.getLangOpts().CPlusPlus11)
9625 SemaRef.AdjustDestructorExceptionSpec(NewDD);
9626
9627 IsVirtualOkay = true;
9628 return NewDD;
9629
9630 } else {
9631 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
9632 D.setInvalidType();
9633
9634 // Create a FunctionDecl to satisfy the function definition parsing
9635 // code path.
9636 return FunctionDecl::Create(
9637 SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
9638 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9639 /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
9640 }
9641
9643 if (!DC->isRecord()) {
9644 SemaRef.Diag(D.getIdentifierLoc(),
9645 diag::err_conv_function_not_member);
9646 return nullptr;
9647 }
9648
9649 SemaRef.CheckConversionDeclarator(D, R, SC);
9650 if (D.isInvalidType())
9651 return nullptr;
9652
9653 IsVirtualOkay = true;
9655 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9656 TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9657 ExplicitSpecifier, ConstexprKind, SourceLocation(),
9658 TrailingRequiresClause);
9659
9661 if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))
9662 return nullptr;
9664 SemaRef.Context, DC, D.getBeginLoc(), ExplicitSpecifier, NameInfo, R,
9665 TInfo, D.getEndLoc(), /*Ctor=*/nullptr,
9666 /*Kind=*/DeductionCandidate::Normal, TrailingRequiresClause);
9667 } else if (DC->isRecord()) {
9668 // If the name of the function is the same as the name of the record,
9669 // then this must be an invalid constructor that has a return type.
9670 // (The parser checks for a return type and makes the declarator a
9671 // constructor if it has no return type).
9672 if (Name.getAsIdentifierInfo() &&
9673 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
9674 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
9677 return nullptr;
9678 }
9679
9680 // This is a C++ method declaration.
9682 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9683 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9684 ConstexprKind, SourceLocation(), TrailingRequiresClause);
9685 IsVirtualOkay = !Ret->isStatic();
9686 return Ret;
9687 } else {
9688 bool isFriend =
9689 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9690 if (!isFriend && SemaRef.CurContext->isRecord())
9691 return nullptr;
9692
9693 // Determine whether the function was written with a
9694 // prototype. This true when:
9695 // - we're in C++ (where every function has a prototype),
9696 return FunctionDecl::Create(
9697 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9698 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9699 true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9700 }
9701}
9702
9711
9713 // Size dependent types are just typedefs to normal integer types
9714 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9715 // integers other than by their names.
9716 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9717
9718 // Remove typedefs one by one until we reach a typedef
9719 // for a size dependent type.
9720 QualType DesugaredTy = Ty;
9721 do {
9722 ArrayRef<StringRef> Names(SizeTypeNames);
9723 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
9724 if (Names.end() != Match)
9725 return true;
9726
9727 Ty = DesugaredTy;
9728 DesugaredTy = Ty.getSingleStepDesugaredType(C);
9729 } while (DesugaredTy != Ty);
9730
9731 return false;
9732}
9733
9735 if (PT->isDependentType())
9736 return InvalidKernelParam;
9737
9738 if (PT->isPointerOrReferenceType()) {
9739 QualType PointeeType = PT->getPointeeType();
9740 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9741 PointeeType.getAddressSpace() == LangAS::opencl_private ||
9742 PointeeType.getAddressSpace() == LangAS::Default)
9744
9745 if (PointeeType->isPointerType()) {
9746 // This is a pointer to pointer parameter.
9747 // Recursively check inner type.
9748 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
9749 if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9750 ParamKind == InvalidKernelParam)
9751 return ParamKind;
9752
9753 // OpenCL v3.0 s6.11.a:
9754 // A restriction to pass pointers to pointers only applies to OpenCL C
9755 // v1.2 or below.
9757 return ValidKernelParam;
9758
9759 return PtrPtrKernelParam;
9760 }
9761
9762 // C++ for OpenCL v1.0 s2.4:
9763 // Moreover the types used in parameters of the kernel functions must be:
9764 // Standard layout types for pointer parameters. The same applies to
9765 // reference if an implementation supports them in kernel parameters.
9766 if (S.getLangOpts().OpenCLCPlusPlus &&
9768 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts())) {
9769 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9770 bool IsStandardLayoutType = true;
9771 if (CXXRec) {
9772 // If template type is not ODR-used its definition is only available
9773 // in the template definition not its instantiation.
9774 // FIXME: This logic doesn't work for types that depend on template
9775 // parameter (PR58590).
9776 if (!CXXRec->hasDefinition())
9777 CXXRec = CXXRec->getTemplateInstantiationPattern();
9778 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9779 IsStandardLayoutType = false;
9780 }
9781 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9782 !IsStandardLayoutType)
9783 return InvalidKernelParam;
9784 }
9785
9786 // OpenCL v1.2 s6.9.p:
9787 // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9789 return ValidKernelParam;
9790
9791 return PtrKernelParam;
9792 }
9793
9794 // OpenCL v1.2 s6.9.k:
9795 // Arguments to kernel functions in a program cannot be declared with the
9796 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9797 // uintptr_t or a struct and/or union that contain fields declared to be one
9798 // of these built-in scalar types.
9800 return InvalidKernelParam;
9801
9802 if (PT->isImageType())
9803 return PtrKernelParam;
9804
9805 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9806 return InvalidKernelParam;
9807
9808 // OpenCL extension spec v1.2 s9.5:
9809 // This extension adds support for half scalar and vector types as built-in
9810 // types that can be used for arithmetic operations, conversions etc.
9811 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
9812 PT->isHalfType())
9813 return InvalidKernelParam;
9814
9815 // Look into an array argument to check if it has a forbidden type.
9816 if (PT->isArrayType()) {
9817 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9818 // Call ourself to check an underlying type of an array. Since the
9819 // getPointeeOrArrayElementType returns an innermost type which is not an
9820 // array, this recursive call only happens once.
9821 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
9822 }
9823
9824 // C++ for OpenCL v1.0 s2.4:
9825 // Moreover the types used in parameters of the kernel functions must be:
9826 // Trivial and standard-layout types C++17 [basic.types] (plain old data
9827 // types) for parameters passed by value;
9828 if (S.getLangOpts().OpenCLCPlusPlus &&
9830 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9831 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
9832 return InvalidKernelParam;
9833
9834 if (PT->isRecordType())
9835 return RecordKernelParam;
9836
9837 return ValidKernelParam;
9838}
9839
9841 Sema &S,
9842 Declarator &D,
9843 ParmVarDecl *Param,
9844 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9845 QualType PT = Param->getType();
9846
9847 // Cache the valid types we encounter to avoid rechecking structs that are
9848 // used again
9849 if (ValidTypes.count(PT.getTypePtr()))
9850 return;
9851
9852 switch (getOpenCLKernelParameterType(S, PT)) {
9853 case PtrPtrKernelParam:
9854 // OpenCL v3.0 s6.11.a:
9855 // A kernel function argument cannot be declared as a pointer to a pointer
9856 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9857 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9858 D.setInvalidType();
9859 return;
9860
9862 // OpenCL v1.0 s6.5:
9863 // __kernel function arguments declared to be a pointer of a type can point
9864 // to one of the following address spaces only : __global, __local or
9865 // __constant.
9866 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9867 D.setInvalidType();
9868 return;
9869
9870 // OpenCL v1.2 s6.9.k:
9871 // Arguments to kernel functions in a program cannot be declared with the
9872 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9873 // uintptr_t or a struct and/or union that contain fields declared to be
9874 // one of these built-in scalar types.
9875
9876 case InvalidKernelParam:
9877 // OpenCL v1.2 s6.8 n:
9878 // A kernel function argument cannot be declared
9879 // of event_t type.
9880 // Do not diagnose half type since it is diagnosed as invalid argument
9881 // type for any function elsewhere.
9882 if (!PT->isHalfType()) {
9883 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9884
9885 // Explain what typedefs are involved.
9886 const TypedefType *Typedef = nullptr;
9887 while ((Typedef = PT->getAs<TypedefType>())) {
9888 SourceLocation Loc = Typedef->getDecl()->getLocation();
9889 // SourceLocation may be invalid for a built-in type.
9890 if (Loc.isValid())
9891 S.Diag(Loc, diag::note_entity_declared_at) << PT;
9892 PT = Typedef->desugar();
9893 }
9894 }
9895
9896 D.setInvalidType();
9897 return;
9898
9899 case PtrKernelParam:
9900 case ValidKernelParam:
9901 ValidTypes.insert(PT.getTypePtr());
9902 return;
9903
9904 case RecordKernelParam:
9905 break;
9906 }
9907
9908 // Track nested structs we will inspect
9910
9911 // Track where we are in the nested structs. Items will migrate from
9912 // VisitStack to HistoryStack as we do the DFS for bad field.
9914 HistoryStack.push_back(nullptr);
9915
9916 // At this point we already handled everything except of a RecordType.
9917 assert(PT->isRecordType() && "Unexpected type.");
9918 const auto *PD = PT->castAsRecordDecl();
9919 VisitStack.push_back(PD);
9920 assert(VisitStack.back() && "First decl null?");
9921
9922 do {
9923 const Decl *Next = VisitStack.pop_back_val();
9924 if (!Next) {
9925 assert(!HistoryStack.empty());
9926 // Found a marker, we have gone up a level
9927 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9928 ValidTypes.insert(Hist->getType().getTypePtr());
9929
9930 continue;
9931 }
9932
9933 // Adds everything except the original parameter declaration (which is not a
9934 // field itself) to the history stack.
9935 const RecordDecl *RD;
9936 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9937 HistoryStack.push_back(Field);
9938
9939 QualType FieldTy = Field->getType();
9940 // Other field types (known to be valid or invalid) are handled while we
9941 // walk around RecordDecl::fields().
9942 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9943 "Unexpected type.");
9944 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9945
9946 RD = FieldRecTy->castAsRecordDecl();
9947 } else {
9948 RD = cast<RecordDecl>(Next);
9949 }
9950
9951 // Add a null marker so we know when we've gone back up a level
9952 VisitStack.push_back(nullptr);
9953
9954 for (const auto *FD : RD->fields()) {
9955 QualType QT = FD->getType();
9956
9957 if (ValidTypes.count(QT.getTypePtr()))
9958 continue;
9959
9961 if (ParamType == ValidKernelParam)
9962 continue;
9963
9964 if (ParamType == RecordKernelParam) {
9965 VisitStack.push_back(FD);
9966 continue;
9967 }
9968
9969 // OpenCL v1.2 s6.9.p:
9970 // Arguments to kernel functions that are declared to be a struct or union
9971 // do not allow OpenCL objects to be passed as elements of the struct or
9972 // union. This restriction was lifted in OpenCL v2.0 with the introduction
9973 // of SVM.
9974 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9975 ParamType == InvalidAddrSpacePtrKernelParam) {
9976 S.Diag(Param->getLocation(),
9977 diag::err_record_with_pointers_kernel_param)
9978 << PT->isUnionType()
9979 << PT;
9980 } else {
9981 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9982 }
9983
9984 S.Diag(PD->getLocation(), diag::note_within_field_of_type)
9985 << PD->getDeclName();
9986
9987 // We have an error, now let's go back up through history and show where
9988 // the offending field came from
9990 I = HistoryStack.begin() + 1,
9991 E = HistoryStack.end();
9992 I != E; ++I) {
9993 const FieldDecl *OuterField = *I;
9994 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9995 << OuterField->getType();
9996 }
9997
9998 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9999 << QT->isPointerType()
10000 << QT;
10001 D.setInvalidType();
10002 return;
10003 }
10004 } while (!VisitStack.empty());
10005}
10006
10007/// Find the DeclContext in which a tag is implicitly declared if we see an
10008/// elaborated type specifier in the specified context, and lookup finds
10009/// nothing.
10011 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
10012 DC = DC->getParent();
10013 return DC;
10014}
10015
10016/// Find the Scope in which a tag is implicitly declared if we see an
10017/// elaborated type specifier in the specified context, and lookup finds
10018/// nothing.
10019static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
10020 while (S->isClassScope() ||
10021 (LangOpts.CPlusPlus &&
10023 ((S->getFlags() & Scope::DeclScope) == 0) ||
10024 (S->getEntity() && S->getEntity()->isTransparentContext()))
10025 S = S->getParent();
10026 return S;
10027}
10028
10029/// Determine whether a declaration matches a known function in namespace std.
10031 unsigned BuiltinID) {
10032 switch (BuiltinID) {
10033 case Builtin::BI__GetExceptionInfo:
10034 // No type checking whatsoever.
10035 return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
10036
10037 case Builtin::BIaddressof:
10038 case Builtin::BI__addressof:
10039 case Builtin::BIforward:
10040 case Builtin::BIforward_like:
10041 case Builtin::BImove:
10042 case Builtin::BImove_if_noexcept:
10043 case Builtin::BIas_const: {
10044 // Ensure that we don't treat the algorithm
10045 // OutputIt std::move(InputIt, InputIt, OutputIt)
10046 // as the builtin std::move.
10047 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10048 return FPT->getNumParams() == 1 && !FPT->isVariadic();
10049 }
10050
10051 default:
10052 return false;
10053 }
10054}
10055
10056NamedDecl*
10059 MultiTemplateParamsArg TemplateParamListsRef,
10060 bool &AddToScope) {
10061 QualType R = TInfo->getType();
10062
10063 assert(R->isFunctionType());
10065 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
10066
10067 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
10068 llvm::append_range(TemplateParamLists, TemplateParamListsRef);
10070 if (!TemplateParamLists.empty() && !TemplateParamLists.back()->empty() &&
10071 Invented->getDepth() == TemplateParamLists.back()->getDepth())
10072 TemplateParamLists.back() = Invented;
10073 else
10074 TemplateParamLists.push_back(Invented);
10075 }
10076
10077 // TODO: consider using NameInfo for diagnostic.
10079 DeclarationName Name = NameInfo.getName();
10081
10084 diag::err_invalid_thread)
10086
10091
10092 bool isFriend = false;
10094 bool isMemberSpecialization = false;
10095 bool isFunctionTemplateSpecialization = false;
10096
10097 bool HasExplicitTemplateArgs = false;
10098 TemplateArgumentListInfo TemplateArgs;
10099
10100 bool isVirtualOkay = false;
10101
10102 DeclContext *OriginalDC = DC;
10103 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
10104
10105 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
10106 isVirtualOkay);
10107 if (!NewFD) return nullptr;
10108
10109 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
10111
10112 // Set the lexical context. If this is a function-scope declaration, or has a
10113 // C++ scope specifier, or is the object of a friend declaration, the lexical
10114 // context will be different from the semantic context.
10116
10117 if (IsLocalExternDecl)
10118 NewFD->setLocalExternDecl();
10119
10120 if (getLangOpts().CPlusPlus) {
10121 // The rules for implicit inlines changed in C++20 for methods and friends
10122 // with an in-class definition (when such a definition is not attached to
10123 // the global module). This does not affect declarations that are already
10124 // inline (whether explicitly or implicitly by being declared constexpr,
10125 // consteval, etc).
10126 // FIXME: We need a better way to separate C++ standard and clang modules.
10127 bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
10128 !NewFD->getOwningModule() ||
10129 NewFD->isFromGlobalModule() ||
10131 bool isInline = D.getDeclSpec().isInlineSpecified();
10132 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10133 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
10134 isFriend = D.getDeclSpec().isFriendSpecified();
10135 if (ImplicitInlineCXX20 && isFriend && D.isFunctionDefinition()) {
10136 // Pre-C++20 [class.friend]p5
10137 // A function can be defined in a friend declaration of a
10138 // class . . . . Such a function is implicitly inline.
10139 // Post C++20 [class.friend]p7
10140 // Such a function is implicitly an inline function if it is attached
10141 // to the global module.
10142 NewFD->setImplicitlyInline();
10143 }
10144
10145 // If this is a method defined in an __interface, and is not a constructor
10146 // or an overloaded operator, then set the pure flag (isVirtual will already
10147 // return true).
10148 if (const CXXRecordDecl *Parent =
10149 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
10150 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
10151 NewFD->setIsPureVirtual(true);
10152
10153 // C++ [class.union]p2
10154 // A union can have member functions, but not virtual functions.
10155 if (isVirtual && Parent->isUnion()) {
10156 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
10157 NewFD->setInvalidDecl();
10158 }
10159 if ((Parent->isClass() || Parent->isStruct()) &&
10160 Parent->hasAttr<SYCLSpecialClassAttr>() &&
10161 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
10162 NewFD->getName() == "__init" && D.isFunctionDefinition()) {
10163 if (auto *Def = Parent->getDefinition())
10164 Def->setInitMethod(true);
10165 }
10166 }
10167
10168 SetNestedNameSpecifier(*this, NewFD, D);
10169 isMemberSpecialization = false;
10170 isFunctionTemplateSpecialization = false;
10171 if (D.isInvalidType())
10172 NewFD->setInvalidDecl();
10173
10174 // Match up the template parameter lists with the scope specifier, then
10175 // determine whether we have a template or a template specialization.
10176 bool Invalid = false;
10177 TemplateIdAnnotation *TemplateId =
10179 ? D.getName().TemplateId
10180 : nullptr;
10181 TemplateParameterList *TemplateParams =
10184 D.getCXXScopeSpec(), TemplateId, TemplateParamLists, isFriend,
10185 isMemberSpecialization, Invalid);
10186 if (TemplateParams) {
10187 // Check that we can declare a template here.
10188 if (CheckTemplateDeclScope(S, TemplateParams))
10189 NewFD->setInvalidDecl();
10190
10191 if (TemplateParams->size() > 0) {
10192 // This is a function template
10193
10194 // A destructor cannot be a template.
10196 Diag(NewFD->getLocation(), diag::err_destructor_template);
10197 NewFD->setInvalidDecl();
10198 // Function template with explicit template arguments.
10199 } else if (TemplateId) {
10200 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
10201 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
10202 NewFD->setInvalidDecl();
10203 }
10204
10205 // If we're adding a template to a dependent context, we may need to
10206 // rebuilding some of the types used within the template parameter list,
10207 // now that we know what the current instantiation is.
10208 if (DC->isDependentContext()) {
10209 ContextRAII SavedContext(*this, DC);
10211 Invalid = true;
10212 }
10213
10215 NewFD->getLocation(),
10216 Name, TemplateParams,
10217 NewFD);
10218 FunctionTemplate->setLexicalDeclContext(CurContext);
10220
10221 // For source fidelity, store the other template param lists.
10222 if (TemplateParamLists.size() > 1) {
10224 ArrayRef<TemplateParameterList *>(TemplateParamLists)
10225 .drop_back(1));
10226 }
10227 } else {
10228 // This is a function template specialization.
10229 isFunctionTemplateSpecialization = true;
10230 // For source fidelity, store all the template param lists.
10231 if (TemplateParamLists.size() > 0)
10232 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
10233
10234 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
10235 if (isFriend) {
10236 // We want to remove the "template<>", found here.
10237 SourceRange RemoveRange = TemplateParams->getSourceRange();
10238
10239 // If we remove the template<> and the name is not a
10240 // template-id, we're actually silently creating a problem:
10241 // the friend declaration will refer to an untemplated decl,
10242 // and clearly the user wants a template specialization. So
10243 // we need to insert '<>' after the name.
10244 SourceLocation InsertLoc;
10246 InsertLoc = D.getName().getSourceRange().getEnd();
10247 InsertLoc = getLocForEndOfToken(InsertLoc);
10248 }
10249
10250 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
10251 << Name << RemoveRange
10252 << FixItHint::CreateRemoval(RemoveRange)
10253 << FixItHint::CreateInsertion(InsertLoc, "<>");
10254 Invalid = true;
10255
10256 // Recover by faking up an empty template argument list.
10257 HasExplicitTemplateArgs = true;
10258 TemplateArgs.setLAngleLoc(InsertLoc);
10259 TemplateArgs.setRAngleLoc(InsertLoc);
10260 }
10261 }
10262 } else {
10263 // Check that we can declare a template here.
10264 if (!TemplateParamLists.empty() && isMemberSpecialization &&
10265 CheckTemplateDeclScope(S, TemplateParamLists.back()))
10266 NewFD->setInvalidDecl();
10267
10268 // All template param lists were matched against the scope specifier:
10269 // this is NOT (an explicit specialization of) a template.
10270 if (TemplateParamLists.size() > 0)
10271 // For source fidelity, store all the template param lists.
10272 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
10273
10274 // "friend void foo<>(int);" is an implicit specialization decl.
10275 if (isFriend && TemplateId)
10276 isFunctionTemplateSpecialization = true;
10277 }
10278
10279 // If this is a function template specialization and the unqualified-id of
10280 // the declarator-id is a template-id, convert the template argument list
10281 // into our AST format and check for unexpanded packs.
10282 if (isFunctionTemplateSpecialization && TemplateId) {
10283 HasExplicitTemplateArgs = true;
10284
10285 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
10286 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
10287 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
10288 TemplateId->NumArgs);
10289 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
10290
10291 // FIXME: Should we check for unexpanded packs if this was an (invalid)
10292 // declaration of a function template partial specialization? Should we
10293 // consider the unexpanded pack context to be a partial specialization?
10294 for (const TemplateArgumentLoc &ArgLoc : TemplateArgs.arguments()) {
10296 ArgLoc, isFriend ? UPPC_FriendDeclaration
10298 NewFD->setInvalidDecl();
10299 }
10300 }
10301
10302 if (Invalid) {
10303 NewFD->setInvalidDecl();
10304 if (FunctionTemplate)
10305 FunctionTemplate->setInvalidDecl();
10306 }
10307
10308 // C++ [dcl.fct.spec]p5:
10309 // The virtual specifier shall only be used in declarations of
10310 // nonstatic class member functions that appear within a
10311 // member-specification of a class declaration; see 10.3.
10312 //
10313 if (isVirtual && !NewFD->isInvalidDecl()) {
10314 if (!isVirtualOkay) {
10316 diag::err_virtual_non_function);
10317 } else if (!CurContext->isRecord()) {
10318 // 'virtual' was specified outside of the class.
10320 diag::err_virtual_out_of_class)
10322 } else if (NewFD->getDescribedFunctionTemplate()) {
10323 // C++ [temp.mem]p3:
10324 // A member function template shall not be virtual.
10326 diag::err_virtual_member_function_template)
10328 } else {
10329 // Okay: Add virtual to the method.
10330 NewFD->setVirtualAsWritten(true);
10331 }
10332
10333 if (getLangOpts().CPlusPlus14 &&
10334 NewFD->getReturnType()->isUndeducedType())
10335 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
10336 }
10337
10338 // C++ [dcl.fct.spec]p3:
10339 // The inline specifier shall not appear on a block scope function
10340 // declaration.
10341 if (isInline && !NewFD->isInvalidDecl()) {
10342 if (CurContext->isFunctionOrMethod()) {
10343 // 'inline' is not allowed on block scope function declaration.
10345 diag::err_inline_declaration_block_scope) << Name
10347 }
10348 }
10349
10350 // C++ [dcl.fct.spec]p6:
10351 // The explicit specifier shall be used only in the declaration of a
10352 // constructor or conversion function within its class definition;
10353 // see 12.3.1 and 12.3.2.
10354 if (hasExplicit && !NewFD->isInvalidDecl() &&
10356 if (!CurContext->isRecord()) {
10357 // 'explicit' was specified outside of the class.
10359 diag::err_explicit_out_of_class)
10361 } else if (!isa<CXXConstructorDecl>(NewFD) &&
10362 !isa<CXXConversionDecl>(NewFD)) {
10363 // 'explicit' was specified on a function that wasn't a constructor
10364 // or conversion function.
10366 diag::err_explicit_non_ctor_or_conv_function)
10368 }
10369 }
10370
10372 if (ConstexprKind != ConstexprSpecKind::Unspecified) {
10373 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
10374 // are implicitly inline.
10375 NewFD->setImplicitlyInline();
10376
10377 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
10378 // be either constructors or to return a literal type. Therefore,
10379 // destructors cannot be declared constexpr.
10380 if (isa<CXXDestructorDecl>(NewFD) &&
10382 ConstexprKind == ConstexprSpecKind::Consteval)) {
10383 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
10384 << static_cast<int>(ConstexprKind);
10388 }
10389 // C++20 [dcl.constexpr]p2: An allocation function, or a
10390 // deallocation function shall not be declared with the consteval
10391 // specifier.
10392 if (ConstexprKind == ConstexprSpecKind::Consteval &&
10395 diag::err_invalid_consteval_decl_kind)
10396 << NewFD;
10398 }
10399 }
10400
10401 // If __module_private__ was specified, mark the function accordingly.
10403 if (isFunctionTemplateSpecialization) {
10404 SourceLocation ModulePrivateLoc
10406 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
10407 << 0
10408 << FixItHint::CreateRemoval(ModulePrivateLoc);
10409 } else {
10410 NewFD->setModulePrivate();
10411 if (FunctionTemplate)
10412 FunctionTemplate->setModulePrivate();
10413 }
10414 }
10415
10416 if (isFriend) {
10417 if (FunctionTemplate) {
10418 FunctionTemplate->setObjectOfFriendDecl();
10419 FunctionTemplate->setAccess(AS_public);
10420 }
10421 NewFD->setObjectOfFriendDecl();
10422 NewFD->setAccess(AS_public);
10423 }
10424
10425 // If a function is defined as defaulted or deleted, mark it as such now.
10426 // We'll do the relevant checks on defaulted / deleted functions later.
10427 switch (D.getFunctionDefinitionKind()) {
10430 break;
10431
10433 NewFD->setDefaulted();
10434 break;
10435
10437 NewFD->setDeletedAsWritten();
10438 break;
10439 }
10440
10441 if (ImplicitInlineCXX20 && isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
10443 // Pre C++20 [class.mfct]p2:
10444 // A member function may be defined (8.4) in its class definition, in
10445 // which case it is an inline member function (7.1.2)
10446 // Post C++20 [class.mfct]p1:
10447 // If a member function is attached to the global module and is defined
10448 // in its class definition, it is inline.
10449 NewFD->setImplicitlyInline();
10450 }
10451
10452 if (!isFriend && SC != SC_None) {
10453 // C++ [temp.expl.spec]p2:
10454 // The declaration in an explicit-specialization shall not be an
10455 // export-declaration. An explicit specialization shall not use a
10456 // storage-class-specifier other than thread_local.
10457 //
10458 // We diagnose friend declarations with storage-class-specifiers
10459 // elsewhere.
10460 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10462 diag::ext_explicit_specialization_storage_class)
10465 }
10466
10467 if (SC == SC_Static && !CurContext->isRecord() && DC->isRecord()) {
10468 assert(isa<CXXMethodDecl>(NewFD) &&
10469 "Out-of-line member function should be a CXXMethodDecl");
10470 // C++ [class.static]p1:
10471 // A data or function member of a class may be declared static
10472 // in a class definition, in which case it is a static member of
10473 // the class.
10474
10475 // Complain about the 'static' specifier if it's on an out-of-line
10476 // member function definition.
10477
10478 // MSVC permits the use of a 'static' storage specifier on an
10479 // out-of-line member function template declaration and class member
10480 // template declaration (MSVC versions before 2015), warn about this.
10482 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
10483 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
10484 (getLangOpts().MSVCCompat &&
10486 ? diag::ext_static_out_of_line
10487 : diag::err_static_out_of_line)
10490 }
10491 }
10492
10493 // C++11 [except.spec]p15:
10494 // A deallocation function with no exception-specification is treated
10495 // as if it were specified with noexcept(true).
10496 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10497 if (Name.isAnyOperatorDelete() && getLangOpts().CPlusPlus11 && FPT &&
10498 !FPT->hasExceptionSpec())
10499 NewFD->setType(Context.getFunctionType(
10500 FPT->getReturnType(), FPT->getParamTypes(),
10502
10503 // C++20 [dcl.inline]/7
10504 // If an inline function or variable that is attached to a named module
10505 // is declared in a definition domain, it shall be defined in that
10506 // domain.
10507 // So, if the current declaration does not have a definition, we must
10508 // check at the end of the TU (or when the PMF starts) to see that we
10509 // have a definition at that point.
10510 if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
10511 NewFD->isInNamedModule()) {
10512 PendingInlineFuncDecls.insert(NewFD);
10513 }
10514 }
10515
10516 // Filter out previous declarations that don't match the scope.
10519 isMemberSpecialization ||
10520 isFunctionTemplateSpecialization);
10521
10522 // Handle GNU asm-label extension (encoded as an attribute).
10523 if (Expr *E = D.getAsmLabel()) {
10524 // The parser guarantees this is a string.
10526 NewFD->addAttr(
10527 AsmLabelAttr::Create(Context, SE->getString(), SE->getStrTokenLoc(0)));
10528 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10529 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
10531 if (I != ExtnameUndeclaredIdentifiers.end()) {
10532 if (isDeclExternC(NewFD)) {
10533 NewFD->addAttr(I->second);
10535 } else
10536 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
10537 << /*Variable*/0 << NewFD;
10538 }
10539 }
10540
10541 // Copy the parameter declarations from the declarator D to the function
10542 // declaration NewFD, if they are available. First scavenge them into Params.
10544 unsigned FTIIdx;
10545 if (D.isFunctionDeclarator(FTIIdx)) {
10547
10548 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10549 // function that takes no arguments, not a function that takes a
10550 // single void argument.
10551 // We let through "const void" here because Sema::GetTypeForDeclarator
10552 // already checks for that case.
10553 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10554 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10555 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
10556 assert(Param->getDeclContext() != NewFD && "Was set before ?");
10557 Param->setDeclContext(NewFD);
10558 Params.push_back(Param);
10559
10560 if (Param->isInvalidDecl())
10561 NewFD->setInvalidDecl();
10562 }
10563 }
10564
10565 if (!getLangOpts().CPlusPlus) {
10566 // In C, find all the tag declarations from the prototype and move them
10567 // into the function DeclContext. Remove them from the surrounding tag
10568 // injection context of the function, which is typically but not always
10569 // the TU.
10570 DeclContext *PrototypeTagContext =
10572 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10573 auto *TD = dyn_cast<TagDecl>(NonParmDecl);
10574
10575 // We don't want to reparent enumerators. Look at their parent enum
10576 // instead.
10577 if (!TD) {
10578 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
10579 TD = cast<EnumDecl>(ECD->getDeclContext());
10580 }
10581 if (!TD)
10582 continue;
10583 DeclContext *TagDC = TD->getLexicalDeclContext();
10584 if (!TagDC->containsDecl(TD))
10585 continue;
10586 TagDC->removeDecl(TD);
10587 TD->setDeclContext(NewFD);
10588 NewFD->addDecl(TD);
10589
10590 // Preserve the lexical DeclContext if it is not the surrounding tag
10591 // injection context of the FD. In this example, the semantic context of
10592 // E will be f and the lexical context will be S, while both the
10593 // semantic and lexical contexts of S will be f:
10594 // void f(struct S { enum E { a } f; } s);
10595 if (TagDC != PrototypeTagContext)
10596 TD->setLexicalDeclContext(TagDC);
10597 }
10598 }
10599 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10600 // When we're declaring a function with a typedef, typeof, etc as in the
10601 // following example, we'll need to synthesize (unnamed)
10602 // parameters for use in the declaration.
10603 //
10604 // @code
10605 // typedef void fn(int);
10606 // fn f;
10607 // @endcode
10608
10609 // Synthesize a parameter for each argument type.
10610 for (const auto &AI : FT->param_types()) {
10611 ParmVarDecl *Param =
10613 Param->setScopeInfo(0, Params.size());
10614 Params.push_back(Param);
10615 }
10616 } else {
10617 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10618 "Should not need args for typedef of non-prototype fn");
10619 }
10620
10621 // Finally, we know we have the right number of parameters, install them.
10622 NewFD->setParams(Params);
10623
10624 // If this declarator is a declaration and not a definition, its parameters
10625 // will not be pushed onto a scope chain. That means we will not issue any
10626 // reserved identifier warnings for the declaration, but we will for the
10627 // definition. Handle those here.
10628 if (!D.isFunctionDefinition()) {
10629 for (const ParmVarDecl *PVD : Params)
10631 }
10632
10634 NewFD->addAttr(
10635 C11NoReturnAttr::Create(Context, D.getDeclSpec().getNoreturnSpecLoc()));
10636
10637 // Functions returning a variably modified type violate C99 6.7.5.2p2
10638 // because all functions have linkage.
10639 if (!NewFD->isInvalidDecl() &&
10641 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
10642 NewFD->setInvalidDecl();
10643 }
10644
10645 // Apply an implicit SectionAttr if '#pragma clang section text' is active
10647 !NewFD->hasAttr<SectionAttr>())
10648 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
10649 Context, PragmaClangTextSection.SectionName,
10650 PragmaClangTextSection.PragmaLocation));
10651
10652 // Apply an implicit SectionAttr if #pragma code_seg is active.
10653 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10654 !NewFD->hasAttr<SectionAttr>()) {
10655 NewFD->addAttr(SectionAttr::CreateImplicit(
10656 Context, CodeSegStack.CurrentValue->getString(),
10657 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate));
10658 if (UnifySection(CodeSegStack.CurrentValue->getString(),
10661 NewFD))
10662 NewFD->dropAttr<SectionAttr>();
10663 }
10664
10665 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10666 // active.
10667 if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() &&
10668 !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10669 NewFD->addAttr(StrictGuardStackCheckAttr::CreateImplicit(
10670 Context, PragmaClangTextSection.PragmaLocation));
10671
10672 // Apply an implicit CodeSegAttr from class declspec or
10673 // apply an implicit SectionAttr from #pragma code_seg if active.
10674 if (!NewFD->hasAttr<CodeSegAttr>()) {
10676 D.isFunctionDefinition())) {
10677 NewFD->addAttr(SAttr);
10678 }
10679 }
10680
10681 // Handle attributes.
10682 ProcessDeclAttributes(S, NewFD, D);
10683 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10684 if (Context.getTargetInfo().getTriple().isAArch64() && NewTVA &&
10685 !NewTVA->isDefaultVersion() &&
10686 !Context.getTargetInfo().hasFeature("fmv")) {
10687 // Don't add to scope fmv functions declarations if fmv disabled
10688 AddToScope = false;
10689 return NewFD;
10690 }
10691
10692 if (getLangOpts().OpenCL || getLangOpts().HLSL) {
10693 // Neither OpenCL nor HLSL allow an address space qualifyer on a return
10694 // type.
10695 //
10696 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10697 // type declaration will generate a compilation error.
10698 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10699 if (AddressSpace != LangAS::Default) {
10700 Diag(NewFD->getLocation(), diag::err_return_value_with_address_space);
10701 NewFD->setInvalidDecl();
10702 }
10703 }
10704
10705 if (!getLangOpts().CPlusPlus) {
10706 // Perform semantic checking on the function declaration.
10707 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10708 CheckMain(NewFD, D.getDeclSpec());
10709
10710 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10711 CheckMSVCRTEntryPoint(NewFD);
10712
10713 if (!NewFD->isInvalidDecl())
10715 isMemberSpecialization,
10717 else if (!Previous.empty())
10718 // Recover gracefully from an invalid redeclaration.
10719 D.setRedeclaration(true);
10720 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10721 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
10722 "previous declaration set still overloaded");
10723
10724 // Diagnose no-prototype function declarations with calling conventions that
10725 // don't support variadic calls. Only do this in C and do it after merging
10726 // possibly prototyped redeclarations.
10727 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10729 CallingConv CC = FT->getExtInfo().getCC();
10730 if (!supportsVariadicCall(CC)) {
10731 // Windows system headers sometimes accidentally use stdcall without
10732 // (void) parameters, so we relax this to a warning.
10733 int DiagID =
10734 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10735 Diag(NewFD->getLocation(), DiagID)
10737 }
10738 }
10739
10743 NewFD->getReturnType(), NewFD->getReturnTypeSourceRange().getBegin(),
10745 } else {
10746 // C++11 [replacement.functions]p3:
10747 // The program's definitions shall not be specified as inline.
10748 //
10749 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10750 //
10751 // Suppress the diagnostic if the function is __attribute__((used)), since
10752 // that forces an external definition to be emitted.
10753 if (D.getDeclSpec().isInlineSpecified() &&
10755 !NewFD->hasAttr<UsedAttr>())
10757 diag::ext_operator_new_delete_declared_inline)
10758 << NewFD->getDeclName();
10759
10760 if (const Expr *TRC = NewFD->getTrailingRequiresClause().ConstraintExpr) {
10761 // C++20 [dcl.decl.general]p4:
10762 // The optional requires-clause in an init-declarator or
10763 // member-declarator shall be present only if the declarator declares a
10764 // templated function.
10765 //
10766 // C++20 [temp.pre]p8:
10767 // An entity is templated if it is
10768 // - a template,
10769 // - an entity defined or created in a templated entity,
10770 // - a member of a templated entity,
10771 // - an enumerator for an enumeration that is a templated entity, or
10772 // - the closure type of a lambda-expression appearing in the
10773 // declaration of a templated entity.
10774 //
10775 // [Note 6: A local class, a local or block variable, or a friend
10776 // function defined in a templated entity is a templated entity.
10777 // — end note]
10778 //
10779 // A templated function is a function template or a function that is
10780 // templated. A templated class is a class template or a class that is
10781 // templated. A templated variable is a variable template or a variable
10782 // that is templated.
10783 if (!FunctionTemplate) {
10784 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10785 // C++ [temp.expl.spec]p8 (proposed resolution for CWG2847):
10786 // An explicit specialization shall not have a trailing
10787 // requires-clause unless it declares a function template.
10788 //
10789 // Since a friend function template specialization cannot be
10790 // definition, and since a non-template friend declaration with a
10791 // trailing requires-clause must be a definition, we diagnose
10792 // friend function template specializations with trailing
10793 // requires-clauses on the same path as explicit specializations
10794 // even though they aren't necessarily prohibited by the same
10795 // language rule.
10796 Diag(TRC->getBeginLoc(), diag::err_non_temp_spec_requires_clause)
10797 << isFriend;
10798 } else if (isFriend && NewFD->isTemplated() &&
10799 !D.isFunctionDefinition()) {
10800 // C++ [temp.friend]p9:
10801 // A non-template friend declaration with a requires-clause shall be
10802 // a definition.
10803 Diag(NewFD->getBeginLoc(),
10804 diag::err_non_temp_friend_decl_with_requires_clause_must_be_def);
10805 NewFD->setInvalidDecl();
10806 } else if (!NewFD->isTemplated() ||
10807 !(isa<CXXMethodDecl>(NewFD) || D.isFunctionDefinition())) {
10808 Diag(TRC->getBeginLoc(),
10809 diag::err_constrained_non_templated_function);
10810 }
10811 }
10812 }
10813
10814 // We do not add HD attributes to specializations here because
10815 // they may have different constexpr-ness compared to their
10816 // templates and, after maybeAddHostDeviceAttrs() is applied,
10817 // may end up with different effective targets. Instead, a
10818 // specialization inherits its target attributes from its template
10819 // in the CheckFunctionTemplateSpecialization() call below.
10820 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
10822
10823 // Handle explicit specializations of function templates
10824 // and friend function declarations with an explicit
10825 // template argument list.
10826 if (isFunctionTemplateSpecialization) {
10827 bool isDependentSpecialization = false;
10828 if (isFriend) {
10829 // For friend function specializations, this is a dependent
10830 // specialization if its semantic context is dependent, its
10831 // type is dependent, or if its template-id is dependent.
10832 isDependentSpecialization =
10833 DC->isDependentContext() || NewFD->getType()->isDependentType() ||
10834 (HasExplicitTemplateArgs &&
10835 TemplateSpecializationType::
10836 anyInstantiationDependentTemplateArguments(
10837 TemplateArgs.arguments()));
10838 assert((!isDependentSpecialization ||
10839 (HasExplicitTemplateArgs == isDependentSpecialization)) &&
10840 "dependent friend function specialization without template "
10841 "args");
10842 } else {
10843 // For class-scope explicit specializations of function templates,
10844 // if the lexical context is dependent, then the specialization
10845 // is dependent.
10846 isDependentSpecialization =
10847 CurContext->isRecord() && CurContext->isDependentContext();
10848 }
10849
10850 TemplateArgumentListInfo *ExplicitTemplateArgs =
10851 HasExplicitTemplateArgs ? &TemplateArgs : nullptr;
10852 if (isDependentSpecialization) {
10853 // If it's a dependent specialization, it may not be possible
10854 // to determine the primary template (for explicit specializations)
10855 // or befriended declaration (for friends) until the enclosing
10856 // template is instantiated. In such cases, we store the declarations
10857 // found by name lookup and defer resolution until instantiation.
10859 NewFD, ExplicitTemplateArgs, Previous))
10860 NewFD->setInvalidDecl();
10861 } else if (!NewFD->isInvalidDecl()) {
10862 if (CheckFunctionTemplateSpecialization(NewFD, ExplicitTemplateArgs,
10863 Previous))
10864 NewFD->setInvalidDecl();
10865 }
10866 } else if (isMemberSpecialization && !FunctionTemplate) {
10868 NewFD->setInvalidDecl();
10869 }
10870
10871 // Perform semantic checking on the function declaration.
10872 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10873 CheckMain(NewFD, D.getDeclSpec());
10874
10875 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10876 CheckMSVCRTEntryPoint(NewFD);
10877
10878 if (!NewFD->isInvalidDecl())
10880 isMemberSpecialization,
10882 else if (!Previous.empty())
10883 // Recover gracefully from an invalid redeclaration.
10884 D.setRedeclaration(true);
10885
10886 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
10887 !D.isRedeclaration() ||
10888 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
10889 "previous declaration set still overloaded");
10890
10891 NamedDecl *PrincipalDecl = (FunctionTemplate
10893 : NewFD);
10894
10895 if (isFriend && NewFD->getPreviousDecl()) {
10896 AccessSpecifier Access = AS_public;
10897 if (!NewFD->isInvalidDecl())
10898 Access = NewFD->getPreviousDecl()->getAccess();
10899
10900 NewFD->setAccess(Access);
10901 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10902 }
10903
10904 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10906 PrincipalDecl->setNonMemberOperator();
10907
10908 // If we have a function template, check the template parameter
10909 // list. This will check and merge default template arguments.
10910 if (FunctionTemplate) {
10911 FunctionTemplateDecl *PrevTemplate =
10912 FunctionTemplate->getPreviousDecl();
10913 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
10914 PrevTemplate ? PrevTemplate->getTemplateParameters()
10915 : nullptr,
10920 : (D.getCXXScopeSpec().isSet() &&
10921 DC && DC->isRecord() &&
10922 DC->isDependentContext())
10925 }
10926
10927 if (NewFD->isInvalidDecl()) {
10928 // Ignore all the rest of this.
10929 } else if (!D.isRedeclaration()) {
10930 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
10931 AddToScope };
10932 // Fake up an access specifier if it's supposed to be a class member.
10933 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10934 NewFD->setAccess(AS_public);
10935
10936 // Qualified decls generally require a previous declaration.
10937 if (D.getCXXScopeSpec().isSet()) {
10938 // ...with the major exception of templated-scope or
10939 // dependent-scope friend declarations.
10940
10941 // TODO: we currently also suppress this check in dependent
10942 // contexts because (1) the parameter depth will be off when
10943 // matching friend templates and (2) we might actually be
10944 // selecting a friend based on a dependent factor. But there
10945 // are situations where these conditions don't apply and we
10946 // can actually do this check immediately.
10947 //
10948 // Unless the scope is dependent, it's always an error if qualified
10949 // redeclaration lookup found nothing at all. Diagnose that now;
10950 // nothing will diagnose that error later.
10951 if (isFriend &&
10953 (!Previous.empty() && CurContext->isDependentContext()))) {
10954 // ignore these
10955 } else if (NewFD->isCPUDispatchMultiVersion() ||
10956 NewFD->isCPUSpecificMultiVersion()) {
10957 // ignore this, we allow the redeclaration behavior here to create new
10958 // versions of the function.
10959 } else {
10960 // The user tried to provide an out-of-line definition for a
10961 // function that is a member of a class or namespace, but there
10962 // was no such member function declared (C++ [class.mfct]p2,
10963 // C++ [namespace.memdef]p2). For example:
10964 //
10965 // class X {
10966 // void f() const;
10967 // };
10968 //
10969 // void X::f() { } // ill-formed
10970 //
10971 // Complain about this problem, and attempt to suggest close
10972 // matches (e.g., those that differ only in cv-qualifiers and
10973 // whether the parameter types are references).
10974
10976 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
10977 AddToScope = ExtraArgs.AddToScope;
10978 return Result;
10979 }
10980 }
10981
10982 // Unqualified local friend declarations are required to resolve
10983 // to something.
10984 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
10986 *this, Previous, NewFD, ExtraArgs, true, S)) {
10987 AddToScope = ExtraArgs.AddToScope;
10988 return Result;
10989 }
10990 }
10991 } else if (!D.isFunctionDefinition() &&
10992 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
10993 !isFriend && !isFunctionTemplateSpecialization &&
10994 !isMemberSpecialization) {
10995 // An out-of-line member function declaration must also be a
10996 // definition (C++ [class.mfct]p2).
10997 // Note that this is not the case for explicit specializations of
10998 // function templates or member functions of class templates, per
10999 // C++ [temp.expl.spec]p2. We also allow these declarations as an
11000 // extension for compatibility with old SWIG code which likes to
11001 // generate them.
11002 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
11003 << D.getCXXScopeSpec().getRange();
11004 }
11005 }
11006
11007 if (getLangOpts().HLSL && D.isFunctionDefinition()) {
11008 // Any top level function could potentially be specified as an entry.
11009 if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier())
11010 HLSL().ActOnTopLevelFunction(NewFD);
11011
11012 if (NewFD->hasAttr<HLSLShaderAttr>())
11013 HLSL().CheckEntryPoint(NewFD);
11014 }
11015
11016 // If this is the first declaration of a library builtin function, add
11017 // attributes as appropriate.
11018 if (!D.isRedeclaration()) {
11019 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
11020 if (unsigned BuiltinID = II->getBuiltinID()) {
11021 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);
11022 if (!InStdNamespace &&
11024 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
11025 // Validate the type matches unless this builtin is specified as
11026 // matching regardless of its declared type.
11027 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
11028 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
11029 } else {
11031 LookupNecessaryTypesForBuiltin(S, BuiltinID);
11032 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
11033
11034 if (!Error && !BuiltinType.isNull() &&
11035 Context.hasSameFunctionTypeIgnoringExceptionSpec(
11036 NewFD->getType(), BuiltinType))
11037 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
11038 }
11039 }
11040 } else if (InStdNamespace && NewFD->isInStdNamespace() &&
11041 isStdBuiltin(Context, NewFD, BuiltinID)) {
11042 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
11043 }
11044 }
11045 }
11046 }
11047
11048 ProcessPragmaWeak(S, NewFD);
11049 ProcessPragmaExport(NewFD);
11050 checkAttributesAfterMerging(*this, *NewFD);
11051
11053
11054 if (NewFD->hasAttr<OverloadableAttr>() &&
11055 !NewFD->getType()->getAs<FunctionProtoType>()) {
11056 Diag(NewFD->getLocation(),
11057 diag::err_attribute_overloadable_no_prototype)
11058 << NewFD;
11059 NewFD->dropAttr<OverloadableAttr>();
11060 }
11061
11062 // If there's a #pragma GCC visibility in scope, and this isn't a class
11063 // member, set the visibility of this function.
11064 if (!DC->isRecord() && NewFD->isExternallyVisible())
11066
11067 // If there's a #pragma clang arc_cf_code_audited in scope, consider
11068 // marking the function.
11069 ObjC().AddCFAuditedAttribute(NewFD);
11070
11071 // If this is a function definition, check if we have to apply any
11072 // attributes (i.e. optnone and no_builtin) due to a pragma.
11073 if (D.isFunctionDefinition()) {
11074 AddRangeBasedOptnone(NewFD);
11076 AddSectionMSAllocText(NewFD);
11078 }
11079
11080 // If this is the first declaration of an extern C variable, update
11081 // the map of such variables.
11082 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
11083 isIncompleteDeclExternC(*this, NewFD))
11085
11086 // Set this FunctionDecl's range up to the right paren.
11087 NewFD->setRangeEnd(D.getSourceRange().getEnd());
11088
11089 if (D.isRedeclaration() && !Previous.empty()) {
11090 NamedDecl *Prev = Previous.getRepresentativeDecl();
11091 checkDLLAttributeRedeclaration(*this, Prev, NewFD,
11092 isMemberSpecialization ||
11093 isFunctionTemplateSpecialization,
11095 }
11096
11097 if (getLangOpts().CUDA) {
11098 if (IdentifierInfo *II = NewFD->getIdentifier()) {
11099 if (II->isStr(CUDA().getConfigureFuncName()) && !NewFD->isInvalidDecl() &&
11102 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
11104 Context.setcudaConfigureCallDecl(NewFD);
11105 }
11106 if (II->isStr(CUDA().getGetParameterBufferFuncName()) &&
11107 !NewFD->isInvalidDecl() &&
11110 Diag(NewFD->getLocation(), diag::err_config_pointer_return)
11112 Context.setcudaGetParameterBufferDecl(NewFD);
11113 }
11114 if (II->isStr(CUDA().getLaunchDeviceFuncName()) &&
11115 !NewFD->isInvalidDecl() &&
11118 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
11120 Context.setcudaLaunchDeviceDecl(NewFD);
11121 }
11122 }
11123 }
11124
11126
11127 if (getLangOpts().OpenCL && NewFD->hasAttr<DeviceKernelAttr>()) {
11128 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
11129 if (SC == SC_Static) {
11130 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
11131 D.setInvalidType();
11132 }
11133
11134 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
11135 if (!NewFD->getReturnType()->isVoidType()) {
11136 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
11137 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
11138 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
11139 : FixItHint());
11140 D.setInvalidType();
11141 }
11142
11144 for (auto *Param : NewFD->parameters())
11145 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
11146
11147 if (getLangOpts().OpenCLCPlusPlus) {
11148 if (DC->isRecord()) {
11149 Diag(D.getIdentifierLoc(), diag::err_method_kernel);
11150 D.setInvalidType();
11151 }
11152 if (FunctionTemplate) {
11153 Diag(D.getIdentifierLoc(), diag::err_template_kernel);
11154 D.setInvalidType();
11155 }
11156 }
11157 }
11158
11159 if (getLangOpts().CPlusPlus) {
11160 // Precalculate whether this is a friend function template with a constraint
11161 // that depends on an enclosing template, per [temp.friend]p9.
11162 if (isFriend && FunctionTemplate &&
11165
11166 // C++ [temp.friend]p9:
11167 // A friend function template with a constraint that depends on a
11168 // template parameter from an enclosing template shall be a definition.
11169 if (!D.isFunctionDefinition()) {
11170 Diag(NewFD->getBeginLoc(),
11171 diag::err_friend_decl_with_enclosing_temp_constraint_must_be_def);
11172 NewFD->setInvalidDecl();
11173 }
11174 }
11175
11176 if (FunctionTemplate) {
11177 if (NewFD->isInvalidDecl())
11178 FunctionTemplate->setInvalidDecl();
11179 return FunctionTemplate;
11180 }
11181
11182 if (isMemberSpecialization && !NewFD->isInvalidDecl())
11184 }
11185
11186 for (const ParmVarDecl *Param : NewFD->parameters()) {
11187 QualType PT = Param->getType();
11188
11189 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
11190 // types.
11191 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
11192 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
11193 QualType ElemTy = PipeTy->getElementType();
11194 if (ElemTy->isPointerOrReferenceType()) {
11195 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type);
11196 D.setInvalidType();
11197 }
11198 }
11199 }
11200 // WebAssembly tables can't be used as function parameters.
11201 if (Context.getTargetInfo().getTriple().isWasm()) {
11203 Diag(Param->getTypeSpecStartLoc(),
11204 diag::err_wasm_table_as_function_parameter);
11205 D.setInvalidType();
11206 }
11207 }
11208 }
11209
11210 // Diagnose availability attributes. Availability cannot be used on functions
11211 // that are run during load/unload.
11212 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
11213 if (NewFD->hasAttr<ConstructorAttr>()) {
11214 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
11215 << 1;
11216 NewFD->dropAttr<AvailabilityAttr>();
11217 }
11218 if (NewFD->hasAttr<DestructorAttr>()) {
11219 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
11220 << 2;
11221 NewFD->dropAttr<AvailabilityAttr>();
11222 }
11223 }
11224
11225 // Diagnose no_builtin attribute on function declaration that are not a
11226 // definition.
11227 // FIXME: We should really be doing this in
11228 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
11229 // the FunctionDecl and at this point of the code
11230 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
11231 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11232 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
11233 switch (D.getFunctionDefinitionKind()) {
11236 Diag(NBA->getLocation(),
11237 diag::err_attribute_no_builtin_on_defaulted_deleted_function)
11238 << NBA->getSpelling();
11239 break;
11241 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
11242 << NBA->getSpelling();
11243 break;
11245 break;
11246 }
11247
11248 // Similar to no_builtin logic above, at this point of the code
11249 // FunctionDecl::isThisDeclarationADefinition() always returns `false`
11250 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11251 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
11252 !NewFD->isInvalidDecl() &&
11254 ExternalDeclarations.push_back(NewFD);
11255
11256 // Used for a warning on the 'next' declaration when used with a
11257 // `routine(name)`.
11258 if (getLangOpts().OpenACC)
11260
11261 return NewFD;
11262}
11263
11264/// Return a CodeSegAttr from a containing class. The Microsoft docs say
11265/// when __declspec(code_seg) "is applied to a class, all member functions of
11266/// the class and nested classes -- this includes compiler-generated special
11267/// member functions -- are put in the specified segment."
11268/// The actual behavior is a little more complicated. The Microsoft compiler
11269/// won't check outer classes if there is an active value from #pragma code_seg.
11270/// The CodeSeg is always applied from the direct parent but only from outer
11271/// classes when the #pragma code_seg stack is empty. See:
11272/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
11273/// available since MS has removed the page.
11275 const auto *Method = dyn_cast<CXXMethodDecl>(FD);
11276 if (!Method)
11277 return nullptr;
11278 const CXXRecordDecl *Parent = Method->getParent();
11279 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11280 Attr *NewAttr = SAttr->clone(S.getASTContext());
11281 NewAttr->setImplicit(true);
11282 return NewAttr;
11283 }
11284
11285 // The Microsoft compiler won't check outer classes for the CodeSeg
11286 // when the #pragma code_seg stack is active.
11287 if (S.CodeSegStack.CurrentValue)
11288 return nullptr;
11289
11290 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
11291 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11292 Attr *NewAttr = SAttr->clone(S.getASTContext());
11293 NewAttr->setImplicit(true);
11294 return NewAttr;
11295 }
11296 }
11297 return nullptr;
11298}
11299
11301 bool IsDefinition) {
11302 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
11303 return A;
11304 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
11305 CodeSegStack.CurrentValue)
11306 return SectionAttr::CreateImplicit(
11307 getASTContext(), CodeSegStack.CurrentValue->getString(),
11308 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate);
11309 return nullptr;
11310}
11311
11313 QualType NewT, QualType OldT) {
11315 return true;
11316
11317 // For dependently-typed local extern declarations and friends, we can't
11318 // perform a correct type check in general until instantiation:
11319 //
11320 // int f();
11321 // template<typename T> void g() { T f(); }
11322 //
11323 // (valid if g() is only instantiated with T = int).
11324 if (NewT->isDependentType() &&
11325 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
11326 return false;
11327
11328 // Similarly, if the previous declaration was a dependent local extern
11329 // declaration, we don't really know its type yet.
11330 if (OldT->isDependentType() && OldD->isLocalExternDecl())
11331 return false;
11332
11333 return true;
11334}
11335
11338 return true;
11339
11340 // Don't chain dependent friend function definitions until instantiation, to
11341 // permit cases like
11342 //
11343 // void func();
11344 // template<typename T> class C1 { friend void func() {} };
11345 // template<typename T> class C2 { friend void func() {} };
11346 //
11347 // ... which is valid if only one of C1 and C2 is ever instantiated.
11348 //
11349 // FIXME: This need only apply to function definitions. For now, we proxy
11350 // this by checking for a file-scope function. We do not want this to apply
11351 // to friend declarations nominating member functions, because that gets in
11352 // the way of access checks.
11354 return false;
11355
11356 auto *VD = dyn_cast<ValueDecl>(D);
11357 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
11358 return !VD || !PrevVD ||
11359 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
11360 PrevVD->getType());
11361}
11362
11363/// Check the target or target_version attribute of the function for
11364/// MultiVersion validity.
11365///
11366/// Returns true if there was an error, false otherwise.
11367static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
11368 const auto *TA = FD->getAttr<TargetAttr>();
11369 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11370
11371 assert((TA || TVA) && "Expecting target or target_version attribute");
11372
11374 enum ErrType { Feature = 0, Architecture = 1 };
11375
11376 if (TA) {
11377 ParsedTargetAttr ParseInfo =
11378 S.getASTContext().getTargetInfo().parseTargetAttr(TA->getFeaturesStr());
11379 if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(ParseInfo.CPU)) {
11380 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11381 << Architecture << ParseInfo.CPU;
11382 return true;
11383 }
11384 for (const auto &Feat : ParseInfo.Features) {
11385 auto BareFeat = StringRef{Feat}.substr(1);
11386 if (Feat[0] == '-') {
11387 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11388 << Feature << ("no-" + BareFeat).str();
11389 return true;
11390 }
11391
11392 if (!TargetInfo.validateCpuSupports(BareFeat) ||
11393 !TargetInfo.isValidFeatureName(BareFeat) ||
11394 (BareFeat != "default" && TargetInfo.getFMVPriority(BareFeat) == 0)) {
11395 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11396 << Feature << BareFeat;
11397 return true;
11398 }
11399 }
11400 }
11401
11402 if (TVA) {
11404 ParsedTargetAttr ParseInfo;
11405 if (S.getASTContext().getTargetInfo().getTriple().isRISCV()) {
11406 ParseInfo =
11407 S.getASTContext().getTargetInfo().parseTargetAttr(TVA->getName());
11408 for (auto &Feat : ParseInfo.Features)
11409 Feats.push_back(StringRef{Feat}.substr(1));
11410 } else {
11411 assert(S.getASTContext().getTargetInfo().getTriple().isAArch64());
11412 TVA->getFeatures(Feats);
11413 }
11414 for (const auto &Feat : Feats) {
11415 if (!TargetInfo.validateCpuSupports(Feat)) {
11416 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11417 << Feature << Feat;
11418 return true;
11419 }
11420 }
11421 }
11422 return false;
11423}
11424
11425// Provide a white-list of attributes that are allowed to be combined with
11426// multiversion functions.
11428 MultiVersionKind MVKind) {
11429 // Note: this list/diagnosis must match the list in
11430 // checkMultiversionAttributesAllSame.
11431 switch (Kind) {
11432 default:
11433 return false;
11434 case attr::ArmLocallyStreaming:
11435 return MVKind == MultiVersionKind::TargetVersion ||
11437 case attr::Used:
11438 return MVKind == MultiVersionKind::Target;
11439 case attr::NonNull:
11440 case attr::NoThrow:
11441 return true;
11442 }
11443}
11444
11446 const FunctionDecl *FD,
11447 const FunctionDecl *CausedFD,
11448 MultiVersionKind MVKind) {
11449 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
11450 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
11451 << static_cast<unsigned>(MVKind) << A;
11452 if (CausedFD)
11453 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
11454 return true;
11455 };
11456
11457 for (const Attr *A : FD->attrs()) {
11458 switch (A->getKind()) {
11459 case attr::CPUDispatch:
11460 case attr::CPUSpecific:
11461 if (MVKind != MultiVersionKind::CPUDispatch &&
11463 return Diagnose(S, A);
11464 break;
11465 case attr::Target:
11466 if (MVKind != MultiVersionKind::Target)
11467 return Diagnose(S, A);
11468 break;
11469 case attr::TargetVersion:
11470 if (MVKind != MultiVersionKind::TargetVersion &&
11472 return Diagnose(S, A);
11473 break;
11474 case attr::TargetClones:
11475 if (MVKind != MultiVersionKind::TargetClones &&
11477 return Diagnose(S, A);
11478 break;
11479 default:
11480 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
11481 return Diagnose(S, A);
11482 break;
11483 }
11484 }
11485 return false;
11486}
11487
11489 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11490 const PartialDiagnostic &NoProtoDiagID,
11491 const PartialDiagnosticAt &NoteCausedDiagIDAt,
11492 const PartialDiagnosticAt &NoSupportDiagIDAt,
11493 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11494 bool ConstexprSupported, bool CLinkageMayDiffer) {
11495 enum DoesntSupport {
11496 FuncTemplates = 0,
11497 VirtFuncs = 1,
11498 DeducedReturn = 2,
11499 Constructors = 3,
11500 Destructors = 4,
11501 DeletedFuncs = 5,
11502 DefaultedFuncs = 6,
11503 ConstexprFuncs = 7,
11504 ConstevalFuncs = 8,
11505 Lambda = 9,
11506 };
11507 enum Different {
11508 CallingConv = 0,
11509 ReturnType = 1,
11510 ConstexprSpec = 2,
11511 InlineSpec = 3,
11512 Linkage = 4,
11513 LanguageLinkage = 5,
11514 };
11515
11516 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
11517 !OldFD->getType()->getAs<FunctionProtoType>()) {
11518 Diag(OldFD->getLocation(), NoProtoDiagID);
11519 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
11520 return true;
11521 }
11522
11523 if (NoProtoDiagID.getDiagID() != 0 &&
11524 !NewFD->getType()->getAs<FunctionProtoType>())
11525 return Diag(NewFD->getLocation(), NoProtoDiagID);
11526
11527 if (!TemplatesSupported &&
11529 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11530 << FuncTemplates;
11531
11532 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
11533 if (NewCXXFD->isVirtual())
11534 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11535 << VirtFuncs;
11536
11537 if (isa<CXXConstructorDecl>(NewCXXFD))
11538 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11539 << Constructors;
11540
11541 if (isa<CXXDestructorDecl>(NewCXXFD))
11542 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11543 << Destructors;
11544 }
11545
11546 if (NewFD->isDeleted())
11547 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11548 << DeletedFuncs;
11549
11550 if (NewFD->isDefaulted())
11551 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11552 << DefaultedFuncs;
11553
11554 if (!ConstexprSupported && NewFD->isConstexpr())
11555 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11556 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11557
11558 QualType NewQType = Context.getCanonicalType(NewFD->getType());
11559 const auto *NewType = cast<FunctionType>(NewQType);
11560 QualType NewReturnType = NewType->getReturnType();
11561
11562 if (NewReturnType->isUndeducedType())
11563 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11564 << DeducedReturn;
11565
11566 // Ensure the return type is identical.
11567 if (OldFD) {
11568 QualType OldQType = Context.getCanonicalType(OldFD->getType());
11569 const auto *OldType = cast<FunctionType>(OldQType);
11570 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11571 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11572
11573 const auto *OldFPT = OldFD->getType()->getAs<FunctionProtoType>();
11574 const auto *NewFPT = NewFD->getType()->getAs<FunctionProtoType>();
11575
11576 bool ArmStreamingCCMismatched = false;
11577 if (OldFPT && NewFPT) {
11578 unsigned Diff =
11579 OldFPT->getAArch64SMEAttributes() ^ NewFPT->getAArch64SMEAttributes();
11580 // Arm-streaming, arm-streaming-compatible and non-streaming versions
11581 // cannot be mixed.
11584 ArmStreamingCCMismatched = true;
11585 }
11586
11587 if (OldTypeInfo.getCC() != NewTypeInfo.getCC() || ArmStreamingCCMismatched)
11588 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
11589
11590 QualType OldReturnType = OldType->getReturnType();
11591
11592 if (OldReturnType != NewReturnType)
11593 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
11594
11595 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11596 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
11597
11598 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11599 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
11600
11601 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11602 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
11603
11604 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11605 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
11606
11607 if (CheckEquivalentExceptionSpec(OldFPT, OldFD->getLocation(), NewFPT,
11608 NewFD->getLocation()))
11609 return true;
11610 }
11611 return false;
11612}
11613
11615 const FunctionDecl *NewFD,
11616 bool CausesMV,
11617 MultiVersionKind MVKind) {
11619 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
11620 if (OldFD)
11621 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11622 return true;
11623 }
11624
11625 bool IsCPUSpecificCPUDispatchMVKind =
11628
11629 if (CausesMV && OldFD &&
11630 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
11631 return true;
11632
11633 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
11634 return true;
11635
11636 // Only allow transition to MultiVersion if it hasn't been used.
11637 if (OldFD && CausesMV && OldFD->isUsed(false)) {
11638 S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11639 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11640 return true;
11641 }
11642
11644 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
11646 S.PDiag(diag::note_multiversioning_caused_here)),
11648 S.PDiag(diag::err_multiversion_doesnt_support)
11649 << static_cast<unsigned>(MVKind)),
11651 S.PDiag(diag::err_multiversion_diff)),
11652 /*TemplatesSupported=*/false,
11653 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11654 /*CLinkageMayDiffer=*/false);
11655}
11656
11657/// Check the validity of a multiversion function declaration that is the
11658/// first of its kind. Also sets the multiversion'ness' of the function itself.
11659///
11660/// This sets NewFD->isInvalidDecl() to true if there was an error.
11661///
11662/// Returns true if there was an error, false otherwise.
11665 assert(MVKind != MultiVersionKind::None &&
11666 "Function lacks multiversion attribute");
11667 const auto *TA = FD->getAttr<TargetAttr>();
11668 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11669 // The target attribute only causes MV if this declaration is the default,
11670 // otherwise it is treated as a normal function.
11671 if (TA && !TA->isDefaultVersion())
11672 return false;
11673
11674 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11675 FD->setInvalidDecl();
11676 return true;
11677 }
11678
11679 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
11680 FD->setInvalidDecl();
11681 return true;
11682 }
11683
11684 FD->setIsMultiVersion();
11685 return false;
11686}
11687
11689 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11691 return true;
11692 }
11693
11694 return false;
11695}
11696
11698 if (!From->getASTContext().getTargetInfo().getTriple().isAArch64() &&
11699 !From->getASTContext().getTargetInfo().getTriple().isRISCV())
11700 return;
11701
11702 MultiVersionKind MVKindFrom = From->getMultiVersionKind();
11703 MultiVersionKind MVKindTo = To->getMultiVersionKind();
11704
11705 if (MVKindTo == MultiVersionKind::None &&
11706 (MVKindFrom == MultiVersionKind::TargetVersion ||
11707 MVKindFrom == MultiVersionKind::TargetClones))
11708 To->addAttr(TargetVersionAttr::CreateImplicit(
11709 To->getASTContext(), "default", To->getSourceRange()));
11710}
11711
11713 FunctionDecl *NewFD,
11714 bool &Redeclaration,
11715 NamedDecl *&OldDecl,
11717 assert(!OldFD->isMultiVersion() && "Unexpected MultiVersion");
11718
11719 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11720 const auto *OldTA = OldFD->getAttr<TargetAttr>();
11721 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11722 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11723
11724 assert((NewTA || NewTVA) && "Excpecting target or target_version attribute");
11725
11726 // The definitions should be allowed in any order. If we have discovered
11727 // a new target version and the preceeding was the default, then add the
11728 // corresponding attribute to it.
11729 patchDefaultTargetVersion(NewFD, OldFD);
11730
11731 // If the old decl is NOT MultiVersioned yet, and we don't cause that
11732 // to change, this is a simple redeclaration.
11733 if (NewTA && !NewTA->isDefaultVersion() &&
11734 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
11735 return false;
11736
11737 // Otherwise, this decl causes MultiVersioning.
11738 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
11741 NewFD->setInvalidDecl();
11742 return true;
11743 }
11744
11745 if (CheckMultiVersionValue(S, NewFD)) {
11746 NewFD->setInvalidDecl();
11747 return true;
11748 }
11749
11750 // If this is 'default', permit the forward declaration.
11751 if ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
11752 (NewTVA && NewTVA->isDefaultVersion() && !OldTVA)) {
11753 Redeclaration = true;
11754 OldDecl = OldFD;
11755 OldFD->setIsMultiVersion();
11756 NewFD->setIsMultiVersion();
11757 return false;
11758 }
11759
11760 if ((OldTA || OldTVA) && CheckMultiVersionValue(S, OldFD)) {
11761 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11762 NewFD->setInvalidDecl();
11763 return true;
11764 }
11765
11766 if (NewTA) {
11767 ParsedTargetAttr OldParsed =
11769 OldTA->getFeaturesStr());
11770 llvm::sort(OldParsed.Features);
11771 ParsedTargetAttr NewParsed =
11773 NewTA->getFeaturesStr());
11774 // Sort order doesn't matter, it just needs to be consistent.
11775 llvm::sort(NewParsed.Features);
11776 if (OldParsed == NewParsed) {
11777 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11778 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11779 NewFD->setInvalidDecl();
11780 return true;
11781 }
11782 }
11783
11784 for (const auto *FD : OldFD->redecls()) {
11785 const auto *CurTA = FD->getAttr<TargetAttr>();
11786 const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
11787 // We allow forward declarations before ANY multiversioning attributes, but
11788 // nothing after the fact.
11790 ((NewTA && (!CurTA || CurTA->isInherited())) ||
11791 (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
11792 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
11793 << (NewTA ? 0 : 2);
11794 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11795 NewFD->setInvalidDecl();
11796 return true;
11797 }
11798 }
11799
11800 OldFD->setIsMultiVersion();
11801 NewFD->setIsMultiVersion();
11802 Redeclaration = false;
11803 OldDecl = nullptr;
11804 Previous.clear();
11805 return false;
11806}
11807
11809 MultiVersionKind OldKind = Old->getMultiVersionKind();
11810 MultiVersionKind NewKind = New->getMultiVersionKind();
11811
11812 if (OldKind == NewKind || OldKind == MultiVersionKind::None ||
11813 NewKind == MultiVersionKind::None)
11814 return true;
11815
11816 if (Old->getASTContext().getTargetInfo().getTriple().isAArch64()) {
11817 switch (OldKind) {
11819 return NewKind == MultiVersionKind::TargetClones;
11821 return NewKind == MultiVersionKind::TargetVersion;
11822 default:
11823 return false;
11824 }
11825 } else {
11826 switch (OldKind) {
11828 return NewKind == MultiVersionKind::CPUSpecific;
11830 return NewKind == MultiVersionKind::CPUDispatch;
11831 default:
11832 return false;
11833 }
11834 }
11835}
11836
11837/// Check the validity of a new function declaration being added to an existing
11838/// multiversioned declaration collection.
11840 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
11841 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
11842 const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
11844
11845 // Disallow mixing of multiversioning types.
11846 if (!MultiVersionTypesCompatible(OldFD, NewFD)) {
11847 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
11848 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11849 NewFD->setInvalidDecl();
11850 return true;
11851 }
11852
11853 // Add the default target_version attribute if it's missing.
11854 patchDefaultTargetVersion(OldFD, NewFD);
11855 patchDefaultTargetVersion(NewFD, OldFD);
11856
11857 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11858 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11859 MultiVersionKind NewMVKind = NewFD->getMultiVersionKind();
11860 [[maybe_unused]] MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
11861
11862 ParsedTargetAttr NewParsed;
11863 if (NewTA) {
11865 NewTA->getFeaturesStr());
11866 llvm::sort(NewParsed.Features);
11867 }
11869 if (NewTVA) {
11870 NewTVA->getFeatures(NewFeats);
11871 llvm::sort(NewFeats);
11872 }
11873
11874 bool UseMemberUsingDeclRules =
11875 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
11876
11877 bool MayNeedOverloadableChecks =
11879
11880 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
11881 // of a previous member of the MultiVersion set.
11882 for (NamedDecl *ND : Previous) {
11883 FunctionDecl *CurFD = ND->getAsFunction();
11884 if (!CurFD || CurFD->isInvalidDecl())
11885 continue;
11886 if (MayNeedOverloadableChecks &&
11887 S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
11888 continue;
11889
11890 switch (NewMVKind) {
11892 assert(OldMVKind == MultiVersionKind::TargetClones &&
11893 "Only target_clones can be omitted in subsequent declarations");
11894 break;
11896 const auto *CurTA = CurFD->getAttr<TargetAttr>();
11897 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
11898 NewFD->setIsMultiVersion();
11899 Redeclaration = true;
11900 OldDecl = ND;
11901 return false;
11902 }
11903
11904 ParsedTargetAttr CurParsed =
11906 CurTA->getFeaturesStr());
11907 llvm::sort(CurParsed.Features);
11908 if (CurParsed == NewParsed) {
11909 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11910 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11911 NewFD->setInvalidDecl();
11912 return true;
11913 }
11914 break;
11915 }
11917 if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11918 if (CurTVA->getName() == NewTVA->getName()) {
11919 NewFD->setIsMultiVersion();
11920 Redeclaration = true;
11921 OldDecl = ND;
11922 return false;
11923 }
11925 CurTVA->getFeatures(CurFeats);
11926 llvm::sort(CurFeats);
11927
11928 if (CurFeats == NewFeats) {
11929 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11930 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11931 NewFD->setInvalidDecl();
11932 return true;
11933 }
11934 } else if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11935 // Default
11936 if (NewFeats.empty())
11937 break;
11938
11939 for (unsigned I = 0; I < CurClones->featuresStrs_size(); ++I) {
11941 CurClones->getFeatures(CurFeats, I);
11942 llvm::sort(CurFeats);
11943
11944 if (CurFeats == NewFeats) {
11945 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11946 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11947 NewFD->setInvalidDecl();
11948 return true;
11949 }
11950 }
11951 }
11952 break;
11953 }
11955 assert(NewClones && "MultiVersionKind does not match attribute type");
11956 if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11957 if (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
11958 !std::equal(CurClones->featuresStrs_begin(),
11959 CurClones->featuresStrs_end(),
11960 NewClones->featuresStrs_begin())) {
11961 S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
11962 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11963 NewFD->setInvalidDecl();
11964 return true;
11965 }
11966 } else if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11968 CurTVA->getFeatures(CurFeats);
11969 llvm::sort(CurFeats);
11970
11971 // Default
11972 if (CurFeats.empty())
11973 break;
11974
11975 for (unsigned I = 0; I < NewClones->featuresStrs_size(); ++I) {
11976 NewFeats.clear();
11977 NewClones->getFeatures(NewFeats, I);
11978 llvm::sort(NewFeats);
11979
11980 if (CurFeats == NewFeats) {
11981 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11982 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11983 NewFD->setInvalidDecl();
11984 return true;
11985 }
11986 }
11987 break;
11988 }
11989 Redeclaration = true;
11990 OldDecl = CurFD;
11991 NewFD->setIsMultiVersion();
11992 return false;
11993 }
11996 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
11997 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
11998 // Handle CPUDispatch/CPUSpecific versions.
11999 // Only 1 CPUDispatch function is allowed, this will make it go through
12000 // the redeclaration errors.
12001 if (NewMVKind == MultiVersionKind::CPUDispatch &&
12002 CurFD->hasAttr<CPUDispatchAttr>()) {
12003 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
12004 std::equal(
12005 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
12006 NewCPUDisp->cpus_begin(),
12007 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
12008 return Cur->getName() == New->getName();
12009 })) {
12010 NewFD->setIsMultiVersion();
12011 Redeclaration = true;
12012 OldDecl = ND;
12013 return false;
12014 }
12015
12016 // If the declarations don't match, this is an error condition.
12017 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
12018 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
12019 NewFD->setInvalidDecl();
12020 return true;
12021 }
12022 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
12023 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
12024 std::equal(
12025 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
12026 NewCPUSpec->cpus_begin(),
12027 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
12028 return Cur->getName() == New->getName();
12029 })) {
12030 NewFD->setIsMultiVersion();
12031 Redeclaration = true;
12032 OldDecl = ND;
12033 return false;
12034 }
12035
12036 // Only 1 version of CPUSpecific is allowed for each CPU.
12037 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
12038 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
12039 if (CurII == NewII) {
12040 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
12041 << NewII;
12042 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
12043 NewFD->setInvalidDecl();
12044 return true;
12045 }
12046 }
12047 }
12048 }
12049 break;
12050 }
12051 }
12052 }
12053
12054 // Redeclarations of a target_clones function may omit the attribute, in which
12055 // case it will be inherited during declaration merging.
12056 if (NewMVKind == MultiVersionKind::None &&
12057 OldMVKind == MultiVersionKind::TargetClones) {
12058 NewFD->setIsMultiVersion();
12059 Redeclaration = true;
12060 OldDecl = OldFD;
12061 return false;
12062 }
12063
12064 // Else, this is simply a non-redecl case. Checking the 'value' is only
12065 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
12066 // handled in the attribute adding step.
12067 if ((NewTA || NewTVA) && CheckMultiVersionValue(S, NewFD)) {
12068 NewFD->setInvalidDecl();
12069 return true;
12070 }
12071
12072 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
12073 !OldFD->isMultiVersion(), NewMVKind)) {
12074 NewFD->setInvalidDecl();
12075 return true;
12076 }
12077
12078 // Permit forward declarations in the case where these two are compatible.
12079 if (!OldFD->isMultiVersion()) {
12080 OldFD->setIsMultiVersion();
12081 NewFD->setIsMultiVersion();
12082 Redeclaration = true;
12083 OldDecl = OldFD;
12084 return false;
12085 }
12086
12087 NewFD->setIsMultiVersion();
12088 Redeclaration = false;
12089 OldDecl = nullptr;
12090 Previous.clear();
12091 return false;
12092}
12093
12094/// Check the validity of a mulitversion function declaration.
12095/// Also sets the multiversion'ness' of the function itself.
12096///
12097/// This sets NewFD->isInvalidDecl() to true if there was an error.
12098///
12099/// Returns true if there was an error, false otherwise.
12101 bool &Redeclaration, NamedDecl *&OldDecl,
12103 const TargetInfo &TI = S.getASTContext().getTargetInfo();
12104
12105 // Check if FMV is disabled.
12106 if (TI.getTriple().isAArch64() && !TI.hasFeature("fmv"))
12107 return false;
12108
12109 const auto *NewTA = NewFD->getAttr<TargetAttr>();
12110 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
12111 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
12112 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
12113 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
12114 MultiVersionKind MVKind = NewFD->getMultiVersionKind();
12115
12116 // Main isn't allowed to become a multiversion function, however it IS
12117 // permitted to have 'main' be marked with the 'target' optimization hint,
12118 // for 'target_version' only default is allowed.
12119 if (NewFD->isMain()) {
12120 if (MVKind != MultiVersionKind::None &&
12121 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
12122 !(MVKind == MultiVersionKind::TargetVersion &&
12123 NewTVA->isDefaultVersion())) {
12124 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
12125 NewFD->setInvalidDecl();
12126 return true;
12127 }
12128 return false;
12129 }
12130
12131 // Target attribute on AArch64 is not used for multiversioning
12132 if (NewTA && TI.getTriple().isAArch64())
12133 return false;
12134
12135 // Target attribute on RISCV is not used for multiversioning
12136 if (NewTA && TI.getTriple().isRISCV())
12137 return false;
12138
12139 if (!OldDecl || !OldDecl->getAsFunction() ||
12140 !OldDecl->getDeclContext()->getRedeclContext()->Equals(
12141 NewFD->getDeclContext()->getRedeclContext())) {
12142 // If there's no previous declaration, AND this isn't attempting to cause
12143 // multiversioning, this isn't an error condition.
12144 if (MVKind == MultiVersionKind::None)
12145 return false;
12146 return CheckMultiVersionFirstFunction(S, NewFD);
12147 }
12148
12149 FunctionDecl *OldFD = OldDecl->getAsFunction();
12150
12151 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
12152 return false;
12153
12154 // Multiversioned redeclarations aren't allowed to omit the attribute, except
12155 // for target_clones and target_version.
12156 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
12159 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
12161 NewFD->setInvalidDecl();
12162 return true;
12163 }
12164
12165 if (!OldFD->isMultiVersion()) {
12166 switch (MVKind) {
12170 S, OldFD, NewFD, Redeclaration, OldDecl, Previous);
12172 if (OldFD->isUsed(false)) {
12173 NewFD->setInvalidDecl();
12174 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
12175 }
12176 OldFD->setIsMultiVersion();
12177 break;
12178
12182 break;
12183 }
12184 }
12185
12186 // At this point, we have a multiversion function decl (in OldFD) AND an
12187 // appropriate attribute in the current function decl (unless it's allowed to
12188 // omit the attribute). Resolve that these are still compatible with previous
12189 // declarations.
12190 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, NewCPUDisp,
12191 NewCPUSpec, NewClones, Redeclaration,
12192 OldDecl, Previous);
12193}
12194
12196 bool IsPure = NewFD->hasAttr<PureAttr>();
12197 bool IsConst = NewFD->hasAttr<ConstAttr>();
12198
12199 // If there are no pure or const attributes, there's nothing to check.
12200 if (!IsPure && !IsConst)
12201 return;
12202
12203 // If the function is marked both pure and const, we retain the const
12204 // attribute because it makes stronger guarantees than the pure attribute, and
12205 // we drop the pure attribute explicitly to prevent later confusion about
12206 // semantics.
12207 if (IsPure && IsConst) {
12208 S.Diag(NewFD->getLocation(), diag::warn_const_attr_with_pure_attr);
12209 NewFD->dropAttrs<PureAttr>();
12210 }
12211
12212 // Constructors and destructors are functions which return void, so are
12213 // handled here as well.
12214 if (NewFD->getReturnType()->isVoidType()) {
12215 S.Diag(NewFD->getLocation(), diag::warn_pure_function_returns_void)
12216 << IsConst;
12217 NewFD->dropAttrs<PureAttr, ConstAttr>();
12218 }
12219}
12220
12223 bool IsMemberSpecialization,
12224 bool DeclIsDefn) {
12225 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
12226 "Variably modified return types are not handled here");
12227
12228 // Determine whether the type of this function should be merged with
12229 // a previous visible declaration. This never happens for functions in C++,
12230 // and always happens in C if the previous declaration was visible.
12231 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
12232 !Previous.isShadowed();
12233
12234 bool Redeclaration = false;
12235 NamedDecl *OldDecl = nullptr;
12236 bool MayNeedOverloadableChecks = false;
12237
12239 // Merge or overload the declaration with an existing declaration of
12240 // the same name, if appropriate.
12241 if (!Previous.empty()) {
12242 // Determine whether NewFD is an overload of PrevDecl or
12243 // a declaration that requires merging. If it's an overload,
12244 // there's no more work to do here; we'll just add the new
12245 // function to the scope.
12247 NamedDecl *Candidate = Previous.getRepresentativeDecl();
12248 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
12249 Redeclaration = true;
12250 OldDecl = Candidate;
12251 }
12252 } else {
12253 MayNeedOverloadableChecks = true;
12254 switch (CheckOverload(S, NewFD, Previous, OldDecl,
12255 /*NewIsUsingDecl*/ false)) {
12257 Redeclaration = true;
12258 break;
12259
12261 Redeclaration = true;
12262 break;
12263
12265 Redeclaration = false;
12266 break;
12267 }
12268 }
12269 }
12270
12271 // Check for a previous extern "C" declaration with this name.
12272 if (!Redeclaration &&
12274 if (!Previous.empty()) {
12275 // This is an extern "C" declaration with the same name as a previous
12276 // declaration, and thus redeclares that entity...
12277 Redeclaration = true;
12278 OldDecl = Previous.getFoundDecl();
12279 MergeTypeWithPrevious = false;
12280
12281 // ... except in the presence of __attribute__((overloadable)).
12282 if (OldDecl->hasAttr<OverloadableAttr>() ||
12283 NewFD->hasAttr<OverloadableAttr>()) {
12284 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
12285 MayNeedOverloadableChecks = true;
12286 Redeclaration = false;
12287 OldDecl = nullptr;
12288 }
12289 }
12290 }
12291 }
12292
12293 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
12294 return Redeclaration;
12295
12296 // PPC MMA non-pointer types are not allowed as function return types.
12297 if (Context.getTargetInfo().getTriple().isPPC64() &&
12298 PPC().CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
12299 NewFD->setInvalidDecl();
12300 }
12301
12302 CheckConstPureAttributesUsage(*this, NewFD);
12303
12304 // C++ [dcl.spec.auto.general]p12:
12305 // Return type deduction for a templated function with a placeholder in its
12306 // declared type occurs when the definition is instantiated even if the
12307 // function body contains a return statement with a non-type-dependent
12308 // operand.
12309 //
12310 // C++ [temp.dep.expr]p3:
12311 // An id-expression is type-dependent if it is a template-id that is not a
12312 // concept-id and is dependent; or if its terminal name is:
12313 // - [...]
12314 // - associated by name lookup with one or more declarations of member
12315 // functions of a class that is the current instantiation declared with a
12316 // return type that contains a placeholder type,
12317 // - [...]
12318 //
12319 // If this is a templated function with a placeholder in its return type,
12320 // make the placeholder type dependent since it won't be deduced until the
12321 // definition is instantiated. We do this here because it needs to happen
12322 // for implicitly instantiated member functions/member function templates.
12323 if (getLangOpts().CPlusPlus14 &&
12324 (NewFD->isDependentContext() &&
12325 NewFD->getReturnType()->isUndeducedType())) {
12326 const FunctionProtoType *FPT =
12327 NewFD->getType()->castAs<FunctionProtoType>();
12328 QualType NewReturnType = SubstAutoTypeDependent(FPT->getReturnType());
12329 NewFD->setType(Context.getFunctionType(NewReturnType, FPT->getParamTypes(),
12330 FPT->getExtProtoInfo()));
12331 }
12332
12333 // C++11 [dcl.constexpr]p8:
12334 // A constexpr specifier for a non-static member function that is not
12335 // a constructor declares that member function to be const.
12336 //
12337 // This needs to be delayed until we know whether this is an out-of-line
12338 // definition of a static member function.
12339 //
12340 // This rule is not present in C++1y, so we produce a backwards
12341 // compatibility warning whenever it happens in C++11.
12342 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
12343 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
12344 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
12346 CXXMethodDecl *OldMD = nullptr;
12347 if (OldDecl)
12348 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
12349 if (!OldMD || !OldMD->isStatic()) {
12350 const FunctionProtoType *FPT =
12353 EPI.TypeQuals.addConst();
12354 MD->setType(Context.getFunctionType(FPT->getReturnType(),
12355 FPT->getParamTypes(), EPI));
12356
12357 // Warn that we did this, if we're not performing template instantiation.
12358 // In that case, we'll have warned already when the template was defined.
12359 if (!inTemplateInstantiation()) {
12360 SourceLocation AddConstLoc;
12363 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
12364
12365 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
12366 << FixItHint::CreateInsertion(AddConstLoc, " const");
12367 }
12368 }
12369 }
12370
12371 if (Redeclaration) {
12372 // NewFD and OldDecl represent declarations that need to be
12373 // merged.
12374 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
12375 DeclIsDefn)) {
12376 NewFD->setInvalidDecl();
12377 return Redeclaration;
12378 }
12379
12380 Previous.clear();
12381 Previous.addDecl(OldDecl);
12382
12383 if (FunctionTemplateDecl *OldTemplateDecl =
12384 dyn_cast<FunctionTemplateDecl>(OldDecl)) {
12385 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
12386 FunctionTemplateDecl *NewTemplateDecl
12388 assert(NewTemplateDecl && "Template/non-template mismatch");
12389
12390 // The call to MergeFunctionDecl above may have created some state in
12391 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
12392 // can add it as a redeclaration.
12393 NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
12394
12395 NewFD->setPreviousDeclaration(OldFD);
12396 if (NewFD->isCXXClassMember()) {
12397 NewFD->setAccess(OldTemplateDecl->getAccess());
12398 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
12399 }
12400
12401 // If this is an explicit specialization of a member that is a function
12402 // template, mark it as a member specialization.
12403 if (IsMemberSpecialization &&
12404 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
12405 NewTemplateDecl->setMemberSpecialization();
12406 assert(OldTemplateDecl->isMemberSpecialization());
12407 // Explicit specializations of a member template do not inherit deleted
12408 // status from the parent member template that they are specializing.
12409 if (OldFD->isDeleted()) {
12410 // FIXME: This assert will not hold in the presence of modules.
12411 assert(OldFD->getCanonicalDecl() == OldFD);
12412 // FIXME: We need an update record for this AST mutation.
12413 OldFD->setDeletedAsWritten(false);
12414 }
12415 }
12416
12417 } else {
12418 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
12419 auto *OldFD = cast<FunctionDecl>(OldDecl);
12420 // This needs to happen first so that 'inline' propagates.
12421 NewFD->setPreviousDeclaration(OldFD);
12422 if (NewFD->isCXXClassMember())
12423 NewFD->setAccess(OldFD->getAccess());
12424 }
12425 }
12426 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
12427 !NewFD->getAttr<OverloadableAttr>()) {
12428 assert((Previous.empty() ||
12429 llvm::any_of(Previous,
12430 [](const NamedDecl *ND) {
12431 return ND->hasAttr<OverloadableAttr>();
12432 })) &&
12433 "Non-redecls shouldn't happen without overloadable present");
12434
12435 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
12436 const auto *FD = dyn_cast<FunctionDecl>(ND);
12437 return FD && !FD->hasAttr<OverloadableAttr>();
12438 });
12439
12440 if (OtherUnmarkedIter != Previous.end()) {
12441 Diag(NewFD->getLocation(),
12442 diag::err_attribute_overloadable_multiple_unmarked_overloads);
12443 Diag((*OtherUnmarkedIter)->getLocation(),
12444 diag::note_attribute_overloadable_prev_overload)
12445 << false;
12446
12447 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
12448 }
12449 }
12450
12451 if (LangOpts.OpenMP)
12453
12454 if (NewFD->hasAttr<SYCLKernelEntryPointAttr>())
12456
12457 if (NewFD->hasAttr<SYCLExternalAttr>())
12459
12460 // Semantic checking for this function declaration (in isolation).
12461
12462 if (getLangOpts().CPlusPlus) {
12463 // C++-specific checks.
12464 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
12466 } else if (CXXDestructorDecl *Destructor =
12467 dyn_cast<CXXDestructorDecl>(NewFD)) {
12468 // We check here for invalid destructor names.
12469 // If we have a friend destructor declaration that is dependent, we can't
12470 // diagnose right away because cases like this are still valid:
12471 // template <class T> struct A { friend T::X::~Y(); };
12472 // struct B { struct Y { ~Y(); }; using X = Y; };
12473 // template struct A<B>;
12475 !Destructor->getFunctionObjectParameterType()->isDependentType()) {
12476 CanQualType ClassType =
12477 Context.getCanonicalTagType(Destructor->getParent());
12478
12479 DeclarationName Name =
12480 Context.DeclarationNames.getCXXDestructorName(ClassType);
12481 if (NewFD->getDeclName() != Name) {
12482 Diag(NewFD->getLocation(), diag::err_destructor_name);
12483 NewFD->setInvalidDecl();
12484 return Redeclaration;
12485 }
12486 }
12487 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
12488 if (auto *TD = Guide->getDescribedFunctionTemplate())
12490
12491 // A deduction guide is not on the list of entities that can be
12492 // explicitly specialized.
12493 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
12494 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
12495 << /*explicit specialization*/ 1;
12496 }
12497
12498 // Find any virtual functions that this function overrides.
12499 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
12500 if (!Method->isFunctionTemplateSpecialization() &&
12501 !Method->getDescribedFunctionTemplate() &&
12502 Method->isCanonicalDecl()) {
12503 AddOverriddenMethods(Method->getParent(), Method);
12504 }
12505 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
12506 // C++2a [class.virtual]p6
12507 // A virtual method shall not have a requires-clause.
12509 diag::err_constrained_virtual_method);
12510
12511 if (Method->isStatic())
12513 }
12514
12515 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
12516 ActOnConversionDeclarator(Conversion);
12517
12518 // Extra checking for C++ overloaded operators (C++ [over.oper]).
12519 if (NewFD->isOverloadedOperator() &&
12521 NewFD->setInvalidDecl();
12522 return Redeclaration;
12523 }
12524
12525 // Extra checking for C++0x literal operators (C++0x [over.literal]).
12526 if (NewFD->getLiteralIdentifier() &&
12528 NewFD->setInvalidDecl();
12529 return Redeclaration;
12530 }
12531
12532 // In C++, check default arguments now that we have merged decls. Unless
12533 // the lexical context is the class, because in this case this is done
12534 // during delayed parsing anyway.
12535 if (!CurContext->isRecord())
12537
12538 // If this function is declared as being extern "C", then check to see if
12539 // the function returns a UDT (class, struct, or union type) that is not C
12540 // compatible, and if it does, warn the user.
12541 // But, issue any diagnostic on the first declaration only.
12542 if (Previous.empty() && NewFD->isExternC()) {
12543 QualType R = NewFD->getReturnType();
12544 if (R->isIncompleteType() && !R->isVoidType())
12545 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
12546 << NewFD << R;
12547 else if (!R.isPODType(Context) && !R->isVoidType() &&
12549 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
12550 }
12551
12552 // C++1z [dcl.fct]p6:
12553 // [...] whether the function has a non-throwing exception-specification
12554 // [is] part of the function type
12555 //
12556 // This results in an ABI break between C++14 and C++17 for functions whose
12557 // declared type includes an exception-specification in a parameter or
12558 // return type. (Exception specifications on the function itself are OK in
12559 // most cases, and exception specifications are not permitted in most other
12560 // contexts where they could make it into a mangling.)
12561 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
12562 auto HasNoexcept = [&](QualType T) -> bool {
12563 // Strip off declarator chunks that could be between us and a function
12564 // type. We don't need to look far, exception specifications are very
12565 // restricted prior to C++17.
12566 if (auto *RT = T->getAs<ReferenceType>())
12567 T = RT->getPointeeType();
12568 else if (T->isAnyPointerType())
12569 T = T->getPointeeType();
12570 else if (auto *MPT = T->getAs<MemberPointerType>())
12571 T = MPT->getPointeeType();
12572 if (auto *FPT = T->getAs<FunctionProtoType>())
12573 if (FPT->isNothrow())
12574 return true;
12575 return false;
12576 };
12577
12578 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12579 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12580 for (QualType T : FPT->param_types())
12581 AnyNoexcept |= HasNoexcept(T);
12582 if (AnyNoexcept)
12583 Diag(NewFD->getLocation(),
12584 diag::warn_cxx17_compat_exception_spec_in_signature)
12585 << NewFD;
12586 }
12587
12588 if (!Redeclaration && LangOpts.CUDA) {
12589 bool IsKernel = NewFD->hasAttr<CUDAGlobalAttr>();
12590 for (auto *Parm : NewFD->parameters()) {
12591 if (!Parm->getType()->isDependentType() &&
12592 Parm->hasAttr<CUDAGridConstantAttr>() &&
12593 !(IsKernel && Parm->getType().isConstQualified()))
12594 Diag(Parm->getAttr<CUDAGridConstantAttr>()->getLocation(),
12595 diag::err_cuda_grid_constant_not_allowed);
12596 }
12598 }
12599 }
12600
12601 if (DeclIsDefn && Context.getTargetInfo().getTriple().isAArch64())
12603
12604 return Redeclaration;
12605}
12606
12608 // [basic.start.main]p3
12609 // The main function shall not be declared with C linkage-specification.
12610 if (FD->isExternCContext())
12611 Diag(FD->getLocation(), diag::ext_main_invalid_linkage_specification);
12612
12613 // C++11 [basic.start.main]p3:
12614 // A program that [...] declares main to be inline, static or
12615 // constexpr is ill-formed.
12616 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
12617 // appear in a declaration of main.
12618 // static main is not an error under C99, but we should warn about it.
12619 // We accept _Noreturn main as an extension.
12620 if (FD->getStorageClass() == SC_Static)
12622 ? diag::err_static_main : diag::warn_static_main)
12624 if (FD->isInlineSpecified())
12625 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
12627 if (DS.isNoreturnSpecified()) {
12628 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12629 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
12630 Diag(NoreturnLoc, diag::ext_noreturn_main);
12631 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
12632 << FixItHint::CreateRemoval(NoreturnRange);
12633 }
12634 if (FD->isConstexpr()) {
12635 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
12636 << FD->isConsteval()
12639 }
12640
12641 if (getLangOpts().OpenCL) {
12642 Diag(FD->getLocation(), diag::err_opencl_no_main)
12643 << FD->hasAttr<DeviceKernelAttr>();
12644 FD->setInvalidDecl();
12645 return;
12646 }
12647
12648 if (FD->hasAttr<SYCLExternalAttr>()) {
12649 Diag(FD->getLocation(), diag::err_sycl_external_invalid_main)
12650 << FD->getAttr<SYCLExternalAttr>();
12651 FD->setInvalidDecl();
12652 return;
12653 }
12654
12655 // Functions named main in hlsl are default entries, but don't have specific
12656 // signatures they are required to conform to.
12657 if (getLangOpts().HLSL)
12658 return;
12659
12660 QualType T = FD->getType();
12661 assert(T->isFunctionType() && "function decl is not of function type");
12662 const FunctionType* FT = T->castAs<FunctionType>();
12663
12664 // Set default calling convention for main()
12665 if (FT->getCallConv() != CC_C) {
12666 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
12667 FD->setType(QualType(FT, 0));
12668 T = Context.getCanonicalType(FD->getType());
12669 }
12670
12672 // In C with GNU extensions we allow main() to have non-integer return
12673 // type, but we should warn about the extension, and we disable the
12674 // implicit-return-zero rule.
12675
12676 // GCC in C mode accepts qualified 'int'.
12677 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
12678 FD->setHasImplicitReturnZero(true);
12679 else {
12680 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
12681 SourceRange RTRange = FD->getReturnTypeSourceRange();
12682 if (RTRange.isValid())
12683 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
12684 << FixItHint::CreateReplacement(RTRange, "int");
12685 }
12686 } else {
12687 // In C and C++, main magically returns 0 if you fall off the end;
12688 // set the flag which tells us that.
12689 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12690
12691 // All the standards say that main() should return 'int'.
12692 if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
12693 FD->setHasImplicitReturnZero(true);
12694 else {
12695 // Otherwise, this is just a flat-out error.
12696 SourceRange RTRange = FD->getReturnTypeSourceRange();
12697 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
12698 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
12699 : FixItHint());
12700 FD->setInvalidDecl(true);
12701 }
12702
12703 // [basic.start.main]p3:
12704 // A program that declares a function main that belongs to the global scope
12705 // and is attached to a named module is ill-formed.
12706 if (FD->isInNamedModule()) {
12707 const SourceLocation start = FD->getTypeSpecStartLoc();
12708 Diag(start, diag::warn_main_in_named_module)
12709 << FixItHint::CreateInsertion(start, "extern \"C++\" ", true);
12710 }
12711 }
12712
12713 // Treat protoless main() as nullary.
12714 if (isa<FunctionNoProtoType>(FT)) return;
12715
12717 unsigned nparams = FTP->getNumParams();
12718 assert(FD->getNumParams() == nparams);
12719
12720 bool HasExtraParameters = (nparams > 3);
12721
12722 if (FTP->isVariadic()) {
12723 Diag(FD->getLocation(), diag::ext_variadic_main);
12724 // FIXME: if we had information about the location of the ellipsis, we
12725 // could add a FixIt hint to remove it as a parameter.
12726 }
12727
12728 // Darwin passes an undocumented fourth argument of type char**. If
12729 // other platforms start sprouting these, the logic below will start
12730 // getting shifty.
12731 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12732 HasExtraParameters = false;
12733
12734 if (HasExtraParameters) {
12735 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
12736 FD->setInvalidDecl(true);
12737 nparams = 3;
12738 }
12739
12740 // FIXME: a lot of the following diagnostics would be improved
12741 // if we had some location information about types.
12742
12743 QualType CharPP =
12744 Context.getPointerType(Context.getPointerType(Context.CharTy));
12745 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12746
12747 for (unsigned i = 0; i < nparams; ++i) {
12748 QualType AT = FTP->getParamType(i);
12749
12750 bool mismatch = true;
12751
12752 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
12753 mismatch = false;
12754 else if (Expected[i] == CharPP) {
12755 // As an extension, the following forms are okay:
12756 // char const **
12757 // char const * const *
12758 // char * const *
12759
12761 const PointerType* PT;
12762 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
12763 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
12764 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
12765 Context.CharTy)) {
12766 qs.removeConst();
12767 mismatch = !qs.empty();
12768 }
12769 }
12770
12771 if (mismatch) {
12772 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
12773 // TODO: suggest replacing given type with expected type
12774 FD->setInvalidDecl(true);
12775 }
12776 }
12777
12778 if (nparams == 1 && !FD->isInvalidDecl()) {
12779 Diag(FD->getLocation(), diag::warn_main_one_arg);
12780 }
12781
12782 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12783 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12784 FD->setInvalidDecl();
12785 }
12786}
12787
12788static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
12789
12790 // Default calling convention for main and wmain is __cdecl
12791 if (FD->getName() == "main" || FD->getName() == "wmain")
12792 return false;
12793
12794 // Default calling convention for MinGW and Cygwin is __cdecl
12795 const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
12796 if (T.isOSCygMing())
12797 return false;
12798
12799 // Default calling convention for WinMain, wWinMain and DllMain
12800 // is __stdcall on 32 bit Windows
12801 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
12802 return true;
12803
12804 return false;
12805}
12806
12808 QualType T = FD->getType();
12809 assert(T->isFunctionType() && "function decl is not of function type");
12810 const FunctionType *FT = T->castAs<FunctionType>();
12811
12812 // Set an implicit return of 'zero' if the function can return some integral,
12813 // enumeration, pointer or nullptr type.
12817 // DllMain is exempt because a return value of zero means it failed.
12818 if (FD->getName() != "DllMain")
12819 FD->setHasImplicitReturnZero(true);
12820
12821 // Explicitly specified calling conventions are applied to MSVC entry points
12822 if (!hasExplicitCallingConv(T)) {
12823 if (isDefaultStdCall(FD, *this)) {
12824 if (FT->getCallConv() != CC_X86StdCall) {
12825 FT = Context.adjustFunctionType(
12827 FD->setType(QualType(FT, 0));
12828 }
12829 } else if (FT->getCallConv() != CC_C) {
12830 FT = Context.adjustFunctionType(FT,
12832 FD->setType(QualType(FT, 0));
12833 }
12834 }
12835
12836 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12837 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12838 FD->setInvalidDecl();
12839 }
12840}
12841
12843 // FIXME: Need strict checking. In C89, we need to check for
12844 // any assignment, increment, decrement, function-calls, or
12845 // commas outside of a sizeof. In C99, it's the same list,
12846 // except that the aforementioned are allowed in unevaluated
12847 // expressions. Everything else falls under the
12848 // "may accept other forms of constant expressions" exception.
12849 //
12850 // Regular C++ code will not end up here (exceptions: language extensions,
12851 // OpenCL C++ etc), so the constant expression rules there don't matter.
12852 if (Init->isValueDependent()) {
12853 assert(Init->containsErrors() &&
12854 "Dependent code should only occur in error-recovery path.");
12855 return true;
12856 }
12857 const Expr *Culprit;
12858 if (Init->isConstantInitializer(Context, false, &Culprit))
12859 return false;
12860 Diag(Culprit->getExprLoc(), DiagID) << Culprit->getSourceRange();
12861 return true;
12862}
12863
12864namespace {
12865 // Visits an initialization expression to see if OrigDecl is evaluated in
12866 // its own initialization and throws a warning if it does.
12867 class SelfReferenceChecker
12868 : public EvaluatedExprVisitor<SelfReferenceChecker> {
12869 Sema &S;
12870 Decl *OrigDecl;
12871 bool isRecordType;
12872 bool isPODType;
12873 bool isReferenceType;
12874 bool isInCXXOperatorCall;
12875
12876 bool isInitList;
12877 llvm::SmallVector<unsigned, 4> InitFieldIndex;
12878
12879 public:
12881
12882 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
12883 S(S), OrigDecl(OrigDecl) {
12884 isPODType = false;
12885 isRecordType = false;
12886 isReferenceType = false;
12887 isInCXXOperatorCall = false;
12888 isInitList = false;
12889 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
12890 isPODType = VD->getType().isPODType(S.Context);
12891 isRecordType = VD->getType()->isRecordType();
12892 isReferenceType = VD->getType()->isReferenceType();
12893 }
12894 }
12895
12896 // For most expressions, just call the visitor. For initializer lists,
12897 // track the index of the field being initialized since fields are
12898 // initialized in order allowing use of previously initialized fields.
12899 void CheckExpr(Expr *E) {
12900 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
12901 if (!InitList) {
12902 Visit(E);
12903 return;
12904 }
12905
12906 // Track and increment the index here.
12907 isInitList = true;
12908 InitFieldIndex.push_back(0);
12909 for (auto *Child : InitList->children()) {
12910 CheckExpr(cast<Expr>(Child));
12911 ++InitFieldIndex.back();
12912 }
12913 InitFieldIndex.pop_back();
12914 }
12915
12916 // Returns true if MemberExpr is checked and no further checking is needed.
12917 // Returns false if additional checking is required.
12918 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
12919 llvm::SmallVector<FieldDecl*, 4> Fields;
12920 Expr *Base = E;
12921 bool ReferenceField = false;
12922
12923 // Get the field members used.
12924 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12925 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
12926 if (!FD)
12927 return false;
12928 Fields.push_back(FD);
12929 if (FD->getType()->isReferenceType())
12930 ReferenceField = true;
12931 Base = ME->getBase()->IgnoreParenImpCasts();
12932 }
12933
12934 // Keep checking only if the base Decl is the same.
12935 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
12936 if (!DRE || DRE->getDecl() != OrigDecl)
12937 return false;
12938
12939 // A reference field can be bound to an unininitialized field.
12940 if (CheckReference && !ReferenceField)
12941 return true;
12942
12943 // Convert FieldDecls to their index number.
12944 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
12945 for (const FieldDecl *I : llvm::reverse(Fields))
12946 UsedFieldIndex.push_back(I->getFieldIndex());
12947
12948 // See if a warning is needed by checking the first difference in index
12949 // numbers. If field being used has index less than the field being
12950 // initialized, then the use is safe.
12951 for (auto UsedIter = UsedFieldIndex.begin(),
12952 UsedEnd = UsedFieldIndex.end(),
12953 OrigIter = InitFieldIndex.begin(),
12954 OrigEnd = InitFieldIndex.end();
12955 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
12956 if (*UsedIter < *OrigIter)
12957 return true;
12958 if (*UsedIter > *OrigIter)
12959 break;
12960 }
12961
12962 // TODO: Add a different warning which will print the field names.
12963 HandleDeclRefExpr(DRE);
12964 return true;
12965 }
12966
12967 // For most expressions, the cast is directly above the DeclRefExpr.
12968 // For conditional operators, the cast can be outside the conditional
12969 // operator if both expressions are DeclRefExpr's.
12970 void HandleValue(Expr *E) {
12971 E = E->IgnoreParens();
12972 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
12973 HandleDeclRefExpr(DRE);
12974 return;
12975 }
12976
12977 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
12978 Visit(CO->getCond());
12979 HandleValue(CO->getTrueExpr());
12980 HandleValue(CO->getFalseExpr());
12981 return;
12982 }
12983
12984 if (BinaryConditionalOperator *BCO =
12985 dyn_cast<BinaryConditionalOperator>(E)) {
12986 Visit(BCO->getCond());
12987 HandleValue(BCO->getFalseExpr());
12988 return;
12989 }
12990
12991 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
12992 if (Expr *SE = OVE->getSourceExpr())
12993 HandleValue(SE);
12994 return;
12995 }
12996
12997 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12998 if (BO->getOpcode() == BO_Comma) {
12999 Visit(BO->getLHS());
13000 HandleValue(BO->getRHS());
13001 return;
13002 }
13003 }
13004
13005 if (isa<MemberExpr>(E)) {
13006 if (isInitList) {
13007 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
13008 false /*CheckReference*/))
13009 return;
13010 }
13011
13012 Expr *Base = E->IgnoreParenImpCasts();
13013 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
13014 // Check for static member variables and don't warn on them.
13015 if (!isa<FieldDecl>(ME->getMemberDecl()))
13016 return;
13017 Base = ME->getBase()->IgnoreParenImpCasts();
13018 }
13019 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
13020 HandleDeclRefExpr(DRE);
13021 return;
13022 }
13023
13024 Visit(E);
13025 }
13026
13027 // Reference types not handled in HandleValue are handled here since all
13028 // uses of references are bad, not just r-value uses.
13029 void VisitDeclRefExpr(DeclRefExpr *E) {
13030 if (isReferenceType)
13031 HandleDeclRefExpr(E);
13032 }
13033
13034 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
13035 if (E->getCastKind() == CK_LValueToRValue) {
13036 HandleValue(E->getSubExpr());
13037 return;
13038 }
13039
13040 Inherited::VisitImplicitCastExpr(E);
13041 }
13042
13043 void VisitMemberExpr(MemberExpr *E) {
13044 if (isInitList) {
13045 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
13046 return;
13047 }
13048
13049 // Don't warn on arrays since they can be treated as pointers.
13050 if (E->getType()->canDecayToPointerType()) return;
13051
13052 // Warn when a non-static method call is followed by non-static member
13053 // field accesses, which is followed by a DeclRefExpr.
13054 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
13055 bool Warn = (MD && !MD->isStatic());
13056 Expr *Base = E->getBase()->IgnoreParenImpCasts();
13057 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
13058 if (!isa<FieldDecl>(ME->getMemberDecl()))
13059 Warn = false;
13060 Base = ME->getBase()->IgnoreParenImpCasts();
13061 }
13062
13063 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
13064 if (Warn)
13065 HandleDeclRefExpr(DRE);
13066 return;
13067 }
13068
13069 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
13070 // Visit that expression.
13071 Visit(Base);
13072 }
13073
13074 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
13075 llvm::SaveAndRestore CxxOpCallScope(isInCXXOperatorCall, true);
13076 Expr *Callee = E->getCallee();
13077
13078 if (isa<UnresolvedLookupExpr>(Callee))
13079 return Inherited::VisitCXXOperatorCallExpr(E);
13080
13081 Visit(Callee);
13082 for (auto Arg: E->arguments())
13083 HandleValue(Arg->IgnoreParenImpCasts());
13084 }
13085
13086 void VisitLambdaExpr(LambdaExpr *E) {
13087 if (!isInCXXOperatorCall) {
13088 Inherited::VisitLambdaExpr(E);
13089 return;
13090 }
13091
13092 for (Expr *Init : E->capture_inits())
13093 if (DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(Init))
13094 HandleDeclRefExpr(DRE);
13095 else if (Init)
13096 Visit(Init);
13097 }
13098
13099 void VisitUnaryOperator(UnaryOperator *E) {
13100 // For POD record types, addresses of its own members are well-defined.
13101 if (E->getOpcode() == UO_AddrOf && isRecordType &&
13103 if (!isPODType)
13104 HandleValue(E->getSubExpr());
13105 return;
13106 }
13107
13108 if (E->isIncrementDecrementOp()) {
13109 HandleValue(E->getSubExpr());
13110 return;
13111 }
13112
13113 Inherited::VisitUnaryOperator(E);
13114 }
13115
13116 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
13117
13118 void VisitCXXConstructExpr(CXXConstructExpr *E) {
13119 if (E->getConstructor()->isCopyConstructor()) {
13120 Expr *ArgExpr = E->getArg(0);
13121 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
13122 if (ILE->getNumInits() == 1)
13123 ArgExpr = ILE->getInit(0);
13124 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
13125 if (ICE->getCastKind() == CK_NoOp)
13126 ArgExpr = ICE->getSubExpr();
13127 HandleValue(ArgExpr);
13128 return;
13129 }
13130 Inherited::VisitCXXConstructExpr(E);
13131 }
13132
13133 void VisitCallExpr(CallExpr *E) {
13134 // Treat std::move as a use.
13135 if (E->isCallToStdMove()) {
13136 HandleValue(E->getArg(0));
13137 return;
13138 }
13139
13140 Inherited::VisitCallExpr(E);
13141 }
13142
13143 void VisitBinaryOperator(BinaryOperator *E) {
13144 if (E->isCompoundAssignmentOp()) {
13145 HandleValue(E->getLHS());
13146 Visit(E->getRHS());
13147 return;
13148 }
13149
13150 Inherited::VisitBinaryOperator(E);
13151 }
13152
13153 // A custom visitor for BinaryConditionalOperator is needed because the
13154 // regular visitor would check the condition and true expression separately
13155 // but both point to the same place giving duplicate diagnostics.
13156 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
13157 Visit(E->getCond());
13158 Visit(E->getFalseExpr());
13159 }
13160
13161 void HandleDeclRefExpr(DeclRefExpr *DRE) {
13162 Decl* ReferenceDecl = DRE->getDecl();
13163 if (OrigDecl != ReferenceDecl) return;
13164 unsigned diag;
13165 if (isReferenceType) {
13166 diag = diag::warn_uninit_self_reference_in_reference_init;
13167 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
13168 diag = diag::warn_static_self_reference_in_init;
13169 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
13170 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
13171 DRE->getDecl()->getType()->isRecordType()) {
13172 diag = diag::warn_uninit_self_reference_in_init;
13173 } else {
13174 // Local variables will be handled by the CFG analysis.
13175 return;
13176 }
13177
13178 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
13179 S.PDiag(diag)
13180 << DRE->getDecl() << OrigDecl->getLocation()
13181 << DRE->getSourceRange());
13182 }
13183 };
13184
13185 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
13186 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
13187 bool DirectInit) {
13188 // Parameters arguments are occassionially constructed with itself,
13189 // for instance, in recursive functions. Skip them.
13190 if (isa<ParmVarDecl>(OrigDecl))
13191 return;
13192
13193 // Skip checking for file-scope constexpr variables - constant evaluation
13194 // will produce appropriate errors without needing runtime diagnostics.
13195 // Local constexpr should still emit runtime warnings.
13196 if (auto *VD = dyn_cast<VarDecl>(OrigDecl);
13197 VD && VD->isConstexpr() && VD->isFileVarDecl())
13198 return;
13199
13200 E = E->IgnoreParens();
13201
13202 // Skip checking T a = a where T is not a record or reference type.
13203 // Doing so is a way to silence uninitialized warnings.
13204 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
13205 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
13206 if (ICE->getCastKind() == CK_LValueToRValue)
13207 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
13208 if (DRE->getDecl() == OrigDecl)
13209 return;
13210
13211 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
13212 }
13213} // end anonymous namespace
13214
13215namespace {
13216 // Simple wrapper to add the name of a variable or (if no variable is
13217 // available) a DeclarationName into a diagnostic.
13218 struct VarDeclOrName {
13219 VarDecl *VDecl;
13220 DeclarationName Name;
13221
13222 friend const Sema::SemaDiagnosticBuilder &
13223 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
13224 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
13225 }
13226 };
13227} // end anonymous namespace
13228
13231 TypeSourceInfo *TSI,
13232 SourceRange Range, bool DirectInit,
13233 Expr *Init) {
13234 bool IsInitCapture = !VDecl;
13235 assert((!VDecl || !VDecl->isInitCapture()) &&
13236 "init captures are expected to be deduced prior to initialization");
13237
13238 VarDeclOrName VN{VDecl, Name};
13239
13240 DeducedType *Deduced = Type->getContainedDeducedType();
13241 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
13242
13243 // Diagnose auto array declarations in C23, unless it's a supported extension.
13244 if (getLangOpts().C23 && Type->isArrayType() &&
13245 !isa_and_present<StringLiteral, InitListExpr>(Init)) {
13246 Diag(Range.getBegin(), diag::err_auto_not_allowed)
13247 << (int)Deduced->getContainedAutoType()->getKeyword()
13248 << /*in array decl*/ 23 << Range;
13249 return QualType();
13250 }
13251
13252 // C++11 [dcl.spec.auto]p3
13253 if (!Init) {
13254 assert(VDecl && "no init for init capture deduction?");
13255
13256 // Except for class argument deduction, and then for an initializing
13257 // declaration only, i.e. no static at class scope or extern.
13259 VDecl->hasExternalStorage() ||
13260 VDecl->isStaticDataMember()) {
13261 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
13262 << VDecl->getDeclName() << Type;
13263 return QualType();
13264 }
13265 }
13266
13267 ArrayRef<Expr*> DeduceInits;
13268 if (Init)
13269 DeduceInits = Init;
13270
13271 auto *PL = dyn_cast_if_present<ParenListExpr>(Init);
13272 if (DirectInit && PL)
13273 DeduceInits = PL->exprs();
13274
13276 assert(VDecl && "non-auto type for init capture deduction?");
13279 VDecl->getLocation(), DirectInit, Init);
13280 // FIXME: Initialization should not be taking a mutable list of inits.
13281 SmallVector<Expr *, 8> InitsCopy(DeduceInits);
13282 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
13283 InitsCopy);
13284 }
13285
13286 if (DirectInit) {
13287 if (auto *IL = dyn_cast<InitListExpr>(Init))
13288 DeduceInits = IL->inits();
13289 }
13290
13291 // Deduction only works if we have exactly one source expression.
13292 if (DeduceInits.empty()) {
13293 // It isn't possible to write this directly, but it is possible to
13294 // end up in this situation with "auto x(some_pack...);"
13295 Diag(Init->getBeginLoc(), IsInitCapture
13296 ? diag::err_init_capture_no_expression
13297 : diag::err_auto_var_init_no_expression)
13298 << VN << Type << Range;
13299 return QualType();
13300 }
13301
13302 if (DeduceInits.size() > 1) {
13303 Diag(DeduceInits[1]->getBeginLoc(),
13304 IsInitCapture ? diag::err_init_capture_multiple_expressions
13305 : diag::err_auto_var_init_multiple_expressions)
13306 << VN << Type << Range;
13307 return QualType();
13308 }
13309
13310 Expr *DeduceInit = DeduceInits[0];
13311 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
13312 Diag(Init->getBeginLoc(), IsInitCapture
13313 ? diag::err_init_capture_paren_braces
13314 : diag::err_auto_var_init_paren_braces)
13315 << isa<InitListExpr>(Init) << VN << Type << Range;
13316 return QualType();
13317 }
13318
13319 // Expressions default to 'id' when we're in a debugger.
13320 bool DefaultedAnyToId = false;
13321 if (getLangOpts().DebuggerCastResultToId &&
13322 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
13324 if (Result.isInvalid()) {
13325 return QualType();
13326 }
13327 Init = Result.get();
13328 DefaultedAnyToId = true;
13329 }
13330
13331 // C++ [dcl.decomp]p1:
13332 // If the assignment-expression [...] has array type A and no ref-qualifier
13333 // is present, e has type cv A
13334 if (VDecl && isa<DecompositionDecl>(VDecl) &&
13335 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
13336 DeduceInit->getType()->isConstantArrayType())
13337 return Context.getQualifiedType(DeduceInit->getType(),
13338 Type.getQualifiers());
13339
13340 QualType DeducedType;
13341 TemplateDeductionInfo Info(DeduceInit->getExprLoc());
13343 DeduceAutoType(TSI->getTypeLoc(), DeduceInit, DeducedType, Info);
13346 if (!IsInitCapture)
13347 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
13348 else if (isa<InitListExpr>(Init))
13349 Diag(Range.getBegin(),
13350 diag::err_init_capture_deduction_failure_from_init_list)
13351 << VN
13352 << (DeduceInit->getType().isNull() ? TSI->getType()
13353 : DeduceInit->getType())
13354 << DeduceInit->getSourceRange();
13355 else
13356 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
13357 << VN << TSI->getType()
13358 << (DeduceInit->getType().isNull() ? TSI->getType()
13359 : DeduceInit->getType())
13360 << DeduceInit->getSourceRange();
13361 }
13362
13363 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
13364 // 'id' instead of a specific object type prevents most of our usual
13365 // checks.
13366 // We only want to warn outside of template instantiations, though:
13367 // inside a template, the 'id' could have come from a parameter.
13368 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
13369 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
13370 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
13371 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
13372 }
13373
13374 return DeducedType;
13375}
13376
13378 Expr *Init) {
13379 assert(!Init || !Init->containsErrors());
13381 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
13382 VDecl->getSourceRange(), DirectInit, Init);
13383 if (DeducedType.isNull()) {
13384 VDecl->setInvalidDecl();
13385 return true;
13386 }
13387
13388 VDecl->setType(DeducedType);
13389 assert(VDecl->isLinkageValid());
13390
13391 // In ARC, infer lifetime.
13392 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(VDecl))
13393 VDecl->setInvalidDecl();
13394
13395 if (getLangOpts().OpenCL)
13397
13398 if (getLangOpts().HLSL)
13399 HLSL().deduceAddressSpace(VDecl);
13400
13401 // If this is a redeclaration, check that the type we just deduced matches
13402 // the previously declared type.
13403 if (VarDecl *Old = VDecl->getPreviousDecl()) {
13404 // We never need to merge the type, because we cannot form an incomplete
13405 // array of auto, nor deduce such a type.
13406 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
13407 }
13408
13409 // Check the deduced type is valid for a variable declaration.
13411 return VDecl->isInvalidDecl();
13412}
13413
13415 SourceLocation Loc) {
13416 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
13417 Init = EWC->getSubExpr();
13418
13419 if (auto *CE = dyn_cast<ConstantExpr>(Init))
13420 Init = CE->getSubExpr();
13421
13422 QualType InitType = Init->getType();
13425 "shouldn't be called if type doesn't have a non-trivial C struct");
13426 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
13427 for (auto *I : ILE->inits()) {
13428 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
13429 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
13430 continue;
13431 SourceLocation SL = I->getExprLoc();
13432 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
13433 }
13434 return;
13435 }
13436
13439 checkNonTrivialCUnion(InitType, Loc,
13441 NTCUK_Init);
13442 } else {
13443 // Assume all other explicit initializers involving copying some existing
13444 // object.
13445 // TODO: ignore any explicit initializers where we can guarantee
13446 // copy-elision.
13449 NTCUK_Copy);
13450 }
13451}
13452
13453namespace {
13454
13455bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
13456 // Ignore unavailable fields. A field can be marked as unavailable explicitly
13457 // in the source code or implicitly by the compiler if it is in a union
13458 // defined in a system header and has non-trivial ObjC ownership
13459 // qualifications. We don't want those fields to participate in determining
13460 // whether the containing union is non-trivial.
13461 return FD->hasAttr<UnavailableAttr>();
13462}
13463
13464struct DiagNonTrivalCUnionDefaultInitializeVisitor
13465 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13466 void> {
13467 using Super =
13468 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13469 void>;
13470
13471 DiagNonTrivalCUnionDefaultInitializeVisitor(
13472 QualType OrigTy, SourceLocation OrigLoc,
13473 NonTrivialCUnionContext UseContext, Sema &S)
13474 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13475
13476 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
13477 const FieldDecl *FD, bool InNonTrivialUnion) {
13478 if (const auto *AT = S.Context.getAsArrayType(QT))
13479 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13480 InNonTrivialUnion);
13481 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
13482 }
13483
13484 void visitARCStrong(QualType QT, const FieldDecl *FD,
13485 bool InNonTrivialUnion) {
13486 if (InNonTrivialUnion)
13487 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13488 << 1 << 0 << QT << FD->getName();
13489 }
13490
13491 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13492 if (InNonTrivialUnion)
13493 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13494 << 1 << 0 << QT << FD->getName();
13495 }
13496
13497 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13498 const auto *RD = QT->castAsRecordDecl();
13499 if (RD->isUnion()) {
13500 if (OrigLoc.isValid()) {
13501 bool IsUnion = false;
13502 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13503 IsUnion = OrigRD->isUnion();
13504 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13505 << 0 << OrigTy << IsUnion << UseContext;
13506 // Reset OrigLoc so that this diagnostic is emitted only once.
13507 OrigLoc = SourceLocation();
13508 }
13509 InNonTrivialUnion = true;
13510 }
13511
13512 if (InNonTrivialUnion)
13513 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13514 << 0 << 0 << QT.getUnqualifiedType() << "";
13515
13516 for (const FieldDecl *FD : RD->fields())
13517 if (!shouldIgnoreForRecordTriviality(FD))
13518 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13519 }
13520
13521 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13522
13523 // The non-trivial C union type or the struct/union type that contains a
13524 // non-trivial C union.
13525 QualType OrigTy;
13526 SourceLocation OrigLoc;
13527 NonTrivialCUnionContext UseContext;
13528 Sema &S;
13529};
13530
13531struct DiagNonTrivalCUnionDestructedTypeVisitor
13532 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
13533 using Super =
13534 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
13535
13536 DiagNonTrivalCUnionDestructedTypeVisitor(QualType OrigTy,
13537 SourceLocation OrigLoc,
13538 NonTrivialCUnionContext UseContext,
13539 Sema &S)
13540 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13541
13542 void visitWithKind(QualType::DestructionKind DK, QualType QT,
13543 const FieldDecl *FD, bool InNonTrivialUnion) {
13544 if (const auto *AT = S.Context.getAsArrayType(QT))
13545 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13546 InNonTrivialUnion);
13547 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
13548 }
13549
13550 void visitARCStrong(QualType QT, const FieldDecl *FD,
13551 bool InNonTrivialUnion) {
13552 if (InNonTrivialUnion)
13553 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13554 << 1 << 1 << QT << FD->getName();
13555 }
13556
13557 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13558 if (InNonTrivialUnion)
13559 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13560 << 1 << 1 << QT << FD->getName();
13561 }
13562
13563 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13564 const auto *RD = QT->castAsRecordDecl();
13565 if (RD->isUnion()) {
13566 if (OrigLoc.isValid()) {
13567 bool IsUnion = false;
13568 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13569 IsUnion = OrigRD->isUnion();
13570 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13571 << 1 << OrigTy << IsUnion << UseContext;
13572 // Reset OrigLoc so that this diagnostic is emitted only once.
13573 OrigLoc = SourceLocation();
13574 }
13575 InNonTrivialUnion = true;
13576 }
13577
13578 if (InNonTrivialUnion)
13579 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13580 << 0 << 1 << QT.getUnqualifiedType() << "";
13581
13582 for (const FieldDecl *FD : RD->fields())
13583 if (!shouldIgnoreForRecordTriviality(FD))
13584 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13585 }
13586
13587 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13588 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
13589 bool InNonTrivialUnion) {}
13590
13591 // The non-trivial C union type or the struct/union type that contains a
13592 // non-trivial C union.
13593 QualType OrigTy;
13594 SourceLocation OrigLoc;
13595 NonTrivialCUnionContext UseContext;
13596 Sema &S;
13597};
13598
13599struct DiagNonTrivalCUnionCopyVisitor
13600 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
13601 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
13602
13603 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
13604 NonTrivialCUnionContext UseContext, Sema &S)
13605 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13606
13607 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
13608 const FieldDecl *FD, bool InNonTrivialUnion) {
13609 if (const auto *AT = S.Context.getAsArrayType(QT))
13610 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13611 InNonTrivialUnion);
13612 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
13613 }
13614
13615 void visitARCStrong(QualType QT, const FieldDecl *FD,
13616 bool InNonTrivialUnion) {
13617 if (InNonTrivialUnion)
13618 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13619 << 1 << 2 << QT << FD->getName();
13620 }
13621
13622 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13623 if (InNonTrivialUnion)
13624 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13625 << 1 << 2 << QT << FD->getName();
13626 }
13627
13628 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13629 const auto *RD = QT->castAsRecordDecl();
13630 if (RD->isUnion()) {
13631 if (OrigLoc.isValid()) {
13632 bool IsUnion = false;
13633 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13634 IsUnion = OrigRD->isUnion();
13635 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13636 << 2 << OrigTy << IsUnion << UseContext;
13637 // Reset OrigLoc so that this diagnostic is emitted only once.
13638 OrigLoc = SourceLocation();
13639 }
13640 InNonTrivialUnion = true;
13641 }
13642
13643 if (InNonTrivialUnion)
13644 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13645 << 0 << 2 << QT.getUnqualifiedType() << "";
13646
13647 for (const FieldDecl *FD : RD->fields())
13648 if (!shouldIgnoreForRecordTriviality(FD))
13649 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13650 }
13651
13652 void visitPtrAuth(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13653 if (InNonTrivialUnion)
13654 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13655 << 1 << 2 << QT << FD->getName();
13656 }
13657
13658 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13659 const FieldDecl *FD, bool InNonTrivialUnion) {}
13660 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13661 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13662 bool InNonTrivialUnion) {}
13663
13664 // The non-trivial C union type or the struct/union type that contains a
13665 // non-trivial C union.
13666 QualType OrigTy;
13667 SourceLocation OrigLoc;
13668 NonTrivialCUnionContext UseContext;
13669 Sema &S;
13670};
13671
13672} // namespace
13673
13675 NonTrivialCUnionContext UseContext,
13676 unsigned NonTrivialKind) {
13680 "shouldn't be called if type doesn't have a non-trivial C union");
13681
13682 if ((NonTrivialKind & NTCUK_Init) &&
13684 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
13685 .visit(QT, nullptr, false);
13686 if ((NonTrivialKind & NTCUK_Destruct) &&
13688 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
13689 .visit(QT, nullptr, false);
13690 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
13691 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
13692 .visit(QT, nullptr, false);
13693}
13694
13696 const VarDecl *Dcl) {
13697 if (!getLangOpts().CPlusPlus)
13698 return false;
13699
13700 // We only need to warn if the definition is in a header file, so wait to
13701 // diagnose until we've seen the definition.
13702 if (!Dcl->isThisDeclarationADefinition())
13703 return false;
13704
13705 // If an object is defined in a source file, its definition can't get
13706 // duplicated since it will never appear in more than one TU.
13708 return false;
13709
13710 // If the variable we're looking at is a static local, then we actually care
13711 // about the properties of the function containing it.
13712 const ValueDecl *Target = Dcl;
13713 // VarDecls and FunctionDecls have different functions for checking
13714 // inline-ness, and whether they were originally templated, so we have to
13715 // call the appropriate functions manually.
13716 bool TargetIsInline = Dcl->isInline();
13717 bool TargetWasTemplated =
13719
13720 // Update the Target and TargetIsInline property if necessary
13721 if (Dcl->isStaticLocal()) {
13722 const DeclContext *Ctx = Dcl->getDeclContext();
13723 if (!Ctx)
13724 return false;
13725
13726 const FunctionDecl *FunDcl =
13727 dyn_cast_if_present<FunctionDecl>(Ctx->getNonClosureAncestor());
13728 if (!FunDcl)
13729 return false;
13730
13731 Target = FunDcl;
13732 // IsInlined() checks for the C++ inline property
13733 TargetIsInline = FunDcl->isInlined();
13734 TargetWasTemplated =
13736 }
13737
13738 // Non-inline functions/variables can only legally appear in one TU
13739 // unless they were part of a template. Unfortunately, making complex
13740 // template instantiations visible is infeasible in practice, since
13741 // everything the template depends on also has to be visible. To avoid
13742 // giving impractical-to-fix warnings, don't warn if we're inside
13743 // something that was templated, even on inline stuff.
13744 if (!TargetIsInline || TargetWasTemplated)
13745 return false;
13746
13747 // If the object isn't hidden, the dynamic linker will prevent duplication.
13748 clang::LinkageInfo Lnk = Target->getLinkageAndVisibility();
13749
13750 // The target is "hidden" (from the dynamic linker) if:
13751 // 1. On posix, it has hidden visibility, or
13752 // 2. On windows, it has no import/export annotation, and neither does the
13753 // class which directly contains it.
13754 if (Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
13755 if (Target->hasAttr<DLLExportAttr>() || Target->hasAttr<DLLImportAttr>())
13756 return false;
13757
13758 // If the variable isn't directly annotated, check to see if it's a member
13759 // of an annotated class.
13760 const CXXRecordDecl *Ctx =
13761 dyn_cast<CXXRecordDecl>(Target->getDeclContext());
13762 if (Ctx && (Ctx->hasAttr<DLLExportAttr>() || Ctx->hasAttr<DLLImportAttr>()))
13763 return false;
13764
13765 } else if (Lnk.getVisibility() != HiddenVisibility) {
13766 // Posix case
13767 return false;
13768 }
13769
13770 // If the obj doesn't have external linkage, it's supposed to be duplicated.
13772 return false;
13773
13774 return true;
13775}
13776
13777// Determine whether the object seems mutable for the purpose of diagnosing
13778// possible unique object duplication, i.e. non-const-qualified, and
13779// not an always-constant type like a function.
13780// Not perfect: doesn't account for mutable members, for example, or
13781// elements of container types.
13782// For nested pointers, any individual level being non-const is sufficient.
13783static bool looksMutable(QualType T, const ASTContext &Ctx) {
13784 T = T.getNonReferenceType();
13785 if (T->isFunctionType())
13786 return false;
13787 if (!T.isConstant(Ctx))
13788 return true;
13789 if (T->isPointerType())
13790 return looksMutable(T->getPointeeType(), Ctx);
13791 return false;
13792}
13793
13795 // If this object has external linkage and hidden visibility, it might be
13796 // duplicated when built into a shared library, which causes problems if it's
13797 // mutable (since the copies won't be in sync) or its initialization has side
13798 // effects (since it will run once per copy instead of once globally).
13799
13800 // Don't diagnose if we're inside a template, because it's not practical to
13801 // fix the warning in most cases.
13802 if (!VD->isTemplated() &&
13804
13805 QualType Type = VD->getType();
13806 if (looksMutable(Type, VD->getASTContext())) {
13807 Diag(VD->getLocation(), diag::warn_possible_object_duplication_mutable)
13808 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
13809 }
13810
13811 // To keep false positives low, only warn if we're certain that the
13812 // initializer has side effects. Don't warn on operator new, since a mutable
13813 // pointer will trigger the previous warning, and an immutable pointer
13814 // getting duplicated just results in a little extra memory usage.
13815 const Expr *Init = VD->getAnyInitializer();
13816 if (Init &&
13817 Init->HasSideEffects(VD->getASTContext(),
13818 /*IncludePossibleEffects=*/false) &&
13819 !isa<CXXNewExpr>(Init->IgnoreParenImpCasts())) {
13820 Diag(Init->getExprLoc(), diag::warn_possible_object_duplication_init)
13821 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
13822 }
13823 }
13824}
13825
13827 llvm::scope_exit ResetDeclForInitializer([this]() {
13828 if (!this->ExprEvalContexts.empty())
13829 this->ExprEvalContexts.back().DeclForInitializer = nullptr;
13830 });
13831
13832 // If there is no declaration, there was an error parsing it. Just ignore
13833 // the initializer.
13834 if (!RealDecl) {
13835 return;
13836 }
13837
13838 if (auto *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
13839 if (!Method->isInvalidDecl()) {
13840 // Pure-specifiers are handled in ActOnPureSpecifier.
13841 Diag(Method->getLocation(), diag::err_member_function_initialization)
13842 << Method->getDeclName() << Init->getSourceRange();
13843 Method->setInvalidDecl();
13844 }
13845 return;
13846 }
13847
13848 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
13849 if (!VDecl) {
13850 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
13851 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
13852 RealDecl->setInvalidDecl();
13853 return;
13854 }
13855
13856 if (VDecl->isInvalidDecl()) {
13857 ExprResult Recovery =
13858 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), {Init});
13859 if (Expr *E = Recovery.get())
13860 VDecl->setInit(E);
13861 return;
13862 }
13863
13864 // WebAssembly tables can't be used to initialise a variable.
13865 if (!Init->getType().isNull() && Init->getType()->isWebAssemblyTableType()) {
13866 Diag(Init->getExprLoc(), diag::err_wasm_table_art) << 0;
13867 VDecl->setInvalidDecl();
13868 return;
13869 }
13870
13871 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
13872 if (VDecl->getType()->isUndeducedType()) {
13873 if (Init->containsErrors()) {
13874 // Invalidate the decl as we don't know the type for recovery-expr yet.
13875 RealDecl->setInvalidDecl();
13876 VDecl->setInit(Init);
13877 return;
13878 }
13879
13881 assert(VDecl->isInvalidDecl() &&
13882 "decl should be invalidated when deduce fails");
13883 if (auto *RecoveryExpr =
13884 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), {Init})
13885 .get())
13886 VDecl->setInit(RecoveryExpr);
13887 return;
13888 }
13889 }
13890
13891 this->CheckAttributesOnDeducedType(RealDecl);
13892
13893 // dllimport cannot be used on variable definitions.
13894 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
13895 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
13896 VDecl->setInvalidDecl();
13897 return;
13898 }
13899
13900 // C99 6.7.8p5. If the declaration of an identifier has block scope, and
13901 // the identifier has external or internal linkage, the declaration shall
13902 // have no initializer for the identifier.
13903 // C++14 [dcl.init]p5 is the same restriction for C++.
13904 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
13905 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
13906 VDecl->setInvalidDecl();
13907 return;
13908 }
13909
13910 if (!VDecl->getType()->isDependentType()) {
13911 // A definition must end up with a complete type, which means it must be
13912 // complete with the restriction that an array type might be completed by
13913 // the initializer; note that later code assumes this restriction.
13914 QualType BaseDeclType = VDecl->getType();
13915 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
13916 BaseDeclType = Array->getElementType();
13917 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
13918 diag::err_typecheck_decl_incomplete_type)) {
13919 RealDecl->setInvalidDecl();
13920 return;
13921 }
13922
13923 // The variable can not have an abstract class type.
13924 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
13925 diag::err_abstract_type_in_decl,
13927 VDecl->setInvalidDecl();
13928 }
13929
13930 // C++ [module.import/6]
13931 // ...
13932 // A header unit shall not contain a definition of a non-inline function or
13933 // variable whose name has external linkage.
13934 //
13935 // We choose to allow weak & selectany definitions, as they are common in
13936 // headers, and have semantics similar to inline definitions which are allowed
13937 // in header units.
13938 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
13939 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
13940 VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() &&
13941 !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(VDecl) &&
13943 !(VDecl->hasAttr<SelectAnyAttr>() || VDecl->hasAttr<WeakAttr>())) {
13944 Diag(VDecl->getLocation(), diag::err_extern_def_in_header_unit);
13945 VDecl->setInvalidDecl();
13946 }
13947
13948 // If adding the initializer will turn this declaration into a definition,
13949 // and we already have a definition for this variable, diagnose or otherwise
13950 // handle the situation.
13951 if (VarDecl *Def = VDecl->getDefinition())
13952 if (Def != VDecl &&
13953 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
13955 checkVarDeclRedefinition(Def, VDecl))
13956 return;
13957
13958 if (getLangOpts().CPlusPlus) {
13959 // C++ [class.static.data]p4
13960 // If a static data member is of const integral or const
13961 // enumeration type, its declaration in the class definition can
13962 // specify a constant-initializer which shall be an integral
13963 // constant expression (5.19). In that case, the member can appear
13964 // in integral constant expressions. The member shall still be
13965 // defined in a namespace scope if it is used in the program and the
13966 // namespace scope definition shall not contain an initializer.
13967 //
13968 // We already performed a redefinition check above, but for static
13969 // data members we also need to check whether there was an in-class
13970 // declaration with an initializer.
13971 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
13972 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
13973 << VDecl->getDeclName();
13974 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
13975 diag::note_previous_initializer)
13976 << 0;
13977 return;
13978 }
13979
13981 VDecl->setInvalidDecl();
13982 return;
13983 }
13984 }
13985
13986 // If the variable has an initializer and local storage, check whether
13987 // anything jumps over the initialization.
13988 if (VDecl->hasLocalStorage())
13990
13991 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
13992 // a kernel function cannot be initialized."
13993 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
13994 Diag(VDecl->getLocation(), diag::err_local_cant_init);
13995 VDecl->setInvalidDecl();
13996 return;
13997 }
13998
13999 // The LoaderUninitialized attribute acts as a definition (of undef).
14000 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
14001 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
14002 VDecl->setInvalidDecl();
14003 return;
14004 }
14005
14006 if (getLangOpts().HLSL)
14007 if (!HLSL().handleInitialization(VDecl, Init))
14008 return;
14009
14010 // Get the decls type and save a reference for later, since
14011 // CheckInitializerTypes may change it.
14012 QualType DclT = VDecl->getType(), SavT = DclT;
14013
14014 // Expressions default to 'id' when we're in a debugger
14015 // and we are assigning it to a variable of Objective-C pointer type.
14016 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
14017 Init->getType() == Context.UnknownAnyTy) {
14019 if (!Result.isUsable()) {
14020 VDecl->setInvalidDecl();
14021 return;
14022 }
14023 Init = Result.get();
14024 }
14025
14026 // Perform the initialization.
14027 bool InitializedFromParenListExpr = false;
14028 bool IsParenListInit = false;
14029 if (!VDecl->isInvalidDecl()) {
14032 VDecl->getLocation(), DirectInit, Init);
14033
14034 MultiExprArg Args = Init;
14035 if (auto *CXXDirectInit = dyn_cast<ParenListExpr>(Init)) {
14036 Args =
14037 MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
14038 InitializedFromParenListExpr = true;
14039 } else if (auto *CXXDirectInit = dyn_cast<CXXParenListInitExpr>(Init)) {
14040 Args = CXXDirectInit->getInitExprs();
14041 InitializedFromParenListExpr = true;
14042 }
14043
14044 InitializationSequence InitSeq(*this, Entity, Kind, Args,
14045 /*TopLevelOfInitList=*/false,
14046 /*TreatUnavailableAsInvalid=*/false);
14047 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
14048 if (!Result.isUsable()) {
14049 // If the provided initializer fails to initialize the var decl,
14050 // we attach a recovery expr for better recovery.
14051 auto RecoveryExpr =
14052 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
14053 if (RecoveryExpr.get())
14054 VDecl->setInit(RecoveryExpr.get());
14055 // In general, for error recovery purposes, the initializer doesn't play
14056 // part in the valid bit of the declaration. There are a few exceptions:
14057 // 1) if the var decl has a deduced auto type, and the type cannot be
14058 // deduced by an invalid initializer;
14059 // 2) if the var decl is a decomposition decl with a non-deduced type,
14060 // and the initialization fails (e.g. `int [a] = {1, 2};`);
14061 // Case 1) was already handled elsewhere.
14062 if (isa<DecompositionDecl>(VDecl)) // Case 2)
14063 VDecl->setInvalidDecl();
14064 return;
14065 }
14066
14067 Init = Result.getAs<Expr>();
14068 IsParenListInit = !InitSeq.steps().empty() &&
14069 InitSeq.step_begin()->Kind ==
14071 QualType VDeclType = VDecl->getType();
14072 if (!Init->getType().isNull() && !Init->getType()->isDependentType() &&
14073 !VDeclType->isDependentType() &&
14074 Context.getAsIncompleteArrayType(VDeclType) &&
14075 Context.getAsIncompleteArrayType(Init->getType())) {
14076 // Bail out if it is not possible to deduce array size from the
14077 // initializer.
14078 Diag(VDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)
14079 << VDeclType;
14080 VDecl->setInvalidDecl();
14081 return;
14082 }
14083 }
14084
14085 // Check for self-references within variable initializers.
14086 // Variables declared within a function/method body (except for references)
14087 // are handled by a dataflow analysis.
14088 // This is undefined behavior in C++, but valid in C.
14089 if (getLangOpts().CPlusPlus)
14090 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
14091 VDecl->getType()->isReferenceType())
14092 CheckSelfReference(*this, RealDecl, Init, DirectInit);
14093
14094 // If the type changed, it means we had an incomplete type that was
14095 // completed by the initializer. For example:
14096 // int ary[] = { 1, 3, 5 };
14097 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
14098 if (!VDecl->isInvalidDecl() && (DclT != SavT))
14099 VDecl->setType(DclT);
14100
14101 if (!VDecl->isInvalidDecl()) {
14102 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
14103
14104 if (VDecl->hasAttr<BlocksAttr>())
14105 ObjC().checkRetainCycles(VDecl, Init);
14106
14107 // It is safe to assign a weak reference into a strong variable.
14108 // Although this code can still have problems:
14109 // id x = self.weakProp;
14110 // id y = self.weakProp;
14111 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14112 // paths through the function. This should be revisited if
14113 // -Wrepeated-use-of-weak is made flow-sensitive.
14114 if (FunctionScopeInfo *FSI = getCurFunction())
14115 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
14117 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
14118 Init->getBeginLoc()))
14119 FSI->markSafeWeakUse(Init);
14120 }
14121
14122 // The initialization is usually a full-expression.
14123 //
14124 // FIXME: If this is a braced initialization of an aggregate, it is not
14125 // an expression, and each individual field initializer is a separate
14126 // full-expression. For instance, in:
14127 //
14128 // struct Temp { ~Temp(); };
14129 // struct S { S(Temp); };
14130 // struct T { S a, b; } t = { Temp(), Temp() }
14131 //
14132 // we should destroy the first Temp before constructing the second.
14135 /*DiscardedValue*/ false, VDecl->isConstexpr());
14136 if (!Result.isUsable()) {
14137 VDecl->setInvalidDecl();
14138 return;
14139 }
14140 Init = Result.get();
14141
14142 // Attach the initializer to the decl.
14143 VDecl->setInit(Init);
14144
14145 if (VDecl->isLocalVarDecl()) {
14146 // Don't check the initializer if the declaration is malformed.
14147 if (VDecl->isInvalidDecl()) {
14148 // do nothing
14149
14150 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
14151 // This is true even in C++ for OpenCL.
14152 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
14154
14155 // Otherwise, C++ does not restrict the initializer.
14156 } else if (getLangOpts().CPlusPlus) {
14157 // do nothing
14158
14159 // C99 6.7.8p4: All the expressions in an initializer for an object that has
14160 // static storage duration shall be constant expressions or string literals.
14161 } else if (VDecl->getStorageClass() == SC_Static) {
14162 // Avoid evaluating the initializer twice for constexpr variables. It will
14163 // be evaluated later.
14164 if (!VDecl->isConstexpr())
14166
14167 // C89 is stricter than C99 for aggregate initializers.
14168 // C89 6.5.7p3: All the expressions [...] in an initializer list
14169 // for an object that has aggregate or union type shall be
14170 // constant expressions.
14171 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
14173 CheckForConstantInitializer(Init, diag::ext_aggregate_init_not_constant);
14174 }
14175
14176 if (auto *E = dyn_cast<ExprWithCleanups>(Init))
14177 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
14178 if (VDecl->hasLocalStorage())
14179 BE->getBlockDecl()->setCanAvoidCopyToHeap();
14180 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
14181 VDecl->getLexicalDeclContext()->isRecord()) {
14182 // This is an in-class initialization for a static data member, e.g.,
14183 //
14184 // struct S {
14185 // static const int value = 17;
14186 // };
14187
14188 // C++ [class.mem]p4:
14189 // A member-declarator can contain a constant-initializer only
14190 // if it declares a static member (9.4) of const integral or
14191 // const enumeration type, see 9.4.2.
14192 //
14193 // C++11 [class.static.data]p3:
14194 // If a non-volatile non-inline const static data member is of integral
14195 // or enumeration type, its declaration in the class definition can
14196 // specify a brace-or-equal-initializer in which every initializer-clause
14197 // that is an assignment-expression is a constant expression. A static
14198 // data member of literal type can be declared in the class definition
14199 // with the constexpr specifier; if so, its declaration shall specify a
14200 // brace-or-equal-initializer in which every initializer-clause that is
14201 // an assignment-expression is a constant expression.
14202
14203 // Do nothing on dependent types.
14204 if (DclT->isDependentType()) {
14205
14206 // Allow any 'static constexpr' members, whether or not they are of literal
14207 // type. We separately check that every constexpr variable is of literal
14208 // type.
14209 } else if (VDecl->isConstexpr()) {
14210
14211 // Require constness.
14212 } else if (!DclT.isConstQualified()) {
14213 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
14214 << Init->getSourceRange();
14215 VDecl->setInvalidDecl();
14216
14217 // We allow integer constant expressions in all cases.
14218 } else if (DclT->isIntegralOrEnumerationType()) {
14220 // In C++11, a non-constexpr const static data member with an
14221 // in-class initializer cannot be volatile.
14222 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
14223
14224 // We allow foldable floating-point constants as an extension.
14225 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
14226 // In C++98, this is a GNU extension. In C++11, it is not, but we support
14227 // it anyway and provide a fixit to add the 'constexpr'.
14228 if (getLangOpts().CPlusPlus11) {
14229 Diag(VDecl->getLocation(),
14230 diag::ext_in_class_initializer_float_type_cxx11)
14231 << DclT << Init->getSourceRange();
14232 Diag(VDecl->getBeginLoc(),
14233 diag::note_in_class_initializer_float_type_cxx11)
14234 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
14235 } else {
14236 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
14237 << DclT << Init->getSourceRange();
14238
14239 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
14240 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
14241 << Init->getSourceRange();
14242 VDecl->setInvalidDecl();
14243 }
14244 }
14245
14246 // Suggest adding 'constexpr' in C++11 for literal types.
14247 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
14248 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
14249 << DclT << Init->getSourceRange()
14250 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
14251 VDecl->setConstexpr(true);
14252
14253 } else {
14254 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
14255 << DclT << Init->getSourceRange();
14256 VDecl->setInvalidDecl();
14257 }
14258 } else if (VDecl->isFileVarDecl()) {
14259 // In C, extern is typically used to avoid tentative definitions when
14260 // declaring variables in headers, but adding an initializer makes it a
14261 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
14262 // In C++, extern is often used to give implicitly static const variables
14263 // external linkage, so don't warn in that case. If selectany is present,
14264 // this might be header code intended for C and C++ inclusion, so apply the
14265 // C++ rules.
14266 if (VDecl->getStorageClass() == SC_Extern &&
14267 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
14268 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
14269 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
14271 Diag(VDecl->getLocation(), diag::warn_extern_init);
14272
14273 // In Microsoft C++ mode, a const variable defined in namespace scope has
14274 // external linkage by default if the variable is declared with
14275 // __declspec(dllexport).
14276 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14278 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
14279 VDecl->setStorageClass(SC_Extern);
14280
14281 // C99 6.7.8p4. All file scoped initializers need to be constant.
14282 // Avoid duplicate diagnostics for constexpr variables.
14283 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
14284 !VDecl->isConstexpr())
14286 }
14287
14288 QualType InitType = Init->getType();
14289 if (!InitType.isNull() &&
14293
14294 // We will represent direct-initialization similarly to copy-initialization:
14295 // int x(1); -as-> int x = 1;
14296 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
14297 //
14298 // Clients that want to distinguish between the two forms, can check for
14299 // direct initializer using VarDecl::getInitStyle().
14300 // A major benefit is that clients that don't particularly care about which
14301 // exactly form was it (like the CodeGen) can handle both cases without
14302 // special case code.
14303
14304 // C++ 8.5p11:
14305 // The form of initialization (using parentheses or '=') matters
14306 // when the entity being initialized has class type.
14307 if (InitializedFromParenListExpr) {
14308 assert(DirectInit && "Call-style initializer must be direct init.");
14309 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
14311 } else if (DirectInit) {
14312 // This must be list-initialization. No other way is direct-initialization.
14314 }
14315
14316 if (LangOpts.OpenMP &&
14317 (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&
14318 VDecl->isFileVarDecl())
14319 DeclsToCheckForDeferredDiags.insert(VDecl);
14321
14322 if (LangOpts.OpenACC && !InitType.isNull())
14323 OpenACC().ActOnVariableInit(VDecl, InitType);
14324}
14325
14327 // Our main concern here is re-establishing invariants like "a
14328 // variable's type is either dependent or complete".
14329 if (!D || D->isInvalidDecl()) return;
14330
14331 VarDecl *VD = dyn_cast<VarDecl>(D);
14332 if (!VD) return;
14333
14334 // Bindings are not usable if we can't make sense of the initializer.
14335 if (auto *DD = dyn_cast<DecompositionDecl>(D))
14336 for (auto *BD : DD->bindings())
14337 BD->setInvalidDecl();
14338
14339 // Auto types are meaningless if we can't make sense of the initializer.
14340 if (VD->getType()->isUndeducedType()) {
14341 D->setInvalidDecl();
14342 return;
14343 }
14344
14345 QualType Ty = VD->getType();
14346 if (Ty->isDependentType()) return;
14347
14348 // Require a complete type.
14350 Context.getBaseElementType(Ty),
14351 diag::err_typecheck_decl_incomplete_type)) {
14352 VD->setInvalidDecl();
14353 return;
14354 }
14355
14356 // Require a non-abstract type.
14357 if (RequireNonAbstractType(VD->getLocation(), Ty,
14358 diag::err_abstract_type_in_decl,
14360 VD->setInvalidDecl();
14361 return;
14362 }
14363
14364 // Don't bother complaining about constructors or destructors,
14365 // though.
14366}
14367
14369 // If there is no declaration, there was an error parsing it. Just ignore it.
14370 if (!RealDecl)
14371 return;
14372
14373 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
14374 QualType Type = Var->getType();
14375
14376 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
14377 if (isa<DecompositionDecl>(RealDecl)) {
14378 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
14379 Var->setInvalidDecl();
14380 return;
14381 }
14382
14383 if (Type->isUndeducedType() &&
14384 DeduceVariableDeclarationType(Var, false, nullptr))
14385 return;
14386
14387 this->CheckAttributesOnDeducedType(RealDecl);
14388
14389 // C++11 [class.static.data]p3: A static data member can be declared with
14390 // the constexpr specifier; if so, its declaration shall specify
14391 // a brace-or-equal-initializer.
14392 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
14393 // the definition of a variable [...] or the declaration of a static data
14394 // member.
14395 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
14396 !Var->isThisDeclarationADemotedDefinition()) {
14397 if (Var->isStaticDataMember()) {
14398 // C++1z removes the relevant rule; the in-class declaration is always
14399 // a definition there.
14400 if (!getLangOpts().CPlusPlus17 &&
14401 !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14402 Diag(Var->getLocation(),
14403 diag::err_constexpr_static_mem_var_requires_init)
14404 << Var;
14405 Var->setInvalidDecl();
14406 return;
14407 }
14408 } else {
14409 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
14410 Var->setInvalidDecl();
14411 return;
14412 }
14413 }
14414
14415 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
14416 // be initialized.
14417 if (!Var->isInvalidDecl() &&
14418 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
14419 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
14420 bool HasConstExprDefaultConstructor = false;
14421 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14422 for (auto *Ctor : RD->ctors()) {
14423 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
14424 Ctor->getMethodQualifiers().getAddressSpace() ==
14426 HasConstExprDefaultConstructor = true;
14427 }
14428 }
14429 }
14430 if (!HasConstExprDefaultConstructor) {
14431 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
14432 Var->setInvalidDecl();
14433 return;
14434 }
14435 }
14436
14437 // HLSL variable with the `vk::constant_id` attribute must be initialized.
14438 if (!Var->isInvalidDecl() && Var->hasAttr<HLSLVkConstantIdAttr>()) {
14439 Diag(Var->getLocation(), diag::err_specialization_const);
14440 Var->setInvalidDecl();
14441 return;
14442 }
14443
14444 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
14445 if (Var->getStorageClass() == SC_Extern) {
14446 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
14447 << Var;
14448 Var->setInvalidDecl();
14449 return;
14450 }
14451 if (RequireCompleteType(Var->getLocation(), Var->getType(),
14452 diag::err_typecheck_decl_incomplete_type)) {
14453 Var->setInvalidDecl();
14454 return;
14455 }
14456 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14457 if (!RD->hasTrivialDefaultConstructor()) {
14458 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
14459 Var->setInvalidDecl();
14460 return;
14461 }
14462 }
14463 // The declaration is uninitialized, no need for further checks.
14464 return;
14465 }
14466
14467 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
14468 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
14469 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
14470 checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
14472 NTCUK_Init);
14473
14474 switch (DefKind) {
14476 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
14477 break;
14478
14479 // We have an out-of-line definition of a static data member
14480 // that has an in-class initializer, so we type-check this like
14481 // a declaration.
14482 //
14483 [[fallthrough]];
14484
14486 // It's only a declaration.
14487
14488 // Block scope. C99 6.7p7: If an identifier for an object is
14489 // declared with no linkage (C99 6.2.2p6), the type for the
14490 // object shall be complete.
14491 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
14492 !Var->hasLinkage() && !Var->isInvalidDecl() &&
14493 RequireCompleteType(Var->getLocation(), Type,
14494 diag::err_typecheck_decl_incomplete_type))
14495 Var->setInvalidDecl();
14496
14497 // Make sure that the type is not abstract.
14498 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14499 RequireNonAbstractType(Var->getLocation(), Type,
14500 diag::err_abstract_type_in_decl,
14502 Var->setInvalidDecl();
14503 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14504 Var->getStorageClass() == SC_PrivateExtern) {
14505 Diag(Var->getLocation(), diag::warn_private_extern);
14506 Diag(Var->getLocation(), diag::note_private_extern);
14507 }
14508
14509 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
14510 !Var->isInvalidDecl())
14511 ExternalDeclarations.push_back(Var);
14512
14513 return;
14514
14516 // File scope. C99 6.9.2p2: A declaration of an identifier for an
14517 // object that has file scope without an initializer, and without a
14518 // storage-class specifier or with the storage-class specifier "static",
14519 // constitutes a tentative definition. Note: A tentative definition with
14520 // external linkage is valid (C99 6.2.2p5).
14521 if (!Var->isInvalidDecl()) {
14522 if (const IncompleteArrayType *ArrayT
14523 = Context.getAsIncompleteArrayType(Type)) {
14525 Var->getLocation(), ArrayT->getElementType(),
14526 diag::err_array_incomplete_or_sizeless_type))
14527 Var->setInvalidDecl();
14528 }
14529 if (Var->getStorageClass() == SC_Static) {
14530 // C99 6.9.2p3: If the declaration of an identifier for an object is
14531 // a tentative definition and has internal linkage (C99 6.2.2p3), the
14532 // declared type shall not be an incomplete type.
14533 // NOTE: code such as the following
14534 // static struct s;
14535 // struct s { int a; };
14536 // is accepted by gcc. Hence here we issue a warning instead of
14537 // an error and we do not invalidate the static declaration.
14538 // NOTE: to avoid multiple warnings, only check the first declaration.
14539 if (Var->isFirstDecl())
14540 RequireCompleteType(Var->getLocation(), Type,
14541 diag::ext_typecheck_decl_incomplete_type,
14542 Type->isArrayType());
14543 }
14544 }
14545
14546 // Record the tentative definition; we're done.
14547 if (!Var->isInvalidDecl())
14548 TentativeDefinitions.push_back(Var);
14549 return;
14550 }
14551
14552 // Provide a specific diagnostic for uninitialized variable definitions
14553 // with incomplete array type, unless it is a global unbounded HLSL resource
14554 // array.
14555 if (Type->isIncompleteArrayType() &&
14556 !(getLangOpts().HLSL && Var->hasGlobalStorage() &&
14558 if (Var->isConstexpr())
14559 Diag(Var->getLocation(), diag::err_constexpr_var_requires_const_init)
14560 << Var;
14561 else
14562 Diag(Var->getLocation(),
14563 diag::err_typecheck_incomplete_array_needs_initializer);
14564 Var->setInvalidDecl();
14565 return;
14566 }
14567
14568 // Provide a specific diagnostic for uninitialized variable
14569 // definitions with reference type.
14570 if (Type->isReferenceType()) {
14571 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
14572 << Var << SourceRange(Var->getLocation(), Var->getLocation());
14573 return;
14574 }
14575
14576 // Do not attempt to type-check the default initializer for a
14577 // variable with dependent type.
14578 if (Type->isDependentType())
14579 return;
14580
14581 if (Var->isInvalidDecl())
14582 return;
14583
14584 if (!Var->hasAttr<AliasAttr>()) {
14585 if (RequireCompleteType(Var->getLocation(),
14586 Context.getBaseElementType(Type),
14587 diag::err_typecheck_decl_incomplete_type)) {
14588 Var->setInvalidDecl();
14589 return;
14590 }
14591 } else {
14592 return;
14593 }
14594
14595 // The variable can not have an abstract class type.
14596 if (RequireNonAbstractType(Var->getLocation(), Type,
14597 diag::err_abstract_type_in_decl,
14599 Var->setInvalidDecl();
14600 return;
14601 }
14602
14603 // In C, if the definition is const-qualified and has no initializer, it
14604 // is left uninitialized unless it has static or thread storage duration.
14605 if (!getLangOpts().CPlusPlus && Type.isConstQualified()) {
14606 unsigned DiagID = diag::warn_default_init_const_unsafe;
14607 if (Var->getStorageDuration() == SD_Static ||
14608 Var->getStorageDuration() == SD_Thread)
14609 DiagID = diag::warn_default_init_const;
14610
14611 bool EmitCppCompat = !Diags.isIgnored(
14612 diag::warn_cxx_compat_hack_fake_diagnostic_do_not_emit,
14613 Var->getLocation());
14614
14615 Diag(Var->getLocation(), DiagID) << Type << EmitCppCompat;
14616 }
14617
14618 // Check for jumps past the implicit initializer. C++0x
14619 // clarifies that this applies to a "variable with automatic
14620 // storage duration", not a "local variable".
14621 // C++11 [stmt.dcl]p3
14622 // A program that jumps from a point where a variable with automatic
14623 // storage duration is not in scope to a point where it is in scope is
14624 // ill-formed unless the variable has scalar type, class type with a
14625 // trivial default constructor and a trivial destructor, a cv-qualified
14626 // version of one of these types, or an array of one of the preceding
14627 // types and is declared without an initializer.
14628 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
14629 if (const auto *CXXRecord =
14630 Context.getBaseElementType(Type)->getAsCXXRecordDecl()) {
14631 // Mark the function (if we're in one) for further checking even if the
14632 // looser rules of C++11 do not require such checks, so that we can
14633 // diagnose incompatibilities with C++98.
14634 if (!CXXRecord->isPOD())
14636 }
14637 }
14638 // In OpenCL, we can't initialize objects in the __local address space,
14639 // even implicitly, so don't synthesize an implicit initializer.
14640 if (getLangOpts().OpenCL &&
14641 Var->getType().getAddressSpace() == LangAS::opencl_local)
14642 return;
14643
14644 // Handle HLSL uninitialized decls
14645 if (getLangOpts().HLSL && HLSL().ActOnUninitializedVarDecl(Var))
14646 return;
14647
14648 // HLSL input & push-constant variables are expected to be externally
14649 // initialized, even when marked `static`.
14650 if (getLangOpts().HLSL &&
14651 hlsl::isInitializedByPipeline(Var->getType().getAddressSpace()))
14652 return;
14653
14654 // C++03 [dcl.init]p9:
14655 // If no initializer is specified for an object, and the
14656 // object is of (possibly cv-qualified) non-POD class type (or
14657 // array thereof), the object shall be default-initialized; if
14658 // the object is of const-qualified type, the underlying class
14659 // type shall have a user-declared default
14660 // constructor. Otherwise, if no initializer is specified for
14661 // a non- static object, the object and its subobjects, if
14662 // any, have an indeterminate initial value); if the object
14663 // or any of its subobjects are of const-qualified type, the
14664 // program is ill-formed.
14665 // C++0x [dcl.init]p11:
14666 // If no initializer is specified for an object, the object is
14667 // default-initialized; [...].
14670 = InitializationKind::CreateDefault(Var->getLocation());
14671
14672 InitializationSequence InitSeq(*this, Entity, Kind, {});
14673 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, {});
14674
14675 if (Init.get()) {
14676 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
14677 // This is important for template substitution.
14678 Var->setInitStyle(VarDecl::CallInit);
14679 } else if (Init.isInvalid()) {
14680 // If default-init fails, attach a recovery-expr initializer to track
14681 // that initialization was attempted and failed.
14682 auto RecoveryExpr =
14683 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
14684 if (RecoveryExpr.get())
14685 Var->setInit(RecoveryExpr.get());
14686 }
14687
14689 }
14690}
14691
14693 // If there is no declaration, there was an error parsing it. Ignore it.
14694 if (!D)
14695 return;
14696
14697 VarDecl *VD = dyn_cast<VarDecl>(D);
14698 if (!VD) {
14699 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
14700 D->setInvalidDecl();
14701 return;
14702 }
14703
14704 VD->setCXXForRangeDecl(true);
14705
14706 // for-range-declaration cannot be given a storage class specifier.
14707 int Error = -1;
14708 switch (VD->getStorageClass()) {
14709 case SC_None:
14710 break;
14711 case SC_Extern:
14712 Error = 0;
14713 break;
14714 case SC_Static:
14715 Error = 1;
14716 break;
14717 case SC_PrivateExtern:
14718 Error = 2;
14719 break;
14720 case SC_Auto:
14721 Error = 3;
14722 break;
14723 case SC_Register:
14724 Error = 4;
14725 break;
14726 }
14727
14728 // for-range-declaration cannot be given a storage class specifier con't.
14729 switch (VD->getTSCSpec()) {
14730 case TSCS_thread_local:
14731 Error = 6;
14732 break;
14733 case TSCS___thread:
14734 case TSCS__Thread_local:
14735 case TSCS_unspecified:
14736 break;
14737 }
14738
14739 if (Error != -1) {
14740 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
14741 << VD << Error;
14742 D->setInvalidDecl();
14743 }
14744}
14745
14747 IdentifierInfo *Ident,
14748 ParsedAttributes &Attrs) {
14749 // C++1y [stmt.iter]p1:
14750 // A range-based for statement of the form
14751 // for ( for-range-identifier : for-range-initializer ) statement
14752 // is equivalent to
14753 // for ( auto&& for-range-identifier : for-range-initializer ) statement
14754 DeclSpec DS(Attrs.getPool().getFactory());
14755
14756 const char *PrevSpec;
14757 unsigned DiagID;
14758 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
14760
14762 D.SetIdentifier(Ident, IdentLoc);
14763 D.takeAttributesAppending(Attrs);
14764
14765 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
14766 IdentLoc);
14767 Decl *Var = ActOnDeclarator(S, D);
14768 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
14770 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
14771 Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
14772 : IdentLoc);
14773}
14774
14777 return;
14778 auto *Attr = LifetimeBoundAttr::CreateImplicit(Context, MD->getLocation());
14779 QualType MethodType = MD->getType();
14780 QualType AttributedType =
14781 Context.getAttributedType(Attr, MethodType, MethodType);
14782 TypeLocBuilder TLB;
14783 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
14784 TLB.pushFullCopy(TSI->getTypeLoc());
14785 AttributedTypeLoc TyLoc = TLB.push<AttributedTypeLoc>(AttributedType);
14786 TyLoc.setAttr(Attr);
14787 MD->setType(AttributedType);
14788 MD->setTypeSourceInfo(TLB.getTypeSourceInfo(Context, AttributedType));
14789}
14790
14792 if (var->isInvalidDecl()) return;
14793
14795
14796 if (getLangOpts().OpenCL) {
14797 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
14798 // initialiser
14799 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
14800 !var->hasInit()) {
14801 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
14802 << 1 /*Init*/;
14803 var->setInvalidDecl();
14804 return;
14805 }
14806 }
14807
14808 // In Objective-C, don't allow jumps past the implicit initialization of a
14809 // local retaining variable.
14810 if (getLangOpts().ObjC &&
14811 var->hasLocalStorage()) {
14812 switch (var->getType().getObjCLifetime()) {
14816 break;
14817
14821 break;
14822 }
14823 }
14824
14825 if (var->hasLocalStorage() &&
14826 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
14828
14829 // Warn about externally-visible variables being defined without a
14830 // prior declaration. We only want to do this for global
14831 // declarations, but we also specifically need to avoid doing it for
14832 // class members because the linkage of an anonymous class can
14833 // change if it's later given a typedef name.
14834 if (var->isThisDeclarationADefinition() &&
14835 var->getDeclContext()->getRedeclContext()->isFileContext() &&
14836 var->isExternallyVisible() && var->hasLinkage() &&
14837 !var->isInline() && !var->getDescribedVarTemplate() &&
14838 var->getStorageClass() != SC_Register &&
14840 !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
14841 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
14842 var->getLocation())) {
14843 // Find a previous declaration that's not a definition.
14844 VarDecl *prev = var->getPreviousDecl();
14845 while (prev && prev->isThisDeclarationADefinition())
14846 prev = prev->getPreviousDecl();
14847
14848 if (!prev) {
14849 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
14850 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14851 << /* variable */ 0;
14852 }
14853 }
14854
14855 // Cache the result of checking for constant initialization.
14856 std::optional<bool> CacheHasConstInit;
14857 const Expr *CacheCulprit = nullptr;
14858 auto checkConstInit = [&]() mutable {
14859 const Expr *Init = var->getInit();
14860 if (Init->isInstantiationDependent())
14861 return true;
14862
14863 if (!CacheHasConstInit)
14864 CacheHasConstInit = var->getInit()->isConstantInitializer(
14865 Context, var->getType()->isReferenceType(), &CacheCulprit);
14866 return *CacheHasConstInit;
14867 };
14868
14869 if (var->getTLSKind() == VarDecl::TLS_Static) {
14870 if (var->getType().isDestructedType()) {
14871 // GNU C++98 edits for __thread, [basic.start.term]p3:
14872 // The type of an object with thread storage duration shall not
14873 // have a non-trivial destructor.
14874 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
14876 Diag(var->getLocation(), diag::note_use_thread_local);
14877 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
14878 if (!checkConstInit()) {
14879 // GNU C++98 edits for __thread, [basic.start.init]p4:
14880 // An object of thread storage duration shall not require dynamic
14881 // initialization.
14882 // FIXME: Need strict checking here.
14883 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
14884 << CacheCulprit->getSourceRange();
14886 Diag(var->getLocation(), diag::note_use_thread_local);
14887 }
14888 }
14889 }
14890
14891
14892 if (!var->getType()->isStructureType() && var->hasInit() &&
14893 isa<InitListExpr>(var->getInit())) {
14894 const auto *ILE = cast<InitListExpr>(var->getInit());
14895 unsigned NumInits = ILE->getNumInits();
14896 if (NumInits > 2)
14897 for (unsigned I = 0; I < NumInits; ++I) {
14898 const auto *Init = ILE->getInit(I);
14899 if (!Init)
14900 break;
14901 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14902 if (!SL)
14903 break;
14904
14905 unsigned NumConcat = SL->getNumConcatenated();
14906 // Diagnose missing comma in string array initialization.
14907 // Do not warn when all the elements in the initializer are concatenated
14908 // together. Do not warn for macros too.
14909 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
14910 bool OnlyOneMissingComma = true;
14911 for (unsigned J = I + 1; J < NumInits; ++J) {
14912 const auto *Init = ILE->getInit(J);
14913 if (!Init)
14914 break;
14915 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14916 if (!SLJ || SLJ->getNumConcatenated() > 1) {
14917 OnlyOneMissingComma = false;
14918 break;
14919 }
14920 }
14921
14922 if (OnlyOneMissingComma) {
14924 for (unsigned i = 0; i < NumConcat - 1; ++i)
14925 Hints.push_back(FixItHint::CreateInsertion(
14926 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
14927
14928 Diag(SL->getStrTokenLoc(1),
14929 diag::warn_concatenated_literal_array_init)
14930 << Hints;
14931 Diag(SL->getBeginLoc(),
14932 diag::note_concatenated_string_literal_silence);
14933 }
14934 // In any case, stop now.
14935 break;
14936 }
14937 }
14938 }
14939
14940
14941 QualType type = var->getType();
14942
14943 if (var->hasAttr<BlocksAttr>())
14945
14946 Expr *Init = var->getInit();
14947 bool GlobalStorage = var->hasGlobalStorage();
14948 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
14949 QualType baseType = Context.getBaseElementType(type);
14950 bool HasConstInit = true;
14951
14952 if (getLangOpts().C23 && var->isConstexpr() && !Init)
14953 Diag(var->getLocation(), diag::err_constexpr_var_requires_const_init)
14954 << var;
14955
14956 // Check whether the initializer is sufficiently constant.
14957 if ((getLangOpts().CPlusPlus || (getLangOpts().C23 && var->isConstexpr())) &&
14958 !type->isDependentType() && Init && !Init->isValueDependent() &&
14959 (GlobalStorage || var->isConstexpr() ||
14960 var->mightBeUsableInConstantExpressions(Context))) {
14961 // If this variable might have a constant initializer or might be usable in
14962 // constant expressions, check whether or not it actually is now. We can't
14963 // do this lazily, because the result might depend on things that change
14964 // later, such as which constexpr functions happen to be defined.
14966 if (!getLangOpts().CPlusPlus11 && !getLangOpts().C23) {
14967 // Prior to C++11, in contexts where a constant initializer is required,
14968 // the set of valid constant initializers is described by syntactic rules
14969 // in [expr.const]p2-6.
14970 // FIXME: Stricter checking for these rules would be useful for constinit /
14971 // -Wglobal-constructors.
14972 HasConstInit = checkConstInit();
14973
14974 // Compute and cache the constant value, and remember that we have a
14975 // constant initializer.
14976 if (HasConstInit) {
14977 if (var->isStaticDataMember() && !var->isInline() &&
14978 var->getLexicalDeclContext()->isRecord() &&
14979 type->isIntegralOrEnumerationType()) {
14980 // In C++98, in-class initialization for a static data member must
14981 // be an integer constant expression.
14982 if (!Init->isIntegerConstantExpr(Context)) {
14983 Diag(Init->getExprLoc(),
14984 diag::ext_in_class_initializer_non_constant)
14985 << Init->getSourceRange();
14986 }
14987 }
14988 (void)var->checkForConstantInitialization(Notes);
14989 Notes.clear();
14990 } else if (CacheCulprit) {
14991 Notes.emplace_back(CacheCulprit->getExprLoc(),
14992 PDiag(diag::note_invalid_subexpr_in_const_expr));
14993 Notes.back().second << CacheCulprit->getSourceRange();
14994 }
14995 } else {
14996 // Evaluate the initializer to see if it's a constant initializer.
14997 HasConstInit = var->checkForConstantInitialization(Notes);
14998 }
14999
15000 if (HasConstInit) {
15001 // FIXME: Consider replacing the initializer with a ConstantExpr.
15002 } else if (var->isConstexpr()) {
15003 SourceLocation DiagLoc = var->getLocation();
15004 // If the note doesn't add any useful information other than a source
15005 // location, fold it into the primary diagnostic.
15006 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
15007 diag::note_invalid_subexpr_in_const_expr) {
15008 DiagLoc = Notes[0].first;
15009 Notes.clear();
15010 }
15011 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
15012 << var << Init->getSourceRange();
15013 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15014 Diag(Notes[I].first, Notes[I].second);
15015 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
15016 auto *Attr = var->getAttr<ConstInitAttr>();
15017 Diag(var->getLocation(), diag::err_require_constant_init_failed)
15018 << Init->getSourceRange();
15019 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
15020 << Attr->getRange() << Attr->isConstinit();
15021 for (auto &it : Notes)
15022 Diag(it.first, it.second);
15023 } else if (var->isStaticDataMember() && !var->isInline() &&
15024 var->getLexicalDeclContext()->isRecord()) {
15025 Diag(var->getLocation(), diag::err_in_class_initializer_non_constant)
15026 << Init->getSourceRange();
15027 for (auto &it : Notes)
15028 Diag(it.first, it.second);
15029 var->setInvalidDecl();
15030 } else if (IsGlobal &&
15031 !getDiagnostics().isIgnored(diag::warn_global_constructor,
15032 var->getLocation())) {
15033 // Warn about globals which don't have a constant initializer. Don't
15034 // warn about globals with a non-trivial destructor because we already
15035 // warned about them.
15036 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
15037 if (!(RD && !RD->hasTrivialDestructor())) {
15038 // checkConstInit() here permits trivial default initialization even in
15039 // C++11 onwards, where such an initializer is not a constant initializer
15040 // but nonetheless doesn't require a global constructor.
15041 if (!checkConstInit())
15042 Diag(var->getLocation(), diag::warn_global_constructor)
15043 << Init->getSourceRange();
15044 }
15045 }
15046 }
15047
15048 // Apply section attributes and pragmas to global variables.
15049 if (GlobalStorage && var->isThisDeclarationADefinition() &&
15051 PragmaStack<StringLiteral *> *Stack = nullptr;
15052 int SectionFlags = ASTContext::PSF_Read;
15053 bool MSVCEnv =
15054 Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment();
15055 std::optional<QualType::NonConstantStorageReason> Reason;
15056 if (HasConstInit &&
15057 !(Reason = var->getType().isNonConstantStorage(Context, true, false))) {
15058 Stack = &ConstSegStack;
15059 } else {
15060 SectionFlags |= ASTContext::PSF_Write;
15061 Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack;
15062 }
15063 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
15064 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
15065 SectionFlags |= ASTContext::PSF_Implicit;
15066 UnifySection(SA->getName(), SectionFlags, var);
15067 } else if (Stack->CurrentValue) {
15068 if (Stack != &ConstSegStack && MSVCEnv &&
15069 ConstSegStack.CurrentValue != ConstSegStack.DefaultValue &&
15070 var->getType().isConstQualified()) {
15071 assert((!Reason || Reason != QualType::NonConstantStorageReason::
15072 NonConstNonReferenceType) &&
15073 "This case should've already been handled elsewhere");
15074 Diag(var->getLocation(), diag::warn_section_msvc_compat)
15075 << var << ConstSegStack.CurrentValue << (int)(!HasConstInit
15077 : *Reason);
15078 }
15079 SectionFlags |= ASTContext::PSF_Implicit;
15080 auto SectionName = Stack->CurrentValue->getString();
15081 var->addAttr(SectionAttr::CreateImplicit(Context, SectionName,
15082 Stack->CurrentPragmaLocation,
15083 SectionAttr::Declspec_allocate));
15084 if (UnifySection(SectionName, SectionFlags, var))
15085 var->dropAttr<SectionAttr>();
15086 }
15087
15088 // Apply the init_seg attribute if this has an initializer. If the
15089 // initializer turns out to not be dynamic, we'll end up ignoring this
15090 // attribute.
15091 if (CurInitSeg && var->getInit())
15092 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
15093 CurInitSegLoc));
15094 }
15095
15096 // All the following checks are C++ only.
15097 if (!getLangOpts().CPlusPlus) {
15098 // If this variable must be emitted, add it as an initializer for the
15099 // current module.
15100 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
15101 Context.addModuleInitializer(ModuleScopes.back().Module, var);
15102 return;
15103 }
15104
15106
15107 // Require the destructor.
15108 if (!type->isDependentType())
15109 if (auto *RD = baseType->getAsCXXRecordDecl())
15111
15112 // If this variable must be emitted, add it as an initializer for the current
15113 // module.
15114 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
15115 Context.addModuleInitializer(ModuleScopes.back().Module, var);
15116
15117 // Build the bindings if this is a structured binding declaration.
15118 if (auto *DD = dyn_cast<DecompositionDecl>(var))
15120}
15121
15123 assert(VD->isStaticLocal());
15124
15125 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
15126
15127 // Find outermost function when VD is in lambda function.
15128 while (FD && !getDLLAttr(FD) &&
15129 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
15130 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
15131 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
15132 }
15133
15134 if (!FD)
15135 return;
15136
15137 // Static locals inherit dll attributes from their function.
15138 if (Attr *A = getDLLAttr(FD)) {
15139 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
15140 NewAttr->setInherited(true);
15141 VD->addAttr(NewAttr);
15142 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
15143 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
15144 NewAttr->setInherited(true);
15145 VD->addAttr(NewAttr);
15146
15147 // Export this function to enforce exporting this static variable even
15148 // if it is not used in this compilation unit.
15149 if (!FD->hasAttr<DLLExportAttr>())
15150 FD->addAttr(NewAttr);
15151
15152 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
15153 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
15154 NewAttr->setInherited(true);
15155 VD->addAttr(NewAttr);
15156 }
15157}
15158
15160 assert(VD->getTLSKind());
15161
15162 // Perform TLS alignment check here after attributes attached to the variable
15163 // which may affect the alignment have been processed. Only perform the check
15164 // if the target has a maximum TLS alignment (zero means no constraints).
15165 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
15166 // Protect the check so that it's not performed on dependent types and
15167 // dependent alignments (we can't determine the alignment in that case).
15168 if (!VD->hasDependentAlignment()) {
15169 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
15170 if (Context.getDeclAlign(VD) > MaxAlignChars) {
15171 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
15172 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
15173 << (unsigned)MaxAlignChars.getQuantity();
15174 }
15175 }
15176 }
15177}
15178
15180 // Note that we are no longer parsing the initializer for this declaration.
15181 ParsingInitForAutoVars.erase(ThisDecl);
15182
15183 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
15184 if (!VD)
15185 return;
15186
15187 // Emit any deferred warnings for the variable's initializer, even if the
15188 // variable is invalid
15189 AnalysisWarnings.issueWarningsForRegisteredVarDecl(VD);
15190
15191 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
15193 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
15194 if (PragmaClangBSSSection.Valid)
15195 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
15196 Context, PragmaClangBSSSection.SectionName,
15197 PragmaClangBSSSection.PragmaLocation));
15198 if (PragmaClangDataSection.Valid)
15199 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
15200 Context, PragmaClangDataSection.SectionName,
15201 PragmaClangDataSection.PragmaLocation));
15202 if (PragmaClangRodataSection.Valid)
15203 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
15204 Context, PragmaClangRodataSection.SectionName,
15205 PragmaClangRodataSection.PragmaLocation));
15206 if (PragmaClangRelroSection.Valid)
15207 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
15208 Context, PragmaClangRelroSection.SectionName,
15209 PragmaClangRelroSection.PragmaLocation));
15210 }
15211
15212 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
15213 for (auto *BD : DD->bindings()) {
15215 }
15216 }
15217
15218 CheckInvalidBuiltinCountedByRef(VD->getInit(),
15220
15221 checkAttributesAfterMerging(*this, *VD);
15222
15223 if (VD->isStaticLocal())
15225
15226 if (VD->getTLSKind())
15228
15229 // Perform check for initializers of device-side global variables.
15230 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
15231 // 7.5). We must also apply the same checks to all __shared__
15232 // variables whether they are local or not. CUDA also allows
15233 // constant initializers for __constant__ and __device__ variables.
15234 if (getLangOpts().CUDA)
15236
15237 // Grab the dllimport or dllexport attribute off of the VarDecl.
15238 const InheritableAttr *DLLAttr = getDLLAttr(VD);
15239
15240 // Imported static data members cannot be defined out-of-line.
15241 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
15242 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
15244 // We allow definitions of dllimport class template static data members
15245 // with a warning.
15248 bool IsClassTemplateMember =
15250 Context->getDescribedClassTemplate();
15251
15252 Diag(VD->getLocation(),
15253 IsClassTemplateMember
15254 ? diag::warn_attribute_dllimport_static_field_definition
15255 : diag::err_attribute_dllimport_static_field_definition);
15256 Diag(IA->getLocation(), diag::note_attribute);
15257 if (!IsClassTemplateMember)
15258 VD->setInvalidDecl();
15259 }
15260 }
15261
15262 // dllimport/dllexport variables cannot be thread local, their TLS index
15263 // isn't exported with the variable.
15264 if (DLLAttr && VD->getTLSKind()) {
15265 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
15266 if (F && getDLLAttr(F)) {
15267 assert(VD->isStaticLocal());
15268 // But if this is a static local in a dlimport/dllexport function, the
15269 // function will never be inlined, which means the var would never be
15270 // imported, so having it marked import/export is safe.
15271 } else {
15272 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
15273 << DLLAttr;
15274 VD->setInvalidDecl();
15275 }
15276 }
15277
15278 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
15279 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
15280 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
15281 << Attr;
15282 VD->dropAttr<UsedAttr>();
15283 }
15284 }
15285 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
15286 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
15287 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
15288 << Attr;
15289 VD->dropAttr<RetainAttr>();
15290 }
15291 }
15292
15293 const DeclContext *DC = VD->getDeclContext();
15294 // If there's a #pragma GCC visibility in scope, and this isn't a class
15295 // member, set the visibility of this variable.
15298
15299 // FIXME: Warn on unused var template partial specializations.
15302
15303 // Now we have parsed the initializer and can update the table of magic
15304 // tag values.
15305 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
15307 return;
15308
15309 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
15310 const Expr *MagicValueExpr = VD->getInit();
15311 if (!MagicValueExpr) {
15312 continue;
15313 }
15314 std::optional<llvm::APSInt> MagicValueInt;
15315 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
15316 Diag(I->getRange().getBegin(),
15317 diag::err_type_tag_for_datatype_not_ice)
15318 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15319 continue;
15320 }
15321 if (MagicValueInt->getActiveBits() > 64) {
15322 Diag(I->getRange().getBegin(),
15323 diag::err_type_tag_for_datatype_too_large)
15324 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15325 continue;
15326 }
15327 uint64_t MagicValue = MagicValueInt->getZExtValue();
15328 RegisterTypeTagForDatatype(I->getArgumentKind(),
15329 MagicValue,
15330 I->getMatchingCType(),
15331 I->getLayoutCompatible(),
15332 I->getMustBeNull());
15333 }
15334}
15335
15337 auto *VD = dyn_cast<VarDecl>(DD);
15338 return VD && !VD->getType()->hasAutoForTrailingReturnType();
15339}
15340
15342 ArrayRef<Decl *> Group) {
15344
15345 if (DS.isTypeSpecOwned())
15346 Decls.push_back(DS.getRepAsDecl());
15347
15348 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
15349 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
15350 bool DiagnosedMultipleDecomps = false;
15351 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
15352 bool DiagnosedNonDeducedAuto = false;
15353
15354 for (Decl *D : Group) {
15355 if (!D)
15356 continue;
15357 // Check if the Decl has been declared in '#pragma omp declare target'
15358 // directive and has static storage duration.
15359 if (auto *VD = dyn_cast<VarDecl>(D);
15360 LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&
15361 VD->hasGlobalStorage())
15363 // For declarators, there are some additional syntactic-ish checks we need
15364 // to perform.
15365 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
15366 if (!FirstDeclaratorInGroup)
15367 FirstDeclaratorInGroup = DD;
15368 if (!FirstDecompDeclaratorInGroup)
15369 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
15370 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
15371 !hasDeducedAuto(DD))
15372 FirstNonDeducedAutoInGroup = DD;
15373
15374 if (FirstDeclaratorInGroup != DD) {
15375 // A decomposition declaration cannot be combined with any other
15376 // declaration in the same group.
15377 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
15378 Diag(FirstDecompDeclaratorInGroup->getLocation(),
15379 diag::err_decomp_decl_not_alone)
15380 << FirstDeclaratorInGroup->getSourceRange()
15381 << DD->getSourceRange();
15382 DiagnosedMultipleDecomps = true;
15383 }
15384
15385 // A declarator that uses 'auto' in any way other than to declare a
15386 // variable with a deduced type cannot be combined with any other
15387 // declarator in the same group.
15388 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
15389 Diag(FirstNonDeducedAutoInGroup->getLocation(),
15390 diag::err_auto_non_deduced_not_alone)
15391 << FirstNonDeducedAutoInGroup->getType()
15393 << FirstDeclaratorInGroup->getSourceRange()
15394 << DD->getSourceRange();
15395 DiagnosedNonDeducedAuto = true;
15396 }
15397 }
15398 }
15399
15400 Decls.push_back(D);
15401 }
15402
15404 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
15405 handleTagNumbering(Tag, S);
15406 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
15408 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
15409 }
15410 }
15411
15412 return BuildDeclaratorGroup(Decls);
15413}
15414
15417 // C++14 [dcl.spec.auto]p7: (DR1347)
15418 // If the type that replaces the placeholder type is not the same in each
15419 // deduction, the program is ill-formed.
15420 if (Group.size() > 1) {
15421 QualType Deduced;
15422 VarDecl *DeducedDecl = nullptr;
15423 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
15424 VarDecl *D = dyn_cast<VarDecl>(Group[i]);
15425 if (!D || D->isInvalidDecl())
15426 break;
15427 DeducedType *DT = D->getType()->getContainedDeducedType();
15428 if (!DT || DT->getDeducedType().isNull())
15429 continue;
15430 if (Deduced.isNull()) {
15431 Deduced = DT->getDeducedType();
15432 DeducedDecl = D;
15433 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
15434 auto *AT = dyn_cast<AutoType>(DT);
15435 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
15436 diag::err_auto_different_deductions)
15437 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
15438 << DeducedDecl->getDeclName() << DT->getDeducedType()
15439 << D->getDeclName();
15440 if (DeducedDecl->hasInit())
15441 Dia << DeducedDecl->getInit()->getSourceRange();
15442 if (D->getInit())
15443 Dia << D->getInit()->getSourceRange();
15444 D->setInvalidDecl();
15445 break;
15446 }
15447 }
15448 }
15449
15451
15452 return DeclGroupPtrTy::make(
15453 DeclGroupRef::Create(Context, Group.data(), Group.size()));
15454}
15455
15459
15461 // Don't parse the comment if Doxygen diagnostics are ignored.
15462 if (Group.empty() || !Group[0])
15463 return;
15464
15465 if (Diags.isIgnored(diag::warn_doc_param_not_found,
15466 Group[0]->getLocation()) &&
15467 Diags.isIgnored(diag::warn_unknown_comment_command_name,
15468 Group[0]->getLocation()))
15469 return;
15470
15471 if (Group.size() >= 2) {
15472 // This is a decl group. Normally it will contain only declarations
15473 // produced from declarator list. But in case we have any definitions or
15474 // additional declaration references:
15475 // 'typedef struct S {} S;'
15476 // 'typedef struct S *S;'
15477 // 'struct S *pS;'
15478 // FinalizeDeclaratorGroup adds these as separate declarations.
15479 Decl *MaybeTagDecl = Group[0];
15480 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
15481 Group = Group.slice(1);
15482 }
15483 }
15484
15485 // FIXME: We assume every Decl in the group is in the same file.
15486 // This is false when preprocessor constructs the group from decls in
15487 // different files (e. g. macros or #include).
15488 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
15489}
15490
15492 // Check that there are no default arguments inside the type of this
15493 // parameter.
15494 if (getLangOpts().CPlusPlus)
15496
15497 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
15498 if (D.getCXXScopeSpec().isSet()) {
15499 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
15500 << D.getCXXScopeSpec().getRange();
15501 }
15502
15503 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
15504 // simple identifier except [...irrelevant cases...].
15505 switch (D.getName().getKind()) {
15507 break;
15508
15516 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
15518 break;
15519
15522 // GetNameForDeclarator would not produce a useful name in this case.
15523 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
15524 break;
15525 }
15526}
15527
15529 // This only matters in C.
15530 if (getLangOpts().CPlusPlus)
15531 return;
15532
15533 // This only matters if the declaration has a type.
15534 const auto *VD = dyn_cast<ValueDecl>(D);
15535 if (!VD)
15536 return;
15537
15538 // Get the type, this only matters for tag types.
15539 QualType QT = VD->getType();
15540 const auto *TD = QT->getAsTagDecl();
15541 if (!TD)
15542 return;
15543
15544 // Check if the tag declaration is lexically declared somewhere different
15545 // from the lexical declaration of the given object, then it will be hidden
15546 // in C++ and we should warn on it.
15547 if (!TD->getLexicalParent()->LexicallyEncloses(D->getLexicalDeclContext())) {
15548 unsigned Kind = TD->isEnum() ? 2 : TD->isUnion() ? 1 : 0;
15549 Diag(D->getLocation(), diag::warn_decl_hidden_in_cpp) << Kind;
15550 Diag(TD->getLocation(), diag::note_declared_at);
15551 }
15552}
15553
15555 SourceLocation ExplicitThisLoc) {
15556 if (!ExplicitThisLoc.isValid())
15557 return;
15558 assert(S.getLangOpts().CPlusPlus &&
15559 "explicit parameter in non-cplusplus mode");
15560 if (!S.getLangOpts().CPlusPlus23)
15561 S.Diag(ExplicitThisLoc, diag::err_cxx20_deducing_this)
15562 << P->getSourceRange();
15563
15564 // C++2b [dcl.fct/7] An explicit object parameter shall not be a function
15565 // parameter pack.
15566 if (P->isParameterPack()) {
15567 S.Diag(P->getBeginLoc(), diag::err_explicit_object_parameter_pack)
15568 << P->getSourceRange();
15569 return;
15570 }
15571 P->setExplicitObjectParameterLoc(ExplicitThisLoc);
15572 if (LambdaScopeInfo *LSI = S.getCurLambda())
15573 LSI->ExplicitObjectParameter = P;
15574}
15575
15577 SourceLocation ExplicitThisLoc) {
15578 const DeclSpec &DS = D.getDeclSpec();
15579
15580 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
15581 // C2y 6.7.7.4p4: A parameter declaration shall not specify a void type,
15582 // except for the special case of a single unnamed parameter of type void
15583 // with no storage class specifier, no type qualifier, and no following
15584 // ellipsis terminator.
15585 // Clang applies the C2y rules for 'register void' in all C language modes,
15586 // same as GCC, because it's questionable what that could possibly mean.
15587
15588 // C++03 [dcl.stc]p2 also permits 'auto'.
15589 StorageClass SC = SC_None;
15591 SC = SC_Register;
15592 // In C++11, the 'register' storage class specifier is deprecated.
15593 // In C++17, it is not allowed, but we tolerate it as an extension.
15594 if (getLangOpts().CPlusPlus11) {
15596 ? diag::ext_register_storage_class
15597 : diag::warn_deprecated_register)
15599 } else if (!getLangOpts().CPlusPlus &&
15601 D.getNumTypeObjects() == 0) {
15603 diag::err_invalid_storage_class_in_func_decl)
15606 }
15607 } else if (getLangOpts().CPlusPlus &&
15609 SC = SC_Auto;
15612 diag::err_invalid_storage_class_in_func_decl);
15614 }
15615
15617 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
15619 if (DS.isInlineSpecified())
15620 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
15621 << getLangOpts().CPlusPlus17;
15622 if (DS.hasConstexprSpecifier())
15623 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
15624 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
15625
15627
15629
15631 QualType parmDeclType = TInfo->getType();
15632
15633 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
15634 const IdentifierInfo *II = D.getIdentifier();
15635 if (II) {
15638 LookupName(R, S);
15639 if (!R.empty()) {
15640 NamedDecl *PrevDecl = *R.begin();
15641 if (R.isSingleResult() && PrevDecl->isTemplateParameter()) {
15642 // Maybe we will complain about the shadowed template parameter.
15644 // Just pretend that we didn't see the previous declaration.
15645 PrevDecl = nullptr;
15646 }
15647 if (PrevDecl && S->isDeclScope(PrevDecl)) {
15648 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
15649 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15650 // Recover by removing the name
15651 II = nullptr;
15652 D.SetIdentifier(nullptr, D.getIdentifierLoc());
15653 D.setInvalidType(true);
15654 }
15655 }
15656 }
15657
15658 // Incomplete resource arrays are not allowed as function parameters in HLSL
15659 if (getLangOpts().HLSL && parmDeclType->isIncompleteArrayType() &&
15660 parmDeclType->isHLSLResourceRecordArray()) {
15662 diag::err_hlsl_incomplete_resource_array_in_function_param);
15663 D.setInvalidType(true);
15664 }
15665
15666 // Temporarily put parameter variables in the translation unit, not
15667 // the enclosing context. This prevents them from accidentally
15668 // looking like class members in C++.
15669 ParmVarDecl *New =
15670 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
15671 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
15672
15673 if (D.isInvalidType())
15674 New->setInvalidDecl();
15675
15676 CheckExplicitObjectParameter(*this, New, ExplicitThisLoc);
15677
15678 assert(S->isFunctionPrototypeScope());
15679 assert(S->getFunctionPrototypeDepth() >= 1);
15680 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
15682
15684
15685 // Add the parameter declaration into this scope.
15686 S->AddDecl(New);
15687 if (II)
15688 IdResolver.AddDecl(New);
15689
15691
15693 Diag(New->getLocation(), diag::err_module_private_local)
15696
15697 if (New->hasAttr<BlocksAttr>()) {
15698 Diag(New->getLocation(), diag::err_block_on_nonlocal);
15699 }
15700
15701 if (getLangOpts().OpenCL)
15703
15704 return New;
15705}
15706
15708 SourceLocation Loc,
15709 QualType T) {
15710 /* FIXME: setting StartLoc == Loc.
15711 Would it be worth to modify callers so as to provide proper source
15712 location for the unnamed parameters, embedding the parameter's type? */
15713 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
15714 T, Context.getTrivialTypeSourceInfo(T, Loc),
15715 SC_None, nullptr);
15716 Param->setImplicit();
15717 return Param;
15718}
15719
15721 // Don't diagnose unused-parameter errors in template instantiations; we
15722 // will already have done so in the template itself.
15724 return;
15725
15726 for (const ParmVarDecl *Parameter : Parameters) {
15727 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
15728 !Parameter->hasAttr<UnusedAttr>() &&
15729 !Parameter->getIdentifier()->isPlaceholder()) {
15730 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
15731 << Parameter->getDeclName();
15732 }
15733 }
15734}
15735
15737 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
15738 if (LangOpts.NumLargeByValueCopy == 0) // No check.
15739 return;
15740
15741 // Warn if the return value is pass-by-value and larger than the specified
15742 // threshold.
15743 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
15744 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
15745 if (Size > LangOpts.NumLargeByValueCopy)
15746 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
15747 }
15748
15749 // Warn if any parameter is pass-by-value and larger than the specified
15750 // threshold.
15751 for (const ParmVarDecl *Parameter : Parameters) {
15752 QualType T = Parameter->getType();
15753 if (T->isDependentType() || !T.isPODType(Context))
15754 continue;
15755 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
15756 if (Size > LangOpts.NumLargeByValueCopy)
15757 Diag(Parameter->getLocation(), diag::warn_parameter_size)
15758 << Parameter << Size;
15759 }
15760}
15761
15763 SourceLocation NameLoc,
15764 const IdentifierInfo *Name, QualType T,
15765 TypeSourceInfo *TSInfo, StorageClass SC) {
15766 // In ARC, infer a lifetime qualifier for appropriate parameter types.
15767 if (getLangOpts().ObjCAutoRefCount &&
15768 T.getObjCLifetime() == Qualifiers::OCL_None &&
15769 T->isObjCLifetimeType()) {
15770
15771 Qualifiers::ObjCLifetime lifetime;
15772
15773 // Special cases for arrays:
15774 // - if it's const, use __unsafe_unretained
15775 // - otherwise, it's an error
15776 if (T->isArrayType()) {
15777 if (!T.isConstQualified()) {
15781 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
15782 else
15783 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
15784 << TSInfo->getTypeLoc().getSourceRange();
15785 }
15787 } else {
15788 lifetime = T->getObjCARCImplicitLifetime();
15789 }
15790 T = Context.getLifetimeQualifiedType(T, lifetime);
15791 }
15792
15793 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
15794 Context.getAdjustedParameterType(T),
15795 TSInfo, SC, nullptr);
15796
15797 // Make a note if we created a new pack in the scope of a lambda, so that
15798 // we know that references to that pack must also be expanded within the
15799 // lambda scope.
15800 if (New->isParameterPack())
15801 if (auto *CSI = getEnclosingLambdaOrBlock())
15802 CSI->LocalPacks.push_back(New);
15803
15804 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
15805 New->getType().hasNonTrivialToPrimitiveCopyCUnion())
15806 checkNonTrivialCUnion(New->getType(), New->getLocation(),
15809
15810 // Parameter declarators cannot be interface types. All ObjC objects are
15811 // passed by reference.
15812 if (T->isObjCObjectType()) {
15813 SourceLocation TypeEndLoc =
15815 Diag(NameLoc,
15816 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
15817 << FixItHint::CreateInsertion(TypeEndLoc, "*");
15818 T = Context.getObjCObjectPointerType(T);
15819 New->setType(T);
15820 }
15821
15822 // __ptrauth is forbidden on parameters.
15823 if (T.getPointerAuth()) {
15824 Diag(NameLoc, diag::err_ptrauth_qualifier_invalid) << T << 1;
15825 New->setInvalidDecl();
15826 }
15827
15828 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
15829 // duration shall not be qualified by an address-space qualifier."
15830 // Since all parameters have automatic store duration, they can not have
15831 // an address space.
15832 if (T.getAddressSpace() != LangAS::Default &&
15833 // OpenCL allows function arguments declared to be an array of a type
15834 // to be qualified with an address space.
15835 !(getLangOpts().OpenCL &&
15836 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&
15837 // WebAssembly allows reference types as parameters. Funcref in particular
15838 // lives in a different address space.
15839 !(T->isFunctionPointerType() &&
15840 T.getAddressSpace() == LangAS::wasm_funcref)) {
15841 Diag(NameLoc, diag::err_arg_with_address_space);
15842 New->setInvalidDecl();
15843 }
15844
15845 // PPC MMA non-pointer types are not allowed as function argument types.
15846 if (Context.getTargetInfo().getTriple().isPPC64() &&
15847 PPC().CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
15848 New->setInvalidDecl();
15849 }
15850
15851 return New;
15852}
15853
15855 SourceLocation LocAfterDecls) {
15857
15858 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
15859 // in the declaration list shall have at least one declarator, those
15860 // declarators shall only declare identifiers from the identifier list, and
15861 // every identifier in the identifier list shall be declared.
15862 //
15863 // C89 3.7.1p5 "If a declarator includes an identifier list, only the
15864 // identifiers it names shall be declared in the declaration list."
15865 //
15866 // This is why we only diagnose in C99 and later. Note, the other conditions
15867 // listed are checked elsewhere.
15868 if (!FTI.hasPrototype) {
15869 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
15870 --i;
15871 if (FTI.Params[i].Param == nullptr) {
15872 if (getLangOpts().C99) {
15873 SmallString<256> Code;
15874 llvm::raw_svector_ostream(Code)
15875 << " int " << FTI.Params[i].Ident->getName() << ";\n";
15876 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
15877 << FTI.Params[i].Ident
15878 << FixItHint::CreateInsertion(LocAfterDecls, Code);
15879 }
15880
15881 // Implicitly declare the argument as type 'int' for lack of a better
15882 // type.
15883 AttributeFactory attrs;
15884 DeclSpec DS(attrs);
15885 const char* PrevSpec; // unused
15886 unsigned DiagID; // unused
15887 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
15888 DiagID, Context.getPrintingPolicy());
15889 // Use the identifier location for the type source range.
15890 DS.SetRangeStart(FTI.Params[i].IdentLoc);
15891 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
15894 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
15895 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
15896 }
15897 }
15898 }
15899}
15900
15901Decl *
15903 MultiTemplateParamsArg TemplateParameterLists,
15904 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
15905 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
15906 assert(D.isFunctionDeclarator() && "Not a function declarator!");
15907 Scope *ParentScope = FnBodyScope->getParent();
15908
15909 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
15910 // we define a non-templated function definition, we will create a declaration
15911 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
15912 // The base function declaration will have the equivalent of an `omp declare
15913 // variant` annotation which specifies the mangled definition as a
15914 // specialization function under the OpenMP context defined as part of the
15915 // `omp begin declare variant`.
15917 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
15919 ParentScope, D, TemplateParameterLists, Bases);
15920
15922 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
15923 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
15924
15925 if (!Bases.empty())
15927 Bases);
15928
15929 return Dcl;
15930}
15931
15933 Consumer.HandleInlineFunctionDefinition(D);
15934}
15935
15937 const FunctionDecl *&PossiblePrototype) {
15938 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
15939 Prev = Prev->getPreviousDecl()) {
15940 // Ignore any declarations that occur in function or method
15941 // scope, because they aren't visible from the header.
15942 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
15943 continue;
15944
15945 PossiblePrototype = Prev;
15946 return Prev->getType()->isFunctionProtoType();
15947 }
15948 return false;
15949}
15950
15951static bool
15953 const FunctionDecl *&PossiblePrototype) {
15954 // Don't warn about invalid declarations.
15955 if (FD->isInvalidDecl())
15956 return false;
15957
15958 // Or declarations that aren't global.
15959 if (!FD->isGlobal())
15960 return false;
15961
15962 // Don't warn about C++ member functions.
15963 if (isa<CXXMethodDecl>(FD))
15964 return false;
15965
15966 // Don't warn about 'main'.
15968 if (IdentifierInfo *II = FD->getIdentifier())
15969 if (II->isStr("main") || II->isStr("efi_main"))
15970 return false;
15971
15972 if (FD->isMSVCRTEntryPoint())
15973 return false;
15974
15975 // Don't warn about inline functions.
15976 if (FD->isInlined())
15977 return false;
15978
15979 // Don't warn about function templates.
15981 return false;
15982
15983 // Don't warn about function template specializations.
15985 return false;
15986
15987 // Don't warn for OpenCL kernels.
15988 if (FD->hasAttr<DeviceKernelAttr>())
15989 return false;
15990
15991 // Don't warn on explicitly deleted functions.
15992 if (FD->isDeleted())
15993 return false;
15994
15995 // Don't warn on implicitly local functions (such as having local-typed
15996 // parameters).
15997 if (!FD->isExternallyVisible())
15998 return false;
15999
16000 // If we were able to find a potential prototype, don't warn.
16001 if (FindPossiblePrototype(FD, PossiblePrototype))
16002 return false;
16003
16004 return true;
16005}
16006
16007void
16009 const FunctionDecl *EffectiveDefinition,
16010 SkipBodyInfo *SkipBody) {
16011 const FunctionDecl *Definition = EffectiveDefinition;
16012 if (!Definition &&
16013 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
16014 return;
16015
16016 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
16017 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
16018 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
16019 // A merged copy of the same function, instantiated as a member of
16020 // the same class, is OK.
16021 if (declaresSameEntity(OrigFD, OrigDef) &&
16022 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
16024 return;
16025 }
16026 }
16027 }
16028
16030 return;
16031
16032 // Don't emit an error when this is redefinition of a typo-corrected
16033 // definition.
16035 return;
16036
16037 bool DefinitionVisible = false;
16038 if (SkipBody && isRedefinitionAllowedFor(Definition, DefinitionVisible) &&
16039 (Definition->getFormalLinkage() == Linkage::Internal ||
16040 Definition->isInlined() || Definition->getDescribedFunctionTemplate() ||
16041 Definition->getNumTemplateParameterLists())) {
16042 SkipBody->ShouldSkip = true;
16043 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
16044 if (!DefinitionVisible) {
16045 if (auto *TD = Definition->getDescribedFunctionTemplate())
16048 }
16049 return;
16050 }
16051
16052 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
16053 Definition->getStorageClass() == SC_Extern)
16054 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
16055 << FD << getLangOpts().CPlusPlus;
16056 else
16057 Diag(FD->getLocation(), diag::err_redefinition) << FD;
16058
16059 Diag(Definition->getLocation(), diag::note_previous_definition);
16060 FD->setInvalidDecl();
16061}
16062
16064 CXXRecordDecl *LambdaClass = CallOperator->getParent();
16065
16067 LSI->CallOperator = CallOperator;
16068 LSI->Lambda = LambdaClass;
16069 LSI->ReturnType = CallOperator->getReturnType();
16070 // When this function is called in situation where the context of the call
16071 // operator is not entered, we set AfterParameterList to false, so that
16072 // `tryCaptureVariable` finds explicit captures in the appropriate context.
16073 // There is also at least a situation as in FinishTemplateArgumentDeduction(),
16074 // where we would set the CurContext to the lambda operator before
16075 // substituting into it. In this case the flag needs to be true such that
16076 // tryCaptureVariable can correctly handle potential captures thereof.
16077 LSI->AfterParameterList = CurContext == CallOperator;
16078
16079 // GLTemplateParameterList is necessary for getCurGenericLambda() which is
16080 // used at the point of dealing with potential captures.
16081 //
16082 // We don't use LambdaClass->isGenericLambda() because this value doesn't
16083 // flip for instantiated generic lambdas, where no FunctionTemplateDecls are
16084 // associated. (Technically, we could recover that list from their
16085 // instantiation patterns, but for now, the GLTemplateParameterList seems
16086 // unnecessary in these cases.)
16087 if (FunctionTemplateDecl *FTD = CallOperator->getDescribedFunctionTemplate())
16088 LSI->GLTemplateParameterList = FTD->getTemplateParameters();
16089 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
16090
16091 if (LCD == LCD_None)
16093 else if (LCD == LCD_ByCopy)
16095 else if (LCD == LCD_ByRef)
16097 DeclarationNameInfo DNI = CallOperator->getNameInfo();
16098
16100 LSI->Mutable = !CallOperator->isConst();
16101 if (CallOperator->isExplicitObjectMemberFunction())
16102 LSI->ExplicitObjectParameter = CallOperator->getParamDecl(0);
16103
16104 // Add the captures to the LSI so they can be noted as already
16105 // captured within tryCaptureVar.
16106 auto I = LambdaClass->field_begin();
16107 for (const auto &C : LambdaClass->captures()) {
16108 if (C.capturesVariable()) {
16109 ValueDecl *VD = C.getCapturedVar();
16110 if (VD->isInitCapture())
16111 CurrentInstantiationScope->InstantiatedLocal(VD, VD);
16112 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
16113 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
16114 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
16115 /*EllipsisLoc*/C.isPackExpansion()
16116 ? C.getEllipsisLoc() : SourceLocation(),
16117 I->getType(), /*Invalid*/false);
16118
16119 } else if (C.capturesThis()) {
16120 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
16121 C.getCaptureKind() == LCK_StarThis);
16122 } else {
16123 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
16124 I->getType());
16125 }
16126 ++I;
16127 }
16128 return LSI;
16129}
16130
16132 SkipBodyInfo *SkipBody,
16133 FnBodyKind BodyKind) {
16134 if (!D) {
16135 // Parsing the function declaration failed in some way. Push on a fake scope
16136 // anyway so we can try to parse the function body.
16139 return D;
16140 }
16141
16142 FunctionDecl *FD = nullptr;
16143
16144 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
16145 FD = FunTmpl->getTemplatedDecl();
16146 else
16147 FD = cast<FunctionDecl>(D);
16148
16149 // Do not push if it is a lambda because one is already pushed when building
16150 // the lambda in ActOnStartOfLambdaDefinition().
16151 if (!isLambdaCallOperator(FD))
16153 FD);
16154
16155 // Check for defining attributes before the check for redefinition.
16156 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
16157 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
16158 FD->dropAttr<AliasAttr>();
16159 FD->setInvalidDecl();
16160 }
16161 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
16162 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
16163 FD->dropAttr<IFuncAttr>();
16164 FD->setInvalidDecl();
16165 }
16166 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
16167 if (Context.getTargetInfo().getTriple().isAArch64() &&
16168 !Context.getTargetInfo().hasFeature("fmv") &&
16169 !Attr->isDefaultVersion()) {
16170 // If function multi versioning disabled skip parsing function body
16171 // defined with non-default target_version attribute
16172 if (SkipBody)
16173 SkipBody->ShouldSkip = true;
16174 return nullptr;
16175 }
16176 }
16177
16178 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
16179 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
16180 Ctor->isDefaultConstructor() &&
16181 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
16182 // If this is an MS ABI dllexport default constructor, instantiate any
16183 // default arguments.
16185 }
16186 }
16187
16188 // See if this is a redefinition. If 'will have body' (or similar) is already
16189 // set, then these checks were already performed when it was set.
16190 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
16192 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
16193
16194 // If we're skipping the body, we're done. Don't enter the scope.
16195 if (SkipBody && SkipBody->ShouldSkip)
16196 return D;
16197 }
16198
16199 // Mark this function as "will have a body eventually". This lets users to
16200 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
16201 // this function.
16202 FD->setWillHaveBody();
16203
16204 // If we are instantiating a generic lambda call operator, push
16205 // a LambdaScopeInfo onto the function stack. But use the information
16206 // that's already been calculated (ActOnLambdaExpr) to prime the current
16207 // LambdaScopeInfo.
16208 // When the template operator is being specialized, the LambdaScopeInfo,
16209 // has to be properly restored so that tryCaptureVariable doesn't try
16210 // and capture any new variables. In addition when calculating potential
16211 // captures during transformation of nested lambdas, it is necessary to
16212 // have the LSI properly restored.
16214 // C++2c 7.5.5.2p17 A member of a closure type shall not be explicitly
16215 // instantiated, explicitly specialized.
16218 Diag(FD->getLocation(), diag::err_lambda_explicit_spec);
16219 FD->setInvalidDecl();
16221 } else {
16222 assert(inTemplateInstantiation() &&
16223 "There should be an active template instantiation on the stack "
16224 "when instantiating a generic lambda!");
16226 }
16227 } else {
16228 // Enter a new function scope
16230 }
16231
16232 // Builtin functions cannot be defined.
16233 if (unsigned BuiltinID = FD->getBuiltinID()) {
16234 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
16235 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
16236 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
16237 FD->setInvalidDecl();
16238 }
16239 }
16240
16241 // The return type of a function definition must be complete (C99 6.9.1p3).
16242 // C++23 [dcl.fct.def.general]/p2
16243 // The type of [...] the return for a function definition
16244 // shall not be a (possibly cv-qualified) class type that is incomplete
16245 // or abstract within the function body unless the function is deleted.
16246 QualType ResultType = FD->getReturnType();
16247 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
16248 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
16249 (RequireCompleteType(FD->getLocation(), ResultType,
16250 diag::err_func_def_incomplete_result) ||
16252 diag::err_abstract_type_in_decl,
16254 FD->setInvalidDecl();
16255
16256 if (FnBodyScope)
16257 PushDeclContext(FnBodyScope, FD);
16258
16259 // Check the validity of our function parameters
16260 if (BodyKind != FnBodyKind::Delete)
16262 /*CheckParameterNames=*/true);
16263
16264 // Add non-parameter declarations already in the function to the current
16265 // scope.
16266 if (FnBodyScope) {
16267 for (Decl *NPD : FD->decls()) {
16268 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
16269 if (!NonParmDecl)
16270 continue;
16271 assert(!isa<ParmVarDecl>(NonParmDecl) &&
16272 "parameters should not be in newly created FD yet");
16273
16274 // If the decl has a name, make it accessible in the current scope.
16275 if (NonParmDecl->getDeclName())
16276 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
16277
16278 // Similarly, dive into enums and fish their constants out, making them
16279 // accessible in this scope.
16280 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
16281 for (auto *EI : ED->enumerators())
16282 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
16283 }
16284 }
16285 }
16286
16287 // Introduce our parameters into the function scope
16288 for (auto *Param : FD->parameters()) {
16289 Param->setOwningFunction(FD);
16290
16291 // If this has an identifier, add it to the scope stack.
16292 if (Param->getIdentifier() && FnBodyScope) {
16293 CheckShadow(FnBodyScope, Param);
16294
16295 PushOnScopeChains(Param, FnBodyScope);
16296 }
16297 }
16298
16299 // C++ [module.import/6]
16300 // ...
16301 // A header unit shall not contain a definition of a non-inline function or
16302 // variable whose name has external linkage.
16303 //
16304 // Deleted and Defaulted functions are implicitly inline (but the
16305 // inline state is not set at this point, so check the BodyKind explicitly).
16306 // We choose to allow weak & selectany definitions, as they are common in
16307 // headers, and have semantics similar to inline definitions which are allowed
16308 // in header units.
16309 // FIXME: Consider an alternate location for the test where the inlined()
16310 // state is complete.
16311 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
16312 !FD->isInvalidDecl() && !FD->isInlined() &&
16313 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
16314 FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() &&
16315 !FD->isTemplateInstantiation() &&
16316 !(FD->hasAttr<SelectAnyAttr>() || FD->hasAttr<WeakAttr>())) {
16317 assert(FD->isThisDeclarationADefinition());
16318 Diag(FD->getLocation(), diag::err_extern_def_in_header_unit);
16319 FD->setInvalidDecl();
16320 }
16321
16322 // Ensure that the function's exception specification is instantiated.
16323 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
16325
16326 // dllimport cannot be applied to non-inline function definitions.
16327 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
16328 !FD->isTemplateInstantiation()) {
16329 assert(!FD->hasAttr<DLLExportAttr>());
16330 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
16331 FD->setInvalidDecl();
16332 return D;
16333 }
16334
16335 // Some function attributes (like OptimizeNoneAttr) need actions before
16336 // parsing body started.
16338
16339 // We want to attach documentation to original Decl (which might be
16340 // a function template).
16342 if (getCurLexicalContext()->isObjCContainer() &&
16343 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
16344 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
16345 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
16346
16348
16349 return D;
16350}
16351
16353 if (!FD || FD->isInvalidDecl())
16354 return;
16355 if (auto *TD = dyn_cast<FunctionTemplateDecl>(FD))
16356 FD = TD->getTemplatedDecl();
16357 if (FD && FD->hasAttr<OptimizeNoneAttr>()) {
16360 CurFPFeatures.applyChanges(FPO);
16361 FpPragmaStack.CurrentValue =
16362 CurFPFeatures.getChangesFrom(FPOptions(LangOpts));
16363 }
16364}
16365
16367 ReturnStmt **Returns = Scope->Returns.data();
16368
16369 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
16370 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
16371 if (!NRVOCandidate->isNRVOVariable()) {
16372 Diag(Returns[I]->getRetValue()->getExprLoc(),
16373 diag::warn_not_eliding_copy_on_return);
16374 Returns[I]->setNRVOCandidate(nullptr);
16375 }
16376 }
16377 }
16378}
16379
16381 // We can't delay parsing the body of a constexpr function template (yet).
16383 return false;
16384
16385 // We can't delay parsing the body of a function template with a deduced
16386 // return type (yet).
16387 if (D.getDeclSpec().hasAutoTypeSpec()) {
16388 // If the placeholder introduces a non-deduced trailing return type,
16389 // we can still delay parsing it.
16390 if (D.getNumTypeObjects()) {
16391 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
16392 if (Outer.Kind == DeclaratorChunk::Function &&
16393 Outer.Fun.hasTrailingReturnType()) {
16394 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
16395 return Ty.isNull() || !Ty->isUndeducedType();
16396 }
16397 }
16398 return false;
16399 }
16400
16401 return true;
16402}
16403
16405 // We cannot skip the body of a function (or function template) which is
16406 // constexpr, since we may need to evaluate its body in order to parse the
16407 // rest of the file.
16408 // We cannot skip the body of a function with an undeduced return type,
16409 // because any callers of that function need to know the type.
16410 if (const FunctionDecl *FD = D->getAsFunction()) {
16411 if (FD->isConstexpr())
16412 return false;
16413 // We can't simply call Type::isUndeducedType here, because inside template
16414 // auto can be deduced to a dependent type, which is not considered
16415 // "undeduced".
16416 if (FD->getReturnType()->getContainedDeducedType())
16417 return false;
16418 }
16419 return Consumer.shouldSkipFunctionBody(D);
16420}
16421
16423 if (!Decl)
16424 return nullptr;
16425 if (FunctionDecl *FD = Decl->getAsFunction())
16426 FD->setHasSkippedBody();
16427 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
16428 MD->setHasSkippedBody();
16429 return Decl;
16430}
16431
16432/// RAII object that pops an ExpressionEvaluationContext when exiting a function
16433/// body.
16435public:
16436 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
16438 if (!IsLambda)
16439 S.PopExpressionEvaluationContext();
16440 }
16441
16442private:
16443 Sema &S;
16444 bool IsLambda = false;
16445};
16446
16448 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
16449
16450 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
16451 auto [It, Inserted] = EscapeInfo.try_emplace(BD);
16452 if (!Inserted)
16453 return It->second;
16454
16455 bool R = false;
16456 const BlockDecl *CurBD = BD;
16457
16458 do {
16459 R = !CurBD->doesNotEscape();
16460 if (R)
16461 break;
16462 CurBD = CurBD->getParent()->getInnermostBlockDecl();
16463 } while (CurBD);
16464
16465 return It->second = R;
16466 };
16467
16468 // If the location where 'self' is implicitly retained is inside a escaping
16469 // block, emit a diagnostic.
16470 for (const std::pair<SourceLocation, const BlockDecl *> &P :
16472 if (IsOrNestedInEscapingBlock(P.second))
16473 S.Diag(P.first, diag::warn_implicitly_retains_self)
16474 << FixItHint::CreateInsertion(P.first, "self->");
16475}
16476
16477static bool methodHasName(const FunctionDecl *FD, StringRef Name) {
16478 return isa<CXXMethodDecl>(FD) && FD->param_empty() &&
16479 FD->getDeclName().isIdentifier() && FD->getName() == Name;
16480}
16481
16483 return methodHasName(FD, "get_return_object");
16484}
16485
16487 return FD->isStatic() &&
16488 methodHasName(FD, "get_return_object_on_allocation_failure");
16489}
16490
16493 if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>())
16494 return;
16495 // Allow some_promise_type::get_return_object().
16497 return;
16498 if (!FD->hasAttr<CoroWrapperAttr>())
16499 Diag(FD->getLocation(), diag::err_coroutine_return_type) << RD;
16500}
16501
16502Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, bool IsInstantiation,
16503 bool RetainFunctionScopeInfo) {
16505 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
16506
16507 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
16508 FD->addAttr(StrictFPAttr::CreateImplicit(Context));
16509
16510 SourceLocation AnalysisLoc;
16511 if (Body)
16512 AnalysisLoc = Body->getEndLoc();
16513 else if (FD)
16514 AnalysisLoc = FD->getEndLoc();
16516 AnalysisWarnings.getPolicyInEffectAt(AnalysisLoc);
16517 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
16518
16519 // If we skip function body, we can't tell if a function is a coroutine.
16520 if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) {
16521 if (FSI->isCoroutine())
16523 else
16525 }
16526
16527 // Diagnose invalid SYCL kernel entry point function declarations
16528 // and build SYCLKernelCallStmts for valid ones.
16529 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLKernelEntryPointAttr>()) {
16530 SYCLKernelEntryPointAttr *SKEPAttr =
16531 FD->getAttr<SYCLKernelEntryPointAttr>();
16532 if (FD->isDefaulted()) {
16533 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16534 << SKEPAttr << diag::InvalidSKEPReason::DefaultedFn;
16535 SKEPAttr->setInvalidAttr();
16536 } else if (FD->isDeleted()) {
16537 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16538 << SKEPAttr << diag::InvalidSKEPReason::DeletedFn;
16539 SKEPAttr->setInvalidAttr();
16540 } else if (FSI->isCoroutine()) {
16541 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16542 << SKEPAttr << diag::InvalidSKEPReason::Coroutine;
16543 SKEPAttr->setInvalidAttr();
16544 } else if (Body && isa<CXXTryStmt>(Body)) {
16545 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16546 << SKEPAttr << diag::InvalidSKEPReason::FunctionTryBlock;
16547 SKEPAttr->setInvalidAttr();
16548 }
16549
16550 if (Body && !FD->isTemplated() && !SKEPAttr->isInvalidAttr()) {
16551 StmtResult SR =
16553 if (SR.isInvalid())
16554 return nullptr;
16555 Body = SR.get();
16556 }
16557 }
16558
16559 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLExternalAttr>()) {
16560 SYCLExternalAttr *SEAttr = FD->getAttr<SYCLExternalAttr>();
16561 if (FD->isDeletedAsWritten())
16562 Diag(SEAttr->getLocation(),
16563 diag::err_sycl_external_invalid_deleted_function)
16564 << SEAttr;
16565 }
16566
16567 {
16568 // Do not call PopExpressionEvaluationContext() if it is a lambda because
16569 // one is already popped when finishing the lambda in BuildLambdaExpr().
16570 // This is meant to pop the context added in ActOnStartOfFunctionDef().
16571 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
16572 if (FD) {
16573 // The function body and the DefaultedOrDeletedInfo, if present, use
16574 // the same storage; don't overwrite the latter if the former is null
16575 // (the body is initialised to null anyway, so even if the latter isn't
16576 // present, this would still be a no-op).
16577 if (Body)
16578 FD->setBody(Body);
16579 FD->setWillHaveBody(false);
16580
16581 if (getLangOpts().CPlusPlus14) {
16582 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
16583 FD->getReturnType()->isUndeducedType()) {
16584 // For a function with a deduced result type to return void,
16585 // the result type as written must be 'auto' or 'decltype(auto)',
16586 // possibly cv-qualified or constrained, but not ref-qualified.
16587 if (!FD->getReturnType()->getAs<AutoType>()) {
16588 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
16589 << FD->getReturnType();
16590 FD->setInvalidDecl();
16591 } else {
16592 // Falling off the end of the function is the same as 'return;'.
16593 Expr *Dummy = nullptr;
16595 FD, dcl->getLocation(), Dummy,
16596 FD->getReturnType()->getAs<AutoType>()))
16597 FD->setInvalidDecl();
16598 }
16599 }
16600 } else if (getLangOpts().CPlusPlus && isLambdaCallOperator(FD)) {
16601 // In C++11, we don't use 'auto' deduction rules for lambda call
16602 // operators because we don't support return type deduction.
16603 auto *LSI = getCurLambda();
16604 if (LSI->HasImplicitReturnType) {
16606
16607 // C++11 [expr.prim.lambda]p4:
16608 // [...] if there are no return statements in the compound-statement
16609 // [the deduced type is] the type void
16610 QualType RetType =
16611 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
16612
16613 // Update the return type to the deduced type.
16614 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
16615 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
16616 Proto->getExtProtoInfo()));
16617 }
16618 }
16619
16620 // If the function implicitly returns zero (like 'main') or is naked,
16621 // don't complain about missing return statements.
16622 // Clang implicitly returns 0 in C89 mode, but that's considered an
16623 // extension. The check is necessary to ensure the expected extension
16624 // warning is emitted in C89 mode.
16625 if ((FD->hasImplicitReturnZero() &&
16626 (getLangOpts().CPlusPlus || getLangOpts().C99 || !FD->isMain())) ||
16627 FD->hasAttr<NakedAttr>())
16629
16630 // MSVC permits the use of pure specifier (=0) on function definition,
16631 // defined at class scope, warn about this non-standard construct.
16632 if (getLangOpts().MicrosoftExt && FD->isPureVirtual() &&
16633 !FD->isOutOfLine())
16634 Diag(FD->getLocation(), diag::ext_pure_function_definition);
16635
16636 if (!FD->isInvalidDecl()) {
16637 // Don't diagnose unused parameters of defaulted, deleted or naked
16638 // functions.
16639 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
16640 !FD->hasAttr<NakedAttr>())
16643 FD->getReturnType(), FD);
16644
16645 // If this is a structor, we need a vtable.
16646 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
16647 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
16648 else if (CXXDestructorDecl *Destructor =
16649 dyn_cast<CXXDestructorDecl>(FD))
16650 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
16651
16652 // Try to apply the named return value optimization. We have to check
16653 // if we can do this here because lambdas keep return statements around
16654 // to deduce an implicit return type.
16655 if (FD->getReturnType()->isRecordType() &&
16657 computeNRVO(Body, FSI);
16658 }
16659
16660 // GNU warning -Wmissing-prototypes:
16661 // Warn if a global function is defined without a previous
16662 // prototype declaration. This warning is issued even if the
16663 // definition itself provides a prototype. The aim is to detect
16664 // global functions that fail to be declared in header files.
16665 const FunctionDecl *PossiblePrototype = nullptr;
16666 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
16667 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
16668
16669 if (PossiblePrototype) {
16670 // We found a declaration that is not a prototype,
16671 // but that could be a zero-parameter prototype
16672 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
16673 TypeLoc TL = TI->getTypeLoc();
16675 Diag(PossiblePrototype->getLocation(),
16676 diag::note_declaration_not_a_prototype)
16677 << (FD->getNumParams() != 0)
16679 FTL.getRParenLoc(), "void")
16680 : FixItHint{});
16681 }
16682 } else {
16683 // Returns true if the token beginning at this Loc is `const`.
16684 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
16685 const LangOptions &LangOpts) {
16686 FileIDAndOffset LocInfo = SM.getDecomposedLoc(Loc);
16687 if (LocInfo.first.isInvalid())
16688 return false;
16689
16690 bool Invalid = false;
16691 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
16692 if (Invalid)
16693 return false;
16694
16695 if (LocInfo.second > Buffer.size())
16696 return false;
16697
16698 const char *LexStart = Buffer.data() + LocInfo.second;
16699 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
16700
16701 return StartTok.consume_front("const") &&
16702 (StartTok.empty() || isWhitespace(StartTok[0]) ||
16703 StartTok.starts_with("/*") || StartTok.starts_with("//"));
16704 };
16705
16706 auto findBeginLoc = [&]() {
16707 // If the return type has `const` qualifier, we want to insert
16708 // `static` before `const` (and not before the typename).
16709 if ((FD->getReturnType()->isAnyPointerType() &&
16712 // But only do this if we can determine where the `const` is.
16713
16714 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
16715 getLangOpts()))
16716
16717 return FD->getBeginLoc();
16718 }
16719 return FD->getTypeSpecStartLoc();
16720 };
16722 diag::note_static_for_internal_linkage)
16723 << /* function */ 1
16724 << (FD->getStorageClass() == SC_None
16725 ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
16726 : FixItHint{});
16727 }
16728 }
16729
16730 // We might not have found a prototype because we didn't wish to warn on
16731 // the lack of a missing prototype. Try again without the checks for
16732 // whether we want to warn on the missing prototype.
16733 if (!PossiblePrototype)
16734 (void)FindPossiblePrototype(FD, PossiblePrototype);
16735
16736 // If the function being defined does not have a prototype, then we may
16737 // need to diagnose it as changing behavior in C23 because we now know
16738 // whether the function accepts arguments or not. This only handles the
16739 // case where the definition has no prototype but does have parameters
16740 // and either there is no previous potential prototype, or the previous
16741 // potential prototype also has no actual prototype. This handles cases
16742 // like:
16743 // void f(); void f(a) int a; {}
16744 // void g(a) int a; {}
16745 // See MergeFunctionDecl() for other cases of the behavior change
16746 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
16747 // type without a prototype.
16748 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
16749 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
16750 !PossiblePrototype->isImplicit()))) {
16751 // The function definition has parameters, so this will change behavior
16752 // in C23. If there is a possible prototype, it comes before the
16753 // function definition.
16754 // FIXME: The declaration may have already been diagnosed as being
16755 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
16756 // there's no way to test for the "changes behavior" condition in
16757 // SemaType.cpp when forming the declaration's function type. So, we do
16758 // this awkward dance instead.
16759 //
16760 // If we have a possible prototype and it declares a function with a
16761 // prototype, we don't want to diagnose it; if we have a possible
16762 // prototype and it has no prototype, it may have already been
16763 // diagnosed in SemaType.cpp as deprecated depending on whether
16764 // -Wstrict-prototypes is enabled. If we already warned about it being
16765 // deprecated, add a note that it also changes behavior. If we didn't
16766 // warn about it being deprecated (because the diagnostic is not
16767 // enabled), warn now that it is deprecated and changes behavior.
16768
16769 // This K&R C function definition definitely changes behavior in C23,
16770 // so diagnose it.
16771 Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
16772 << /*definition*/ 1 << /* not supported in C23 */ 0;
16773
16774 // If we have a possible prototype for the function which is a user-
16775 // visible declaration, we already tested that it has no prototype.
16776 // This will change behavior in C23. This gets a warning rather than a
16777 // note because it's the same behavior-changing problem as with the
16778 // definition.
16779 if (PossiblePrototype)
16780 Diag(PossiblePrototype->getLocation(),
16781 diag::warn_non_prototype_changes_behavior)
16782 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
16783 << /*definition*/ 1;
16784 }
16785
16786 // Warn on CPUDispatch with an actual body.
16787 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
16788 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
16789 if (!CmpndBody->body_empty())
16790 Diag(CmpndBody->body_front()->getBeginLoc(),
16791 diag::warn_dispatch_body_ignored);
16792
16793 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
16794 const CXXMethodDecl *KeyFunction;
16795 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
16796 MD->isVirtual() &&
16797 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
16798 MD == KeyFunction->getCanonicalDecl()) {
16799 // Update the key-function state if necessary for this ABI.
16800 if (FD->isInlined() &&
16801 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
16802 Context.setNonKeyFunction(MD);
16803
16804 // If the newly-chosen key function is already defined, then we
16805 // need to mark the vtable as used retroactively.
16806 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
16807 const FunctionDecl *Definition;
16808 if (KeyFunction && KeyFunction->isDefined(Definition))
16809 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
16810 } else {
16811 // We just defined they key function; mark the vtable as used.
16812 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
16813 }
16814 }
16815 }
16816
16817 assert((FD == getCurFunctionDecl(/*AllowLambdas=*/true)) &&
16818 "Function parsing confused");
16819 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
16820 assert(MD == getCurMethodDecl() && "Method parsing confused");
16821 MD->setBody(Body);
16822 if (!MD->isInvalidDecl()) {
16824 MD->getReturnType(), MD);
16825
16826 if (Body)
16827 computeNRVO(Body, FSI);
16828 }
16829 if (FSI->ObjCShouldCallSuper) {
16830 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
16831 << MD->getSelector().getAsString();
16832 FSI->ObjCShouldCallSuper = false;
16833 }
16835 const ObjCMethodDecl *InitMethod = nullptr;
16836 bool isDesignated =
16837 MD->isDesignatedInitializerForTheInterface(&InitMethod);
16838 assert(isDesignated && InitMethod);
16839 (void)isDesignated;
16840
16841 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
16842 auto IFace = MD->getClassInterface();
16843 if (!IFace)
16844 return false;
16845 auto SuperD = IFace->getSuperClass();
16846 if (!SuperD)
16847 return false;
16848 return SuperD->getIdentifier() ==
16849 ObjC().NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
16850 };
16851 // Don't issue this warning for unavailable inits or direct subclasses
16852 // of NSObject.
16853 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
16854 Diag(MD->getLocation(),
16855 diag::warn_objc_designated_init_missing_super_call);
16856 Diag(InitMethod->getLocation(),
16857 diag::note_objc_designated_init_marked_here);
16858 }
16860 }
16861 if (FSI->ObjCWarnForNoInitDelegation) {
16862 // Don't issue this warning for unavailable inits.
16863 if (!MD->isUnavailable())
16864 Diag(MD->getLocation(),
16865 diag::warn_objc_secondary_init_missing_init_call);
16866 FSI->ObjCWarnForNoInitDelegation = false;
16867 }
16868
16870 } else {
16871 // Parsing the function declaration failed in some way. Pop the fake scope
16872 // we pushed on.
16873 PopFunctionScopeInfo(ActivePolicy, dcl);
16874 return nullptr;
16875 }
16876
16877 if (Body && FSI->HasPotentialAvailabilityViolations)
16879
16880 assert(!FSI->ObjCShouldCallSuper &&
16881 "This should only be set for ObjC methods, which should have been "
16882 "handled in the block above.");
16883
16884 // Verify and clean out per-function state.
16885 if (Body && (!FD || !FD->isDefaulted())) {
16886 // C++ constructors that have function-try-blocks can't have return
16887 // statements in the handlers of that block. (C++ [except.handle]p14)
16888 // Verify this.
16889 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
16891
16892 // Verify that gotos and switch cases don't jump into scopes illegally.
16893 if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
16895
16896 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
16897 if (!Destructor->getParent()->isDependentType())
16899
16901 Destructor->getParent());
16902 }
16903
16904 // If any errors have occurred, clear out any temporaries that may have
16905 // been leftover. This ensures that these temporaries won't be picked up
16906 // for deletion in some later function.
16909 getDiagnostics().getSuppressAllDiagnostics()) {
16911 }
16913 // Since the body is valid, issue any analysis-based warnings that are
16914 // enabled.
16915 ActivePolicy = &WP;
16916 }
16917
16918 if (!IsInstantiation && FD &&
16919 (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) &&
16920 !FD->isInvalidDecl() &&
16922 FD->setInvalidDecl();
16923
16924 if (FD && FD->hasAttr<NakedAttr>()) {
16925 for (const Stmt *S : Body->children()) {
16926 // Allow local register variables without initializer as they don't
16927 // require prologue.
16928 bool RegisterVariables = false;
16929 if (auto *DS = dyn_cast<DeclStmt>(S)) {
16930 for (const auto *Decl : DS->decls()) {
16931 if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
16932 RegisterVariables =
16933 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
16934 if (!RegisterVariables)
16935 break;
16936 }
16937 }
16938 }
16939 if (RegisterVariables)
16940 continue;
16941 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
16942 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
16943 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
16944 FD->setInvalidDecl();
16945 break;
16946 }
16947 }
16948 }
16949
16950 assert(ExprCleanupObjects.size() ==
16951 ExprEvalContexts.back().NumCleanupObjects &&
16952 "Leftover temporaries in function");
16953 assert(!Cleanup.exprNeedsCleanups() &&
16954 "Unaccounted cleanups in function");
16955 assert(MaybeODRUseExprs.empty() &&
16956 "Leftover expressions for odr-use checking");
16957 }
16958 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
16959 // the declaration context below. Otherwise, we're unable to transform
16960 // 'this' expressions when transforming immediate context functions.
16961
16962 if (FD)
16964
16965 if (!IsInstantiation)
16967
16968 if (!RetainFunctionScopeInfo)
16969 PopFunctionScopeInfo(ActivePolicy, dcl);
16970 // If any errors have occurred, clear out any temporaries that may have
16971 // been leftover. This ensures that these temporaries won't be picked up for
16972 // deletion in some later function.
16975 }
16976
16977 if (FD && (LangOpts.isTargetDevice() || LangOpts.CUDA ||
16978 (LangOpts.OpenMP && !LangOpts.OMPTargetTriples.empty()))) {
16979 auto ES = getEmissionStatus(FD);
16983 }
16984
16985 if (FD && !FD->isDeleted())
16986 checkTypeSupport(FD->getType(), FD->getLocation(), FD);
16987
16988 return dcl;
16989}
16990
16991/// When we finish delayed parsing of an attribute, we must attach it to the
16992/// relevant Decl.
16994 ParsedAttributes &Attrs) {
16995 // Always attach attributes to the underlying decl.
16996 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
16997 D = TD->getTemplatedDecl();
16998 ProcessDeclAttributeList(S, D, Attrs);
16999 ProcessAPINotes(D);
17000
17001 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
17002 if (Method->isStatic())
17004}
17005
17007 IdentifierInfo &II, Scope *S) {
17008 // It is not valid to implicitly define a function in C23.
17009 assert(LangOpts.implicitFunctionsAllowed() &&
17010 "Implicit function declarations aren't allowed in this language mode");
17011
17012 // Find the scope in which the identifier is injected and the corresponding
17013 // DeclContext.
17014 // FIXME: C89 does not say what happens if there is no enclosing block scope.
17015 // In that case, we inject the declaration into the translation unit scope
17016 // instead.
17017 Scope *BlockScope = S;
17018 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
17019 BlockScope = BlockScope->getParent();
17020
17021 // Loop until we find a DeclContext that is either a function/method or the
17022 // translation unit, which are the only two valid places to implicitly define
17023 // a function. This avoids accidentally defining the function within a tag
17024 // declaration, for example.
17025 Scope *ContextScope = BlockScope;
17026 while (!ContextScope->getEntity() ||
17027 (!ContextScope->getEntity()->isFunctionOrMethod() &&
17028 !ContextScope->getEntity()->isTranslationUnit()))
17029 ContextScope = ContextScope->getParent();
17030 ContextRAII SavedContext(*this, ContextScope->getEntity());
17031
17032 // Before we produce a declaration for an implicitly defined
17033 // function, see whether there was a locally-scoped declaration of
17034 // this name as a function or variable. If so, use that
17035 // (non-visible) declaration, and complain about it.
17036 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
17037 if (ExternCPrev) {
17038 // We still need to inject the function into the enclosing block scope so
17039 // that later (non-call) uses can see it.
17040 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
17041
17042 // C89 footnote 38:
17043 // If in fact it is not defined as having type "function returning int",
17044 // the behavior is undefined.
17045 if (!isa<FunctionDecl>(ExternCPrev) ||
17046 !Context.typesAreCompatible(
17047 cast<FunctionDecl>(ExternCPrev)->getType(),
17048 Context.getFunctionNoProtoType(Context.IntTy))) {
17049 Diag(Loc, diag::ext_use_out_of_scope_declaration)
17050 << ExternCPrev << !getLangOpts().C99;
17051 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
17052 return ExternCPrev;
17053 }
17054 }
17055
17056 // Extension in C99 (defaults to error). Legal in C89, but warn about it.
17057 unsigned diag_id;
17058 if (II.getName().starts_with("__builtin_"))
17059 diag_id = diag::warn_builtin_unknown;
17060 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
17061 else if (getLangOpts().C99)
17062 diag_id = diag::ext_implicit_function_decl_c99;
17063 else
17064 diag_id = diag::warn_implicit_function_decl;
17065
17066 TypoCorrection Corrected;
17067 // Because typo correction is expensive, only do it if the implicit
17068 // function declaration is going to be treated as an error.
17069 //
17070 // Perform the correction before issuing the main diagnostic, as some
17071 // consumers use typo-correction callbacks to enhance the main diagnostic.
17072 if (S && !ExternCPrev &&
17073 (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {
17075 Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
17076 S, nullptr, CCC, CorrectTypoKind::NonError);
17077 }
17078
17079 Diag(Loc, diag_id) << &II;
17080 if (Corrected) {
17081 // If the correction is going to suggest an implicitly defined function,
17082 // skip the correction as not being a particularly good idea.
17083 bool Diagnose = true;
17084 if (const auto *D = Corrected.getCorrectionDecl())
17085 Diagnose = !D->isImplicit();
17086 if (Diagnose)
17087 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
17088 /*ErrorRecovery*/ false);
17089 }
17090
17091 // If we found a prior declaration of this function, don't bother building
17092 // another one. We've already pushed that one into scope, so there's nothing
17093 // more to do.
17094 if (ExternCPrev)
17095 return ExternCPrev;
17096
17097 // Set a Declarator for the implicit definition: int foo();
17098 const char *Dummy;
17099 AttributeFactory attrFactory;
17100 DeclSpec DS(attrFactory);
17101 unsigned DiagID;
17102 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
17103 Context.getPrintingPolicy());
17104 (void)Error; // Silence warning.
17105 assert(!Error && "Error setting up implicit decl!");
17106 SourceLocation NoLoc;
17108 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
17109 /*IsAmbiguous=*/false,
17110 /*LParenLoc=*/NoLoc,
17111 /*Params=*/nullptr,
17112 /*NumParams=*/0,
17113 /*EllipsisLoc=*/NoLoc,
17114 /*RParenLoc=*/NoLoc,
17115 /*RefQualifierIsLvalueRef=*/true,
17116 /*RefQualifierLoc=*/NoLoc,
17117 /*MutableLoc=*/NoLoc, EST_None,
17118 /*ESpecRange=*/SourceRange(),
17119 /*Exceptions=*/nullptr,
17120 /*ExceptionRanges=*/nullptr,
17121 /*NumExceptions=*/0,
17122 /*NoexceptExpr=*/nullptr,
17123 /*ExceptionSpecTokens=*/nullptr,
17124 /*DeclsInPrototype=*/{}, Loc, Loc,
17125 D),
17126 std::move(DS.getAttributes()), SourceLocation());
17127 D.SetIdentifier(&II, Loc);
17128
17129 // Insert this function into the enclosing block scope.
17130 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
17131 FD->setImplicit();
17132
17134
17135 return FD;
17136}
17137
17139 FunctionDecl *FD) {
17140 if (FD->isInvalidDecl())
17141 return;
17142
17143 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
17144 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
17145 return;
17146
17147 UnsignedOrNone AlignmentParam = std::nullopt;
17148 bool IsNothrow = false;
17149 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
17150 return;
17151
17152 // C++2a [basic.stc.dynamic.allocation]p4:
17153 // An allocation function that has a non-throwing exception specification
17154 // indicates failure by returning a null pointer value. Any other allocation
17155 // function never returns a null pointer value and indicates failure only by
17156 // throwing an exception [...]
17157 //
17158 // However, -fcheck-new invalidates this possible assumption, so don't add
17159 // NonNull when that is enabled.
17160 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&
17161 !getLangOpts().CheckNew)
17162 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
17163
17164 // C++2a [basic.stc.dynamic.allocation]p2:
17165 // An allocation function attempts to allocate the requested amount of
17166 // storage. [...] If the request succeeds, the value returned by a
17167 // replaceable allocation function is a [...] pointer value p0 different
17168 // from any previously returned value p1 [...]
17169 //
17170 // However, this particular information is being added in codegen,
17171 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
17172
17173 // C++2a [basic.stc.dynamic.allocation]p2:
17174 // An allocation function attempts to allocate the requested amount of
17175 // storage. If it is successful, it returns the address of the start of a
17176 // block of storage whose length in bytes is at least as large as the
17177 // requested size.
17178 if (!FD->hasAttr<AllocSizeAttr>()) {
17179 FD->addAttr(AllocSizeAttr::CreateImplicit(
17180 Context, /*ElemSizeParam=*/ParamIdx(1, FD),
17181 /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
17182 }
17183
17184 // C++2a [basic.stc.dynamic.allocation]p3:
17185 // For an allocation function [...], the pointer returned on a successful
17186 // call shall represent the address of storage that is aligned as follows:
17187 // (3.1) If the allocation function takes an argument of type
17188 // std​::​align_­val_­t, the storage will have the alignment
17189 // specified by the value of this argument.
17190 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
17191 FD->addAttr(AllocAlignAttr::CreateImplicit(
17192 Context, ParamIdx(*AlignmentParam, FD), FD->getLocation()));
17193 }
17194
17195 // FIXME:
17196 // C++2a [basic.stc.dynamic.allocation]p3:
17197 // For an allocation function [...], the pointer returned on a successful
17198 // call shall represent the address of storage that is aligned as follows:
17199 // (3.2) Otherwise, if the allocation function is named operator new[],
17200 // the storage is aligned for any object that does not have
17201 // new-extended alignment ([basic.align]) and is no larger than the
17202 // requested size.
17203 // (3.3) Otherwise, the storage is aligned for any object that does not
17204 // have new-extended alignment and is of the requested size.
17205}
17206
17208 if (FD->isInvalidDecl())
17209 return;
17210
17211 // If this is a built-in function, map its builtin attributes to
17212 // actual attributes.
17213 if (unsigned BuiltinID = FD->getBuiltinID()) {
17214 // Handle printf-formatting attributes.
17215 unsigned FormatIdx;
17216 bool HasVAListArg;
17217 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
17218 if (!FD->hasAttr<FormatAttr>()) {
17219 const char *fmt = "printf";
17220 unsigned int NumParams = FD->getNumParams();
17221 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
17222 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
17223 fmt = "NSString";
17224 FD->addAttr(FormatAttr::CreateImplicit(Context,
17225 &Context.Idents.get(fmt),
17226 FormatIdx+1,
17227 HasVAListArg ? 0 : FormatIdx+2,
17228 FD->getLocation()));
17229 }
17230 }
17231 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
17232 HasVAListArg)) {
17233 if (!FD->hasAttr<FormatAttr>())
17234 FD->addAttr(FormatAttr::CreateImplicit(Context,
17235 &Context.Idents.get("scanf"),
17236 FormatIdx+1,
17237 HasVAListArg ? 0 : FormatIdx+2,
17238 FD->getLocation()));
17239 }
17240
17241 // Handle automatically recognized callbacks.
17242 SmallVector<int, 4> Encoding;
17243 if (!FD->hasAttr<CallbackAttr>() &&
17244 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
17245 FD->addAttr(CallbackAttr::CreateImplicit(
17246 Context, Encoding.data(), Encoding.size(), FD->getLocation()));
17247
17248 // Mark const if we don't care about errno and/or floating point exceptions
17249 // that are the only thing preventing the function from being const. This
17250 // allows IRgen to use LLVM intrinsics for such functions.
17251 bool NoExceptions =
17253 bool ConstWithoutErrnoAndExceptions =
17254 Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(BuiltinID);
17255 bool ConstWithoutExceptions =
17256 Context.BuiltinInfo.isConstWithoutExceptions(BuiltinID);
17257 if (!FD->hasAttr<ConstAttr>() &&
17258 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
17259 (!ConstWithoutErrnoAndExceptions ||
17260 (!getLangOpts().MathErrno && NoExceptions)) &&
17261 (!ConstWithoutExceptions || NoExceptions))
17262 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
17263
17264 // We make "fma" on GNU or Windows const because we know it does not set
17265 // errno in those environments even though it could set errno based on the
17266 // C standard.
17267 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
17268 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
17269 !FD->hasAttr<ConstAttr>()) {
17270 switch (BuiltinID) {
17271 case Builtin::BI__builtin_fma:
17272 case Builtin::BI__builtin_fmaf:
17273 case Builtin::BI__builtin_fmal:
17274 case Builtin::BIfma:
17275 case Builtin::BIfmaf:
17276 case Builtin::BIfmal:
17277 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
17278 break;
17279 default:
17280 break;
17281 }
17282 }
17283
17284 SmallVector<int, 4> Indxs;
17286 if (Context.BuiltinInfo.isNonNull(BuiltinID, Indxs, OptMode) &&
17287 !FD->hasAttr<NonNullAttr>()) {
17289 for (int I : Indxs) {
17290 ParmVarDecl *PVD = FD->getParamDecl(I);
17291 QualType T = PVD->getType();
17292 T = Context.getAttributedType(attr::TypeNonNull, T, T);
17293 PVD->setType(T);
17294 }
17295 } else if (OptMode == Builtin::Info::NonNullMode::Optimizing) {
17297 for (int I : Indxs)
17298 ParamIndxs.push_back(ParamIdx(I + 1, FD));
17299 FD->addAttr(NonNullAttr::CreateImplicit(Context, ParamIndxs.data(),
17300 ParamIndxs.size()));
17301 }
17302 }
17303 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
17304 !FD->hasAttr<ReturnsTwiceAttr>())
17305 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
17306 FD->getLocation()));
17307 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
17308 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
17309 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
17310 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
17311 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
17312 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
17313 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
17314 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
17315 // Add the appropriate attribute, depending on the CUDA compilation mode
17316 // and which target the builtin belongs to. For example, during host
17317 // compilation, aux builtins are __device__, while the rest are __host__.
17318 if (getLangOpts().CUDAIsDevice !=
17319 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
17320 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
17321 else
17322 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
17323 }
17324
17325 // Add known guaranteed alignment for allocation functions.
17326 switch (BuiltinID) {
17327 case Builtin::BImemalign:
17328 case Builtin::BIaligned_alloc:
17329 if (!FD->hasAttr<AllocAlignAttr>())
17330 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
17331 FD->getLocation()));
17332 break;
17333 default:
17334 break;
17335 }
17336
17337 // Add allocsize attribute for allocation functions.
17338 switch (BuiltinID) {
17339 case Builtin::BIcalloc:
17340 FD->addAttr(AllocSizeAttr::CreateImplicit(
17341 Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
17342 break;
17343 case Builtin::BImemalign:
17344 case Builtin::BIaligned_alloc:
17345 case Builtin::BIrealloc:
17346 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
17347 ParamIdx(), FD->getLocation()));
17348 break;
17349 case Builtin::BImalloc:
17350 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
17351 ParamIdx(), FD->getLocation()));
17352 break;
17353 default:
17354 break;
17355 }
17356 }
17357
17362
17363 // If C++ exceptions are enabled but we are told extern "C" functions cannot
17364 // throw, add an implicit nothrow attribute to any extern "C" function we come
17365 // across.
17366 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
17367 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
17368 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
17369 if (!FPT || FPT->getExceptionSpecType() == EST_None)
17370 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
17371 }
17372
17373 IdentifierInfo *Name = FD->getIdentifier();
17374 if (!Name)
17375 return;
17378 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
17380 // Okay: this could be a libc/libm/Objective-C function we know
17381 // about.
17382 } else
17383 return;
17384
17385 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
17386 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
17387 // target-specific builtins, perhaps?
17388 if (!FD->hasAttr<FormatAttr>())
17389 FD->addAttr(FormatAttr::CreateImplicit(Context,
17390 &Context.Idents.get("printf"), 2,
17391 Name->isStr("vasprintf") ? 0 : 3,
17392 FD->getLocation()));
17393 }
17394
17395 if (Name->isStr("__CFStringMakeConstantString")) {
17396 // We already have a __builtin___CFStringMakeConstantString,
17397 // but builds that use -fno-constant-cfstrings don't go through that.
17398 if (!FD->hasAttr<FormatArgAttr>())
17399 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
17400 FD->getLocation()));
17401 }
17402}
17403
17405 TypeSourceInfo *TInfo) {
17406 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
17407 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
17408
17409 if (!TInfo) {
17410 assert(D.isInvalidType() && "no declarator info for valid type");
17411 TInfo = Context.getTrivialTypeSourceInfo(T);
17412 }
17413
17414 // Scope manipulation handled by caller.
17415 TypedefDecl *NewTD =
17417 D.getIdentifierLoc(), D.getIdentifier(), TInfo);
17418
17419 // Bail out immediately if we have an invalid declaration.
17420 if (D.isInvalidType()) {
17421 NewTD->setInvalidDecl();
17422 return NewTD;
17423 }
17424
17426 if (CurContext->isFunctionOrMethod())
17427 Diag(NewTD->getLocation(), diag::err_module_private_local)
17428 << 2 << NewTD
17432 else
17433 NewTD->setModulePrivate();
17434 }
17435
17436 // C++ [dcl.typedef]p8:
17437 // If the typedef declaration defines an unnamed class (or
17438 // enum), the first typedef-name declared by the declaration
17439 // to be that class type (or enum type) is used to denote the
17440 // class type (or enum type) for linkage purposes only.
17441 // We need to check whether the type was declared in the declaration.
17442 switch (D.getDeclSpec().getTypeSpecType()) {
17443 case TST_enum:
17444 case TST_struct:
17445 case TST_interface:
17446 case TST_union:
17447 case TST_class: {
17448 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
17449 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
17450 break;
17451 }
17452
17453 default:
17454 break;
17455 }
17456
17457 return NewTD;
17458}
17459
17461 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
17462 QualType T = TI->getType();
17463
17464 if (T->isDependentType())
17465 return false;
17466
17467 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17468 // integral type; any cv-qualification is ignored.
17469 // C23 6.7.3.3p5: The underlying type of the enumeration is the unqualified,
17470 // non-atomic version of the type specified by the type specifiers in the
17471 // specifier qualifier list.
17472 // Because of how odd C's rule is, we'll let the user know that operations
17473 // involving the enumeration type will be non-atomic.
17474 if (T->isAtomicType())
17475 Diag(UnderlyingLoc, diag::warn_atomic_stripped_in_enum);
17476
17477 Qualifiers Q = T.getQualifiers();
17478 std::optional<unsigned> QualSelect;
17479 if (Q.hasConst() && Q.hasVolatile())
17480 QualSelect = diag::CVQualList::Both;
17481 else if (Q.hasConst())
17482 QualSelect = diag::CVQualList::Const;
17483 else if (Q.hasVolatile())
17484 QualSelect = diag::CVQualList::Volatile;
17485
17486 if (QualSelect)
17487 Diag(UnderlyingLoc, diag::warn_cv_stripped_in_enum) << *QualSelect;
17488
17489 T = T.getAtomicUnqualifiedType();
17490
17491 // This doesn't use 'isIntegralType' despite the error message mentioning
17492 // integral type because isIntegralType would also allow enum types in C.
17493 if (const BuiltinType *BT = T->getAs<BuiltinType>())
17494 if (BT->isInteger())
17495 return false;
17496
17497 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying)
17498 << T << T->isBitIntType();
17499}
17500
17502 QualType EnumUnderlyingTy, bool IsFixed,
17503 const EnumDecl *Prev) {
17504 if (IsScoped != Prev->isScoped()) {
17505 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
17506 << Prev->isScoped();
17507 Diag(Prev->getLocation(), diag::note_previous_declaration);
17508 return true;
17509 }
17510
17511 if (IsFixed && Prev->isFixed()) {
17512 if (!EnumUnderlyingTy->isDependentType() &&
17513 !Prev->getIntegerType()->isDependentType() &&
17514 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
17515 Prev->getIntegerType())) {
17516 // TODO: Highlight the underlying type of the redeclaration.
17517 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
17518 << EnumUnderlyingTy << Prev->getIntegerType();
17519 Diag(Prev->getLocation(), diag::note_previous_declaration)
17520 << Prev->getIntegerTypeRange();
17521 return true;
17522 }
17523 } else if (IsFixed != Prev->isFixed()) {
17524 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
17525 << Prev->isFixed();
17526 Diag(Prev->getLocation(), diag::note_previous_declaration);
17527 return true;
17528 }
17529
17530 return false;
17531}
17532
17533/// Get diagnostic %select index for tag kind for
17534/// redeclaration diagnostic message.
17535/// WARNING: Indexes apply to particular diagnostics only!
17536///
17537/// \returns diagnostic %select index.
17539 switch (Tag) {
17541 return 0;
17543 return 1;
17544 case TagTypeKind::Class:
17545 return 2;
17546 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
17547 }
17548}
17549
17550/// Determine if tag kind is a class-key compatible with
17551/// class for redeclaration (class, struct, or __interface).
17552///
17553/// \returns true iff the tag kind is compatible.
17555{
17556 return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class ||
17558}
17559
17561 if (isa<TypedefDecl>(PrevDecl))
17562 return NonTagKind::Typedef;
17563 else if (isa<TypeAliasDecl>(PrevDecl))
17564 return NonTagKind::TypeAlias;
17565 else if (isa<ClassTemplateDecl>(PrevDecl))
17566 return NonTagKind::Template;
17567 else if (isa<TypeAliasTemplateDecl>(PrevDecl))
17569 else if (isa<TemplateTemplateParmDecl>(PrevDecl))
17571 switch (TTK) {
17574 case TagTypeKind::Class:
17575 return getLangOpts().CPlusPlus ? NonTagKind::NonClass
17577 case TagTypeKind::Union:
17578 return NonTagKind::NonUnion;
17579 case TagTypeKind::Enum:
17580 return NonTagKind::NonEnum;
17581 }
17582 llvm_unreachable("invalid TTK");
17583}
17584
17586 TagTypeKind NewTag, bool isDefinition,
17587 SourceLocation NewTagLoc,
17588 const IdentifierInfo *Name) {
17589 // C++ [dcl.type.elab]p3:
17590 // The class-key or enum keyword present in the
17591 // elaborated-type-specifier shall agree in kind with the
17592 // declaration to which the name in the elaborated-type-specifier
17593 // refers. This rule also applies to the form of
17594 // elaborated-type-specifier that declares a class-name or
17595 // friend class since it can be construed as referring to the
17596 // definition of the class. Thus, in any
17597 // elaborated-type-specifier, the enum keyword shall be used to
17598 // refer to an enumeration (7.2), the union class-key shall be
17599 // used to refer to a union (clause 9), and either the class or
17600 // struct class-key shall be used to refer to a class (clause 9)
17601 // declared using the class or struct class-key.
17602 TagTypeKind OldTag = Previous->getTagKind();
17603 if (OldTag != NewTag &&
17605 return false;
17606
17607 // Tags are compatible, but we might still want to warn on mismatched tags.
17608 // Non-class tags can't be mismatched at this point.
17610 return true;
17611
17612 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
17613 // by our warning analysis. We don't want to warn about mismatches with (eg)
17614 // declarations in system headers that are designed to be specialized, but if
17615 // a user asks us to warn, we should warn if their code contains mismatched
17616 // declarations.
17617 auto IsIgnoredLoc = [&](SourceLocation Loc) {
17618 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
17619 Loc);
17620 };
17621 if (IsIgnoredLoc(NewTagLoc))
17622 return true;
17623
17624 auto IsIgnored = [&](const TagDecl *Tag) {
17625 return IsIgnoredLoc(Tag->getLocation());
17626 };
17627 while (IsIgnored(Previous)) {
17628 Previous = Previous->getPreviousDecl();
17629 if (!Previous)
17630 return true;
17631 OldTag = Previous->getTagKind();
17632 }
17633
17634 bool isTemplate = false;
17635 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
17636 isTemplate = Record->getDescribedClassTemplate();
17637
17639 if (OldTag != NewTag) {
17640 // In a template instantiation, do not offer fix-its for tag mismatches
17641 // since they usually mess up the template instead of fixing the problem.
17642 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
17644 << getRedeclDiagFromTagKind(OldTag);
17645 // FIXME: Note previous location?
17646 }
17647 return true;
17648 }
17649
17650 if (isDefinition) {
17651 // On definitions, check all previous tags and issue a fix-it for each
17652 // one that doesn't match the current tag.
17653 if (Previous->getDefinition()) {
17654 // Don't suggest fix-its for redefinitions.
17655 return true;
17656 }
17657
17658 bool previousMismatch = false;
17659 for (const TagDecl *I : Previous->redecls()) {
17660 if (I->getTagKind() != NewTag) {
17661 // Ignore previous declarations for which the warning was disabled.
17662 if (IsIgnored(I))
17663 continue;
17664
17665 if (!previousMismatch) {
17666 previousMismatch = true;
17667 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
17669 << getRedeclDiagFromTagKind(I->getTagKind());
17670 }
17671 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
17673 << FixItHint::CreateReplacement(I->getInnerLocStart(),
17675 }
17676 }
17677 return true;
17678 }
17679
17680 // Identify the prevailing tag kind: this is the kind of the definition (if
17681 // there is a non-ignored definition), or otherwise the kind of the prior
17682 // (non-ignored) declaration.
17683 const TagDecl *PrevDef = Previous->getDefinition();
17684 if (PrevDef && IsIgnored(PrevDef))
17685 PrevDef = nullptr;
17686 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
17687 if (Redecl->getTagKind() != NewTag) {
17688 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
17690 << getRedeclDiagFromTagKind(OldTag);
17691 Diag(Redecl->getLocation(), diag::note_previous_use);
17692
17693 // If there is a previous definition, suggest a fix-it.
17694 if (PrevDef) {
17695 Diag(NewTagLoc, diag::note_struct_class_suggestion)
17699 }
17700 }
17701
17702 return true;
17703}
17704
17705/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
17706/// from an outer enclosing namespace or file scope inside a friend declaration.
17707/// This should provide the commented out code in the following snippet:
17708/// namespace N {
17709/// struct X;
17710/// namespace M {
17711/// struct Y { friend struct /*N::*/ X; };
17712/// }
17713/// }
17715 SourceLocation NameLoc) {
17716 // While the decl is in a namespace, do repeated lookup of that name and see
17717 // if we get the same namespace back. If we do not, continue until
17718 // translation unit scope, at which point we have a fully qualified NNS.
17721 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
17722 // This tag should be declared in a namespace, which can only be enclosed by
17723 // other namespaces. Bail if there's an anonymous namespace in the chain.
17724 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
17725 if (!Namespace || Namespace->isAnonymousNamespace())
17726 return FixItHint();
17727 IdentifierInfo *II = Namespace->getIdentifier();
17728 Namespaces.push_back(II);
17729 NamedDecl *Lookup = SemaRef.LookupSingleName(
17730 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
17731 if (Lookup == Namespace)
17732 break;
17733 }
17734
17735 // Once we have all the namespaces, reverse them to go outermost first, and
17736 // build an NNS.
17737 SmallString<64> Insertion;
17738 llvm::raw_svector_ostream OS(Insertion);
17739 if (DC->isTranslationUnit())
17740 OS << "::";
17741 std::reverse(Namespaces.begin(), Namespaces.end());
17742 for (auto *II : Namespaces)
17743 OS << II->getName() << "::";
17744 return FixItHint::CreateInsertion(NameLoc, Insertion);
17745}
17746
17747/// Determine whether a tag originally declared in context \p OldDC can
17748/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
17749/// found a declaration in \p OldDC as a previous decl, perhaps through a
17750/// using-declaration).
17752 DeclContext *NewDC) {
17753 OldDC = OldDC->getRedeclContext();
17754 NewDC = NewDC->getRedeclContext();
17755
17756 if (OldDC->Equals(NewDC))
17757 return true;
17758
17759 // In MSVC mode, we allow a redeclaration if the contexts are related (either
17760 // encloses the other).
17761 if (S.getLangOpts().MSVCCompat &&
17762 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
17763 return true;
17764
17765 return false;
17766}
17767
17769Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
17770 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17771 const ParsedAttributesView &Attrs, AccessSpecifier AS,
17772 SourceLocation ModulePrivateLoc,
17773 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
17774 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
17775 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
17776 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
17777 OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
17778 // If this is not a definition, it must have a name.
17779 IdentifierInfo *OrigName = Name;
17780 assert((Name != nullptr || TUK == TagUseKind::Definition) &&
17781 "Nameless record must be a definition!");
17782 assert(TemplateParameterLists.size() == 0 || TUK != TagUseKind::Reference);
17783
17784 OwnedDecl = false;
17786 bool ScopedEnum = ScopedEnumKWLoc.isValid();
17787
17788 // FIXME: Check member specializations more carefully.
17789 bool isMemberSpecialization = false;
17790 bool IsInjectedClassName = false;
17791 bool Invalid = false;
17792
17793 // We only need to do this matching if we have template parameters
17794 // or a scope specifier, which also conveniently avoids this work
17795 // for non-C++ cases.
17796 if (TemplateParameterLists.size() > 0 ||
17797 (SS.isNotEmpty() && TUK != TagUseKind::Reference)) {
17798 TemplateParameterList *TemplateParams =
17800 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
17801 TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);
17802
17803 // C++23 [dcl.type.elab] p2:
17804 // If an elaborated-type-specifier is the sole constituent of a
17805 // declaration, the declaration is ill-formed unless it is an explicit
17806 // specialization, an explicit instantiation or it has one of the
17807 // following forms: [...]
17808 // C++23 [dcl.enum] p1:
17809 // If the enum-head-name of an opaque-enum-declaration contains a
17810 // nested-name-specifier, the declaration shall be an explicit
17811 // specialization.
17812 //
17813 // FIXME: Class template partial specializations can be forward declared
17814 // per CWG2213, but the resolution failed to allow qualified forward
17815 // declarations. This is almost certainly unintentional, so we allow them.
17816 if (TUK == TagUseKind::Declaration && SS.isNotEmpty() &&
17817 !isMemberSpecialization)
17818 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
17820
17821 if (TemplateParams) {
17822 if (Kind == TagTypeKind::Enum) {
17823 Diag(KWLoc, diag::err_enum_template);
17824 return true;
17825 }
17826
17827 if (TemplateParams->size() > 0) {
17828 // This is a declaration or definition of a class template (which may
17829 // be a member of another template).
17830
17831 if (Invalid)
17832 return true;
17833
17834 OwnedDecl = false;
17836 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
17837 AS, ModulePrivateLoc,
17838 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
17839 TemplateParameterLists.data(), SkipBody);
17840 return Result.get();
17841 } else {
17842 // The "template<>" header is extraneous.
17843 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
17844 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
17845 isMemberSpecialization = true;
17846 }
17847 }
17848
17849 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
17850 CheckTemplateDeclScope(S, TemplateParameterLists.back()))
17851 return true;
17852 }
17853
17854 if (TUK == TagUseKind::Friend && Kind == TagTypeKind::Enum) {
17855 // C++23 [dcl.type.elab]p4:
17856 // If an elaborated-type-specifier appears with the friend specifier as
17857 // an entire member-declaration, the member-declaration shall have one
17858 // of the following forms:
17859 // friend class-key nested-name-specifier(opt) identifier ;
17860 // friend class-key simple-template-id ;
17861 // friend class-key nested-name-specifier template(opt)
17862 // simple-template-id ;
17863 //
17864 // Since enum is not a class-key, so declarations like "friend enum E;"
17865 // are ill-formed. Although CWG2363 reaffirms that such declarations are
17866 // invalid, most implementations accept so we issue a pedantic warning.
17867 Diag(KWLoc, diag::ext_enum_friend) << FixItHint::CreateRemoval(
17868 ScopedEnum ? SourceRange(KWLoc, ScopedEnumKWLoc) : KWLoc);
17869 assert(ScopedEnum || !ScopedEnumUsesClassTag);
17870 Diag(KWLoc, diag::note_enum_friend)
17871 << (ScopedEnum + ScopedEnumUsesClassTag);
17872 }
17873
17874 // Figure out the underlying type if this a enum declaration. We need to do
17875 // this early, because it's needed to detect if this is an incompatible
17876 // redeclaration.
17877 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
17878 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
17879
17880 if (Kind == TagTypeKind::Enum) {
17881 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
17882 // No underlying type explicitly specified, or we failed to parse the
17883 // type, default to int.
17884 EnumUnderlying = Context.IntTy.getTypePtr();
17885 } else if (UnderlyingType.get()) {
17886 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17887 // integral type; any cv-qualification is ignored.
17888 // C23 6.7.3.3p5: The underlying type of the enumeration is the
17889 // unqualified, non-atomic version of the type specified by the type
17890 // specifiers in the specifier qualifier list.
17891 TypeSourceInfo *TI = nullptr;
17892 GetTypeFromParser(UnderlyingType.get(), &TI);
17893 EnumUnderlying = TI;
17894
17896 // Recover by falling back to int.
17897 EnumUnderlying = Context.IntTy.getTypePtr();
17898
17901 EnumUnderlying = Context.IntTy.getTypePtr();
17902
17903 // If the underlying type is atomic, we need to adjust the type before
17904 // continuing. This only happens in the case we stored a TypeSourceInfo
17905 // into EnumUnderlying because the other cases are error recovery up to
17906 // this point. But because it's not possible to gin up a TypeSourceInfo
17907 // for a non-atomic type from an atomic one, we'll store into the Type
17908 // field instead. FIXME: it would be nice to have an easy way to get a
17909 // derived TypeSourceInfo which strips qualifiers including the weird
17910 // ones like _Atomic where it forms a different type.
17911 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying);
17912 TI && TI->getType()->isAtomicType())
17913 EnumUnderlying = TI->getType().getAtomicUnqualifiedType().getTypePtr();
17914
17915 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
17916 // For MSVC ABI compatibility, unfixed enums must use an underlying type
17917 // of 'int'. However, if this is an unfixed forward declaration, don't set
17918 // the underlying type unless the user enables -fms-compatibility. This
17919 // makes unfixed forward declared enums incomplete and is more conforming.
17920 if (TUK == TagUseKind::Definition || getLangOpts().MSVCCompat)
17921 EnumUnderlying = Context.IntTy.getTypePtr();
17922 }
17923 }
17924
17925 DeclContext *SearchDC = CurContext;
17926 DeclContext *DC = CurContext;
17927 bool isStdBadAlloc = false;
17928 bool isStdAlignValT = false;
17929
17931 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference)
17933
17934 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
17935 /// implemented asks for structural equivalence checking, the returned decl
17936 /// here is passed back to the parser, allowing the tag body to be parsed.
17937 auto createTagFromNewDecl = [&]() -> TagDecl * {
17938 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
17939 // If there is an identifier, use the location of the identifier as the
17940 // location of the decl, otherwise use the location of the struct/union
17941 // keyword.
17942 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
17943 TagDecl *New = nullptr;
17944
17945 if (Kind == TagTypeKind::Enum) {
17946 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
17947 ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
17948 // If this is an undefined enum, bail.
17949 if (TUK != TagUseKind::Definition && !Invalid)
17950 return nullptr;
17951 if (EnumUnderlying) {
17953 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying))
17955 else
17956 ED->setIntegerType(QualType(cast<const Type *>(EnumUnderlying), 0));
17957 QualType EnumTy = ED->getIntegerType();
17958 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
17959 ? Context.getPromotedIntegerType(EnumTy)
17960 : EnumTy);
17961 }
17962 } else { // struct/union
17963 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17964 nullptr);
17965 }
17966
17967 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
17968 // Add alignment attributes if necessary; these attributes are checked
17969 // when the ASTContext lays out the structure.
17970 //
17971 // It is important for implementing the correct semantics that this
17972 // happen here (in ActOnTag). The #pragma pack stack is
17973 // maintained as a result of parser callbacks which can occur at
17974 // many points during the parsing of a struct declaration (because
17975 // the #pragma tokens are effectively skipped over during the
17976 // parsing of the struct).
17977 if (TUK == TagUseKind::Definition &&
17978 (!SkipBody || !SkipBody->ShouldSkip)) {
17979 if (LangOpts.HLSL)
17980 RD->addAttr(PackedAttr::CreateImplicit(Context));
17983 }
17984 }
17985 New->setLexicalDeclContext(CurContext);
17986 return New;
17987 };
17988
17989 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
17990 if (Name && SS.isNotEmpty()) {
17991 // We have a nested-name tag ('struct foo::bar').
17992
17993 // Check for invalid 'foo::'.
17994 if (SS.isInvalid()) {
17995 Name = nullptr;
17996 goto CreateNewDecl;
17997 }
17998
17999 // If this is a friend or a reference to a class in a dependent
18000 // context, don't try to make a decl for it.
18001 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
18002 DC = computeDeclContext(SS, false);
18003 if (!DC) {
18004 IsDependent = true;
18005 return true;
18006 }
18007 } else {
18008 DC = computeDeclContext(SS, true);
18009 if (!DC) {
18010 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
18011 << SS.getRange();
18012 return true;
18013 }
18014 }
18015
18016 if (RequireCompleteDeclContext(SS, DC))
18017 return true;
18018
18019 SearchDC = DC;
18020 // Look-up name inside 'foo::'.
18022
18023 if (Previous.isAmbiguous())
18024 return true;
18025
18026 if (Previous.empty()) {
18027 // Name lookup did not find anything. However, if the
18028 // nested-name-specifier refers to the current instantiation,
18029 // and that current instantiation has any dependent base
18030 // classes, we might find something at instantiation time: treat
18031 // this as a dependent elaborated-type-specifier.
18032 // But this only makes any sense for reference-like lookups.
18033 if (Previous.wasNotFoundInCurrentInstantiation() &&
18034 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)) {
18035 IsDependent = true;
18036 return true;
18037 }
18038
18039 // A tag 'foo::bar' must already exist.
18040 Diag(NameLoc, diag::err_not_tag_in_scope)
18041 << Kind << Name << DC << SS.getRange();
18042 Name = nullptr;
18043 Invalid = true;
18044 goto CreateNewDecl;
18045 }
18046 } else if (Name) {
18047 // C++14 [class.mem]p14:
18048 // If T is the name of a class, then each of the following shall have a
18049 // name different from T:
18050 // -- every member of class T that is itself a type
18051 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
18052 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
18053 return true;
18054
18055 // If this is a named struct, check to see if there was a previous forward
18056 // declaration or definition.
18057 // FIXME: We're looking into outer scopes here, even when we
18058 // shouldn't be. Doing so can result in ambiguities that we
18059 // shouldn't be diagnosing.
18060 LookupName(Previous, S);
18061
18062 // When declaring or defining a tag, ignore ambiguities introduced
18063 // by types using'ed into this scope.
18064 if (Previous.isAmbiguous() &&
18066 LookupResult::Filter F = Previous.makeFilter();
18067 while (F.hasNext()) {
18068 NamedDecl *ND = F.next();
18069 if (!ND->getDeclContext()->getRedeclContext()->Equals(
18070 SearchDC->getRedeclContext()))
18071 F.erase();
18072 }
18073 F.done();
18074 }
18075
18076 // C++11 [namespace.memdef]p3:
18077 // If the name in a friend declaration is neither qualified nor
18078 // a template-id and the declaration is a function or an
18079 // elaborated-type-specifier, the lookup to determine whether
18080 // the entity has been previously declared shall not consider
18081 // any scopes outside the innermost enclosing namespace.
18082 //
18083 // MSVC doesn't implement the above rule for types, so a friend tag
18084 // declaration may be a redeclaration of a type declared in an enclosing
18085 // scope. They do implement this rule for friend functions.
18086 //
18087 // Does it matter that this should be by scope instead of by
18088 // semantic context?
18089 if (!Previous.empty() && TUK == TagUseKind::Friend) {
18090 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
18091 LookupResult::Filter F = Previous.makeFilter();
18092 bool FriendSawTagOutsideEnclosingNamespace = false;
18093 while (F.hasNext()) {
18094 NamedDecl *ND = F.next();
18096 if (DC->isFileContext() &&
18097 !EnclosingNS->Encloses(ND->getDeclContext())) {
18098 if (getLangOpts().MSVCCompat)
18099 FriendSawTagOutsideEnclosingNamespace = true;
18100 else
18101 F.erase();
18102 }
18103 }
18104 F.done();
18105
18106 // Diagnose this MSVC extension in the easy case where lookup would have
18107 // unambiguously found something outside the enclosing namespace.
18108 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
18109 NamedDecl *ND = Previous.getFoundDecl();
18110 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
18111 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
18112 }
18113 }
18114
18115 // Note: there used to be some attempt at recovery here.
18116 if (Previous.isAmbiguous())
18117 return true;
18118
18119 if (!getLangOpts().CPlusPlus && TUK != TagUseKind::Reference) {
18120 // FIXME: This makes sure that we ignore the contexts associated
18121 // with C structs, unions, and enums when looking for a matching
18122 // tag declaration or definition. See the similar lookup tweak
18123 // in Sema::LookupName; is there a better way to deal with this?
18125 SearchDC = SearchDC->getParent();
18126 } else if (getLangOpts().CPlusPlus) {
18127 // Inside ObjCContainer want to keep it as a lexical decl context but go
18128 // past it (most often to TranslationUnit) to find the semantic decl
18129 // context.
18130 while (isa<ObjCContainerDecl>(SearchDC))
18131 SearchDC = SearchDC->getParent();
18132 }
18133 } else if (getLangOpts().CPlusPlus) {
18134 // Don't use ObjCContainerDecl as the semantic decl context for anonymous
18135 // TagDecl the same way as we skip it for named TagDecl.
18136 while (isa<ObjCContainerDecl>(SearchDC))
18137 SearchDC = SearchDC->getParent();
18138 }
18139
18140 if (Previous.isSingleResult() &&
18141 Previous.getFoundDecl()->isTemplateParameter()) {
18142 // Maybe we will complain about the shadowed template parameter.
18143 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
18144 // Just pretend that we didn't see the previous declaration.
18145 Previous.clear();
18146 }
18147
18148 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
18149 DC->Equals(getStdNamespace())) {
18150 if (Name->isStr("bad_alloc")) {
18151 // This is a declaration of or a reference to "std::bad_alloc".
18152 isStdBadAlloc = true;
18153
18154 // If std::bad_alloc has been implicitly declared (but made invisible to
18155 // name lookup), fill in this implicit declaration as the previous
18156 // declaration, so that the declarations get chained appropriately.
18157 if (Previous.empty() && StdBadAlloc)
18158 Previous.addDecl(getStdBadAlloc());
18159 } else if (Name->isStr("align_val_t")) {
18160 isStdAlignValT = true;
18161 if (Previous.empty() && StdAlignValT)
18162 Previous.addDecl(getStdAlignValT());
18163 }
18164 }
18165
18166 // If we didn't find a previous declaration, and this is a reference
18167 // (or friend reference), move to the correct scope. In C++, we
18168 // also need to do a redeclaration lookup there, just in case
18169 // there's a shadow friend decl.
18170 if (Name && Previous.empty() &&
18171 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
18172 IsTemplateParamOrArg)) {
18173 if (Invalid) goto CreateNewDecl;
18174 assert(SS.isEmpty());
18175
18176 if (TUK == TagUseKind::Reference || IsTemplateParamOrArg) {
18177 // C++ [basic.scope.pdecl]p5:
18178 // -- for an elaborated-type-specifier of the form
18179 //
18180 // class-key identifier
18181 //
18182 // if the elaborated-type-specifier is used in the
18183 // decl-specifier-seq or parameter-declaration-clause of a
18184 // function defined in namespace scope, the identifier is
18185 // declared as a class-name in the namespace that contains
18186 // the declaration; otherwise, except as a friend
18187 // declaration, the identifier is declared in the smallest
18188 // non-class, non-function-prototype scope that contains the
18189 // declaration.
18190 //
18191 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
18192 // C structs and unions.
18193 //
18194 // It is an error in C++ to declare (rather than define) an enum
18195 // type, including via an elaborated type specifier. We'll
18196 // diagnose that later; for now, declare the enum in the same
18197 // scope as we would have picked for any other tag type.
18198 //
18199 // GNU C also supports this behavior as part of its incomplete
18200 // enum types extension, while GNU C++ does not.
18201 //
18202 // Find the context where we'll be declaring the tag.
18203 // FIXME: We would like to maintain the current DeclContext as the
18204 // lexical context,
18205 SearchDC = getTagInjectionContext(SearchDC);
18206
18207 // Find the scope where we'll be declaring the tag.
18209 } else {
18210 assert(TUK == TagUseKind::Friend);
18211 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(SearchDC);
18212
18213 // C++ [namespace.memdef]p3:
18214 // If a friend declaration in a non-local class first declares a
18215 // class or function, the friend class or function is a member of
18216 // the innermost enclosing namespace.
18217 SearchDC = RD->isLocalClass() ? RD->isLocalClass()
18218 : SearchDC->getEnclosingNamespaceContext();
18219 }
18220
18221 // In C++, we need to do a redeclaration lookup to properly
18222 // diagnose some problems.
18223 // FIXME: redeclaration lookup is also used (with and without C++) to find a
18224 // hidden declaration so that we don't get ambiguity errors when using a
18225 // type declared by an elaborated-type-specifier. In C that is not correct
18226 // and we should instead merge compatible types found by lookup.
18227 if (getLangOpts().CPlusPlus) {
18228 // FIXME: This can perform qualified lookups into function contexts,
18229 // which are meaningless.
18230 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18231 LookupQualifiedName(Previous, SearchDC);
18232 } else {
18233 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18234 LookupName(Previous, S);
18235 }
18236 }
18237
18238 // If we have a known previous declaration to use, then use it.
18239 if (Previous.empty() && SkipBody && SkipBody->Previous)
18240 Previous.addDecl(SkipBody->Previous);
18241
18242 if (!Previous.empty()) {
18243 NamedDecl *PrevDecl = Previous.getFoundDecl();
18244 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
18245
18246 // It's okay to have a tag decl in the same scope as a typedef
18247 // which hides a tag decl in the same scope. Finding this
18248 // with a redeclaration lookup can only actually happen in C++.
18249 //
18250 // This is also okay for elaborated-type-specifiers, which is
18251 // technically forbidden by the current standard but which is
18252 // okay according to the likely resolution of an open issue;
18253 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
18254 if (getLangOpts().CPlusPlus) {
18255 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
18256 if (TagDecl *Tag = TD->getUnderlyingType()->getAsTagDecl()) {
18257 if (Tag->getDeclName() == Name &&
18258 Tag->getDeclContext()->getRedeclContext()
18259 ->Equals(TD->getDeclContext()->getRedeclContext())) {
18260 PrevDecl = Tag;
18261 Previous.clear();
18262 Previous.addDecl(Tag);
18263 Previous.resolveKind();
18264 }
18265 }
18266 } else if (auto *RD = dyn_cast<CXXRecordDecl>(PrevDecl);
18267 TUK == TagUseKind::Reference && RD &&
18268 RD->isInjectedClassName()) {
18269 // If lookup found the injected class name, the previous declaration is
18270 // the class being injected into.
18271 PrevDecl = cast<TagDecl>(RD->getDeclContext());
18272 Previous.clear();
18273 Previous.addDecl(PrevDecl);
18274 Previous.resolveKind();
18275 IsInjectedClassName = true;
18276 }
18277 }
18278
18279 // If this is a redeclaration of a using shadow declaration, it must
18280 // declare a tag in the same context. In MSVC mode, we allow a
18281 // redefinition if either context is within the other.
18282 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
18283 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
18284 if (SS.isEmpty() && TUK != TagUseKind::Reference &&
18285 TUK != TagUseKind::Friend &&
18286 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
18287 !(OldTag && isAcceptableTagRedeclContext(
18288 *this, OldTag->getDeclContext(), SearchDC))) {
18289 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
18290 Diag(Shadow->getTargetDecl()->getLocation(),
18291 diag::note_using_decl_target);
18292 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
18293 << 0;
18294 // Recover by ignoring the old declaration.
18295 Previous.clear();
18296 goto CreateNewDecl;
18297 }
18298 }
18299
18300 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
18301 // If this is a use of a previous tag, or if the tag is already declared
18302 // in the same scope (so that the definition/declaration completes or
18303 // rementions the tag), reuse the decl.
18304 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
18305 isDeclInScope(DirectPrevDecl, SearchDC, S,
18306 SS.isNotEmpty() || isMemberSpecialization)) {
18307 // Make sure that this wasn't declared as an enum and now used as a
18308 // struct or something similar.
18309 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
18310 TUK == TagUseKind::Definition, KWLoc,
18311 Name)) {
18312 bool SafeToContinue =
18313 (PrevTagDecl->getTagKind() != TagTypeKind::Enum &&
18314 Kind != TagTypeKind::Enum);
18315 if (SafeToContinue)
18316 Diag(KWLoc, diag::err_use_with_wrong_tag)
18317 << Name
18319 PrevTagDecl->getKindName());
18320 else
18321 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
18322 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
18323
18324 if (SafeToContinue)
18325 Kind = PrevTagDecl->getTagKind();
18326 else {
18327 // Recover by making this an anonymous redefinition.
18328 Name = nullptr;
18329 Previous.clear();
18330 Invalid = true;
18331 }
18332 }
18333
18334 if (Kind == TagTypeKind::Enum &&
18335 PrevTagDecl->getTagKind() == TagTypeKind::Enum) {
18336 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
18337 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)
18338 return PrevTagDecl;
18339
18340 QualType EnumUnderlyingTy;
18341 if (TypeSourceInfo *TI =
18342 dyn_cast_if_present<TypeSourceInfo *>(EnumUnderlying))
18343 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
18344 else if (const Type *T =
18345 dyn_cast_if_present<const Type *>(EnumUnderlying))
18346 EnumUnderlyingTy = QualType(T, 0);
18347
18348 // All conflicts with previous declarations are recovered by
18349 // returning the previous declaration, unless this is a definition,
18350 // in which case we want the caller to bail out.
18351 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
18352 ScopedEnum, EnumUnderlyingTy,
18353 IsFixed, PrevEnum))
18354 return TUK == TagUseKind::Declaration ? PrevTagDecl : nullptr;
18355 }
18356
18357 // C++11 [class.mem]p1:
18358 // A member shall not be declared twice in the member-specification,
18359 // except that a nested class or member class template can be declared
18360 // and then later defined.
18361 if (TUK == TagUseKind::Declaration && PrevDecl->isCXXClassMember() &&
18362 S->isDeclScope(PrevDecl)) {
18363 Diag(NameLoc, diag::ext_member_redeclared);
18364 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
18365 }
18366
18367 if (!Invalid) {
18368 // If this is a use, just return the declaration we found, unless
18369 // we have attributes.
18370 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18371 if (!Attrs.empty()) {
18372 // FIXME: Diagnose these attributes. For now, we create a new
18373 // declaration to hold them.
18374 } else if (TUK == TagUseKind::Reference &&
18375 (PrevTagDecl->getFriendObjectKind() ==
18377 PrevDecl->getOwningModule() != getCurrentModule()) &&
18378 SS.isEmpty()) {
18379 // This declaration is a reference to an existing entity, but
18380 // has different visibility from that entity: it either makes
18381 // a friend visible or it makes a type visible in a new module.
18382 // In either case, create a new declaration. We only do this if
18383 // the declaration would have meant the same thing if no prior
18384 // declaration were found, that is, if it was found in the same
18385 // scope where we would have injected a declaration.
18386 if (!getTagInjectionContext(CurContext)->getRedeclContext()
18387 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
18388 return PrevTagDecl;
18389 // This is in the injected scope, create a new declaration in
18390 // that scope.
18392 } else {
18393 return PrevTagDecl;
18394 }
18395 }
18396
18397 // Diagnose attempts to redefine a tag.
18398 if (TUK == TagUseKind::Definition) {
18399 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
18400 // If the type is currently being defined, complain
18401 // about a nested redefinition.
18402 if (Def->isBeingDefined()) {
18403 Diag(NameLoc, diag::err_nested_redefinition) << Name;
18404 Diag(PrevTagDecl->getLocation(),
18405 diag::note_previous_definition);
18406 Name = nullptr;
18407 Previous.clear();
18408 Invalid = true;
18409 } else {
18410 // If we're defining a specialization and the previous
18411 // definition is from an implicit instantiation, don't emit an
18412 // error here; we'll catch this in the general case below.
18413 bool IsExplicitSpecializationAfterInstantiation = false;
18414 if (isMemberSpecialization) {
18415 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
18416 IsExplicitSpecializationAfterInstantiation =
18417 RD->getTemplateSpecializationKind() !=
18419 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
18420 IsExplicitSpecializationAfterInstantiation =
18421 ED->getTemplateSpecializationKind() !=
18423 }
18424
18425 // Note that clang allows ODR-like semantics for ObjC/C, i.e.,
18426 // do not keep more that one definition around (merge them).
18427 // However, ensure the decl passes the structural compatibility
18428 // check in C11 6.2.7/1 (or 6.1.2.6/1 in C89).
18429 NamedDecl *Hidden = nullptr;
18430 bool HiddenDefVisible = false;
18431 if (SkipBody &&
18432 (isRedefinitionAllowedFor(Def, &Hidden, HiddenDefVisible) ||
18433 getLangOpts().C23)) {
18434 // There is a definition of this tag, but it is not visible.
18435 // We explicitly make use of C++'s one definition rule here,
18436 // and assume that this definition is identical to the hidden
18437 // one we already have. Make the existing definition visible
18438 // and use it in place of this one.
18439 if (!getLangOpts().CPlusPlus) {
18440 // Postpone making the old definition visible until after we
18441 // complete parsing the new one and do the structural
18442 // comparison.
18443 SkipBody->CheckSameAsPrevious = true;
18444 SkipBody->New = createTagFromNewDecl();
18445 SkipBody->Previous = Def;
18446
18447 ProcessDeclAttributeList(S, SkipBody->New, Attrs);
18448 return Def;
18449 }
18450
18451 SkipBody->ShouldSkip = true;
18452 SkipBody->Previous = Def;
18453 if (!HiddenDefVisible && Hidden)
18455 // Carry on and handle it like a normal definition. We'll
18456 // skip starting the definition later.
18457
18458 } else if (!IsExplicitSpecializationAfterInstantiation) {
18459 // A redeclaration in function prototype scope in C isn't
18460 // visible elsewhere, so merely issue a warning.
18461 if (!getLangOpts().CPlusPlus &&
18463 Diag(NameLoc, diag::warn_redefinition_in_param_list)
18464 << Name;
18465 else
18466 Diag(NameLoc, diag::err_redefinition) << Name;
18468 NameLoc.isValid() ? NameLoc : KWLoc);
18469 // If this is a redefinition, recover by making this
18470 // struct be anonymous, which will make any later
18471 // references get the previous definition.
18472 Name = nullptr;
18473 Previous.clear();
18474 Invalid = true;
18475 }
18476 }
18477 }
18478
18479 // Okay, this is definition of a previously declared or referenced
18480 // tag. We're going to create a new Decl for it.
18481 }
18482
18483 // Okay, we're going to make a redeclaration. If this is some kind
18484 // of reference, make sure we build the redeclaration in the same DC
18485 // as the original, and ignore the current access specifier.
18486 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
18487 SearchDC = PrevTagDecl->getDeclContext();
18488 AS = AS_none;
18489 }
18490 }
18491 // If we get here we have (another) forward declaration or we
18492 // have a definition. Just create a new decl.
18493
18494 } else {
18495 // If we get here, this is a definition of a new tag type in a nested
18496 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
18497 // new decl/type. We set PrevDecl to NULL so that the entities
18498 // have distinct types.
18499 Previous.clear();
18500 }
18501 // If we get here, we're going to create a new Decl. If PrevDecl
18502 // is non-NULL, it's a definition of the tag declared by
18503 // PrevDecl. If it's NULL, we have a new definition.
18504
18505 // Otherwise, PrevDecl is not a tag, but was found with tag
18506 // lookup. This is only actually possible in C++, where a few
18507 // things like templates still live in the tag namespace.
18508 } else {
18509 // Use a better diagnostic if an elaborated-type-specifier
18510 // found the wrong kind of type on the first
18511 // (non-redeclaration) lookup.
18512 if ((TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) &&
18513 !Previous.isForRedeclaration()) {
18514 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
18515 Diag(NameLoc, diag::err_tag_reference_non_tag)
18516 << PrevDecl << NTK << Kind;
18517 Diag(PrevDecl->getLocation(), diag::note_declared_at);
18518 Invalid = true;
18519
18520 // Otherwise, only diagnose if the declaration is in scope.
18521 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
18522 SS.isNotEmpty() || isMemberSpecialization)) {
18523 // do nothing
18524
18525 // Diagnose implicit declarations introduced by elaborated types.
18526 } else if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18527 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
18528 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
18529 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
18530 Invalid = true;
18531
18532 // Otherwise it's a declaration. Call out a particularly common
18533 // case here.
18534 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
18535 unsigned Kind = 0;
18536 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
18537 Diag(NameLoc, diag::err_tag_definition_of_typedef)
18538 << Name << Kind << TND->getUnderlyingType();
18539 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
18540 Invalid = true;
18541
18542 // Otherwise, diagnose.
18543 } else {
18544 // The tag name clashes with something else in the target scope,
18545 // issue an error and recover by making this tag be anonymous.
18546 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
18547 notePreviousDefinition(PrevDecl, NameLoc);
18548 Name = nullptr;
18549 Invalid = true;
18550 }
18551
18552 // The existing declaration isn't relevant to us; we're in a
18553 // new scope, so clear out the previous declaration.
18554 Previous.clear();
18555 }
18556 }
18557
18558CreateNewDecl:
18559
18560 TagDecl *PrevDecl = nullptr;
18561 if (Previous.isSingleResult())
18562 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
18563
18564 // If there is an identifier, use the location of the identifier as the
18565 // location of the decl, otherwise use the location of the struct/union
18566 // keyword.
18567 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
18568
18569 // Otherwise, create a new declaration. If there is a previous
18570 // declaration of the same entity, the two will be linked via
18571 // PrevDecl.
18572 TagDecl *New;
18573
18574 if (Kind == TagTypeKind::Enum) {
18575 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18576 // enum X { A, B, C } D; D should chain to X.
18577 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
18578 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
18579 ScopedEnumUsesClassTag, IsFixed);
18580
18583 KWLoc, ScopedEnumKWLoc.isValid() ? ScopedEnumKWLoc : KWLoc));
18584
18585 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
18587
18588 // If this is an undefined enum, warn.
18589 if (TUK != TagUseKind::Definition && !Invalid) {
18590 TagDecl *Def;
18591 if (IsFixed && ED->isFixed()) {
18592 // C++0x: 7.2p2: opaque-enum-declaration.
18593 // Conflicts are diagnosed above. Do nothing.
18594 } else if (PrevDecl &&
18595 (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
18596 Diag(Loc, diag::ext_forward_ref_enum_def)
18597 << New;
18598 Diag(Def->getLocation(), diag::note_previous_definition);
18599 } else {
18600 unsigned DiagID = diag::ext_forward_ref_enum;
18601 if (getLangOpts().MSVCCompat)
18602 DiagID = diag::ext_ms_forward_ref_enum;
18603 else if (getLangOpts().CPlusPlus)
18604 DiagID = diag::err_forward_ref_enum;
18605 Diag(Loc, DiagID);
18606 }
18607 }
18608
18609 if (EnumUnderlying) {
18611 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying))
18613 else
18614 ED->setIntegerType(QualType(cast<const Type *>(EnumUnderlying), 0));
18615 QualType EnumTy = ED->getIntegerType();
18616 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
18617 ? Context.getPromotedIntegerType(EnumTy)
18618 : EnumTy);
18619 assert(ED->isComplete() && "enum with type should be complete");
18620 }
18621 } else {
18622 // struct/union/class
18623
18624 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18625 // struct X { int A; } D; D should chain to X.
18626 if (getLangOpts().CPlusPlus) {
18627 // FIXME: Look for a way to use RecordDecl for simple structs.
18628 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
18629 cast_or_null<CXXRecordDecl>(PrevDecl));
18630
18631 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
18633 } else
18634 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
18635 cast_or_null<RecordDecl>(PrevDecl));
18636 }
18637
18638 // Only C23 and later allow defining new types in 'offsetof()'.
18639 if (OOK != OffsetOfKind::Outside && TUK == TagUseKind::Definition &&
18641 Diag(New->getLocation(), diag::ext_type_defined_in_offsetof)
18642 << (OOK == OffsetOfKind::Macro) << New->getSourceRange();
18643
18644 // C++11 [dcl.type]p3:
18645 // A type-specifier-seq shall not define a class or enumeration [...].
18646 if (!Invalid && getLangOpts().CPlusPlus &&
18647 (IsTypeSpecifier || IsTemplateParamOrArg) &&
18648 TUK == TagUseKind::Definition) {
18649 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
18650 << Context.getCanonicalTagType(New);
18651 Invalid = true;
18652 }
18653
18655 DC->getDeclKind() == Decl::Enum) {
18656 Diag(New->getLocation(), diag::err_type_defined_in_enum)
18657 << Context.getCanonicalTagType(New);
18658 Invalid = true;
18659 }
18660
18661 // Maybe add qualifier info.
18662 if (SS.isNotEmpty()) {
18663 if (SS.isSet()) {
18664 // If this is either a declaration or a definition, check the
18665 // nested-name-specifier against the current context.
18666 if ((TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration) &&
18667 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
18668 /*TemplateId=*/nullptr,
18669 isMemberSpecialization))
18670 Invalid = true;
18671
18672 New->setQualifierInfo(SS.getWithLocInContext(Context));
18673 if (TemplateParameterLists.size() > 0) {
18674 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
18675 }
18676 }
18677 else
18678 Invalid = true;
18679 }
18680
18681 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
18682 // Add alignment attributes if necessary; these attributes are checked when
18683 // the ASTContext lays out the structure.
18684 //
18685 // It is important for implementing the correct semantics that this
18686 // happen here (in ActOnTag). The #pragma pack stack is
18687 // maintained as a result of parser callbacks which can occur at
18688 // many points during the parsing of a struct declaration (because
18689 // the #pragma tokens are effectively skipped over during the
18690 // parsing of the struct).
18691 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
18692 if (LangOpts.HLSL)
18693 RD->addAttr(PackedAttr::CreateImplicit(Context));
18696 }
18697 }
18698
18699 if (ModulePrivateLoc.isValid()) {
18700 if (isMemberSpecialization)
18701 Diag(New->getLocation(), diag::err_module_private_specialization)
18702 << 2
18703 << FixItHint::CreateRemoval(ModulePrivateLoc);
18704 // __module_private__ does not apply to local classes. However, we only
18705 // diagnose this as an error when the declaration specifiers are
18706 // freestanding. Here, we just ignore the __module_private__.
18707 else if (!SearchDC->isFunctionOrMethod())
18708 New->setModulePrivate();
18709 }
18710
18711 // If this is a specialization of a member class (of a class template),
18712 // check the specialization.
18713 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
18714 Invalid = true;
18715
18716 // If we're declaring or defining a tag in function prototype scope in C,
18717 // note that this type can only be used within the function and add it to
18718 // the list of decls to inject into the function definition scope. However,
18719 // in C23 and later, while the type is only visible within the function, the
18720 // function can be called with a compatible type defined in the same TU, so
18721 // we silence the diagnostic in C23 and up. This matches the behavior of GCC.
18722 if ((Name || Kind == TagTypeKind::Enum) &&
18723 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
18724 if (getLangOpts().CPlusPlus) {
18725 // C++ [dcl.fct]p6:
18726 // Types shall not be defined in return or parameter types.
18727 if (TUK == TagUseKind::Definition && !IsTypeSpecifier) {
18728 Diag(Loc, diag::err_type_defined_in_param_type)
18729 << Name;
18730 Invalid = true;
18731 }
18732 if (TUK == TagUseKind::Declaration)
18733 Invalid = true;
18734 } else if (!PrevDecl) {
18735 // In C23 mode, if the declaration is complete, we do not want to
18736 // diagnose.
18737 if (!getLangOpts().C23 || TUK != TagUseKind::Definition)
18738 Diag(Loc, diag::warn_decl_in_param_list)
18739 << Context.getCanonicalTagType(New);
18740 }
18741 }
18742
18743 if (Invalid)
18744 New->setInvalidDecl();
18745
18746 // Set the lexical context. If the tag has a C++ scope specifier, the
18747 // lexical context will be different from the semantic context.
18748 New->setLexicalDeclContext(CurContext);
18749
18750 // Mark this as a friend decl if applicable.
18751 // In Microsoft mode, a friend declaration also acts as a forward
18752 // declaration so we always pass true to setObjectOfFriendDecl to make
18753 // the tag name visible.
18754 if (TUK == TagUseKind::Friend)
18755 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
18756
18757 // Set the access specifier.
18758 if (!Invalid && SearchDC->isRecord())
18759 SetMemberAccessSpecifier(New, PrevDecl, AS);
18760
18761 if (PrevDecl)
18763
18764 if (TUK == TagUseKind::Definition) {
18765 if (!SkipBody || !SkipBody->ShouldSkip) {
18766 New->startDefinition();
18767 } else {
18768 New->setCompleteDefinition();
18769 New->demoteThisDefinitionToDeclaration();
18770 }
18771 }
18772
18773 ProcessDeclAttributeList(S, New, Attrs);
18775
18776 // If this has an identifier, add it to the scope stack.
18777 if (TUK == TagUseKind::Friend || IsInjectedClassName) {
18778 // We might be replacing an existing declaration in the lookup tables;
18779 // if so, borrow its access specifier.
18780 if (PrevDecl)
18781 New->setAccess(PrevDecl->getAccess());
18782
18783 DeclContext *DC = New->getDeclContext()->getRedeclContext();
18785 if (Name) // can be null along some error paths
18786 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18787 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
18788 } else if (Name) {
18789 S = getNonFieldDeclScope(S);
18790 PushOnScopeChains(New, S, true);
18791 } else {
18792 CurContext->addDecl(New);
18793 }
18794
18795 // If this is the C FILE type, notify the AST context.
18796 if (IdentifierInfo *II = New->getIdentifier())
18797 if (!New->isInvalidDecl() &&
18798 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
18799 II->isStr("FILE"))
18800 Context.setFILEDecl(New);
18801
18802 if (PrevDecl)
18803 mergeDeclAttributes(New, PrevDecl);
18804
18805 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) {
18808 }
18809
18810 // If there's a #pragma GCC visibility in scope, set the visibility of this
18811 // record.
18813
18814 // If this is not a definition, process API notes for it now.
18815 if (TUK != TagUseKind::Definition)
18817
18818 if (isMemberSpecialization && !New->isInvalidDecl())
18820
18821 OwnedDecl = true;
18822 // In C++, don't return an invalid declaration. We can't recover well from
18823 // the cases where we make the type anonymous.
18824 if (Invalid && getLangOpts().CPlusPlus) {
18825 if (New->isBeingDefined())
18826 if (auto RD = dyn_cast<RecordDecl>(New))
18827 RD->completeDefinition();
18828 return true;
18829 } else if (SkipBody && SkipBody->ShouldSkip) {
18830 return SkipBody->Previous;
18831 } else {
18832 return New;
18833 }
18834}
18835
18838 TagDecl *Tag = cast<TagDecl>(TagD);
18839
18840 // Enter the tag context.
18841 PushDeclContext(S, Tag);
18842
18844
18845 // If there's a #pragma GCC visibility in scope, set the visibility of this
18846 // record.
18848}
18849
18851 SkipBodyInfo &SkipBody) {
18852 if (!hasStructuralCompatLayout(Prev, SkipBody.New))
18853 return false;
18854
18855 // Make the previous decl visible.
18857 CleanupMergedEnum(S, SkipBody.New);
18858 return true;
18859}
18860
18862 SourceLocation FinalLoc,
18863 bool IsFinalSpelledSealed,
18864 bool IsAbstract,
18865 SourceLocation LBraceLoc) {
18868
18869 FieldCollector->StartClass();
18870
18871 if (!Record->getIdentifier())
18872 return;
18873
18874 if (IsAbstract)
18875 Record->markAbstract();
18876
18877 if (FinalLoc.isValid()) {
18878 Record->addAttr(FinalAttr::Create(Context, FinalLoc,
18879 IsFinalSpelledSealed
18880 ? FinalAttr::Keyword_sealed
18881 : FinalAttr::Keyword_final));
18882 }
18883
18884 // C++ [class]p2:
18885 // [...] The class-name is also inserted into the scope of the
18886 // class itself; this is known as the injected-class-name. For
18887 // purposes of access checking, the injected-class-name is treated
18888 // as if it were a public member name.
18889 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
18890 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
18891 Record->getLocation(), Record->getIdentifier());
18892 InjectedClassName->setImplicit();
18893 InjectedClassName->setAccess(AS_public);
18894 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
18895 InjectedClassName->setDescribedClassTemplate(Template);
18896
18897 PushOnScopeChains(InjectedClassName, S);
18898 assert(InjectedClassName->isInjectedClassName() &&
18899 "Broken injected-class-name");
18900}
18901
18903 SourceRange BraceRange) {
18905 TagDecl *Tag = cast<TagDecl>(TagD);
18906 Tag->setBraceRange(BraceRange);
18907
18908 // Make sure we "complete" the definition even it is invalid.
18909 if (Tag->isBeingDefined()) {
18910 assert(Tag->isInvalidDecl() && "We should already have completed it");
18911 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
18912 RD->completeDefinition();
18913 }
18914
18915 if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
18916 FieldCollector->FinishClass();
18917 if (RD->hasAttr<SYCLSpecialClassAttr>()) {
18918 auto *Def = RD->getDefinition();
18919 assert(Def && "The record is expected to have a completed definition");
18920 unsigned NumInitMethods = 0;
18921 for (auto *Method : Def->methods()) {
18922 if (!Method->getIdentifier())
18923 continue;
18924 if (Method->getName() == "__init")
18925 NumInitMethods++;
18926 }
18927 if (NumInitMethods > 1 || !Def->hasInitMethod())
18928 Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
18929 }
18930
18931 // If we're defining a dynamic class in a module interface unit, we always
18932 // need to produce the vtable for it, even if the vtable is not used in the
18933 // current TU.
18934 //
18935 // The case where the current class is not dynamic is handled in
18936 // MarkVTableUsed.
18937 if (getCurrentModule() && getCurrentModule()->isInterfaceOrPartition())
18938 MarkVTableUsed(RD->getLocation(), RD, /*DefinitionRequired=*/true);
18939 }
18940
18941 // Exit this scope of this tag's definition.
18943
18944 if (getCurLexicalContext()->isObjCContainer() &&
18945 Tag->getDeclContext()->isFileContext())
18946 Tag->setTopLevelDeclInObjCContainer();
18947
18948 // Notify the consumer that we've defined a tag.
18949 if (!Tag->isInvalidDecl())
18950 Consumer.HandleTagDeclDefinition(Tag);
18951
18952 // Clangs implementation of #pragma align(packed) differs in bitfield layout
18953 // from XLs and instead matches the XL #pragma pack(1) behavior.
18954 if (Context.getTargetInfo().getTriple().isOSAIX() &&
18955 AlignPackStack.hasValue()) {
18956 AlignPackInfo APInfo = AlignPackStack.CurrentValue;
18957 // Only diagnose #pragma align(packed).
18958 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
18959 return;
18960 const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
18961 if (!RD)
18962 return;
18963 // Only warn if there is at least 1 bitfield member.
18964 if (llvm::any_of(RD->fields(),
18965 [](const FieldDecl *FD) { return FD->isBitField(); }))
18966 Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
18967 }
18968}
18969
18972 TagDecl *Tag = cast<TagDecl>(TagD);
18973 Tag->setInvalidDecl();
18974
18975 // Make sure we "complete" the definition even it is invalid.
18976 if (Tag->isBeingDefined()) {
18977 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
18978 RD->completeDefinition();
18979 }
18980
18981 // We're undoing ActOnTagStartDefinition here, not
18982 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
18983 // the FieldCollector.
18984
18986}
18987
18988// Note that FieldName may be null for anonymous bitfields.
18990 const IdentifierInfo *FieldName,
18991 QualType FieldTy, bool IsMsStruct,
18992 Expr *BitWidth) {
18993 assert(BitWidth);
18994 if (BitWidth->containsErrors())
18995 return ExprError();
18996
18997 // C99 6.7.2.1p4 - verify the field type.
18998 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
18999 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
19000 // Handle incomplete and sizeless types with a specific error.
19001 if (RequireCompleteSizedType(FieldLoc, FieldTy,
19002 diag::err_field_incomplete_or_sizeless))
19003 return ExprError();
19004 if (FieldName)
19005 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
19006 << FieldName << FieldTy << BitWidth->getSourceRange();
19007 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
19008 << FieldTy << BitWidth->getSourceRange();
19010 return ExprError();
19011
19012 // If the bit-width is type- or value-dependent, don't try to check
19013 // it now.
19014 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
19015 return BitWidth;
19016
19017 llvm::APSInt Value;
19018 ExprResult ICE =
19020 if (ICE.isInvalid())
19021 return ICE;
19022 BitWidth = ICE.get();
19023
19024 // Zero-width bitfield is ok for anonymous field.
19025 if (Value == 0 && FieldName)
19026 return Diag(FieldLoc, diag::err_bitfield_has_zero_width)
19027 << FieldName << BitWidth->getSourceRange();
19028
19029 if (Value.isSigned() && Value.isNegative()) {
19030 if (FieldName)
19031 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
19032 << FieldName << toString(Value, 10);
19033 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
19034 << toString(Value, 10);
19035 }
19036
19037 // The size of the bit-field must not exceed our maximum permitted object
19038 // size.
19039 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
19040 return Diag(FieldLoc, diag::err_bitfield_too_wide)
19041 << !FieldName << FieldName << toString(Value, 10);
19042 }
19043
19044 if (!FieldTy->isDependentType()) {
19045 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
19046 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
19047 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
19048
19049 // Over-wide bitfields are an error in C or when using the MSVC bitfield
19050 // ABI.
19051 bool CStdConstraintViolation =
19052 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
19053 bool MSBitfieldViolation = Value.ugt(TypeStorageSize) && IsMsStruct;
19054 if (CStdConstraintViolation || MSBitfieldViolation) {
19055 unsigned DiagWidth =
19056 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
19057 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
19058 << (bool)FieldName << FieldName << toString(Value, 10)
19059 << !CStdConstraintViolation << DiagWidth;
19060 }
19061
19062 // Warn on types where the user might conceivably expect to get all
19063 // specified bits as value bits: that's all integral types other than
19064 // 'bool'.
19065 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
19066 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
19067 << FieldName << Value << (unsigned)TypeWidth;
19068 }
19069 }
19070
19071 if (isa<ConstantExpr>(BitWidth))
19072 return BitWidth;
19073 return ConstantExpr::Create(getASTContext(), BitWidth, APValue{Value});
19074}
19075
19077 Declarator &D, Expr *BitfieldWidth) {
19078 FieldDecl *Res = HandleField(S, cast_if_present<RecordDecl>(TagD), DeclStart,
19079 D, BitfieldWidth,
19080 /*InitStyle=*/ICIS_NoInit, AS_public);
19081 return Res;
19082}
19083
19085 SourceLocation DeclStart,
19086 Declarator &D, Expr *BitWidth,
19087 InClassInitStyle InitStyle,
19088 AccessSpecifier AS) {
19089 if (D.isDecompositionDeclarator()) {
19091 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
19092 << Decomp.getSourceRange();
19093 return nullptr;
19094 }
19095
19096 const IdentifierInfo *II = D.getIdentifier();
19097 SourceLocation Loc = DeclStart;
19098 if (II) Loc = D.getIdentifierLoc();
19099
19101 QualType T = TInfo->getType();
19102 if (getLangOpts().CPlusPlus) {
19104
19107 D.setInvalidType();
19108 T = Context.IntTy;
19109 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
19110 }
19111 }
19112
19114
19116 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
19117 << getLangOpts().CPlusPlus17;
19120 diag::err_invalid_thread)
19122
19123 // Check to see if this name was declared as a member previously
19124 NamedDecl *PrevDecl = nullptr;
19125 LookupResult Previous(*this, II, Loc, LookupMemberName,
19127 LookupName(Previous, S);
19128 switch (Previous.getResultKind()) {
19131 PrevDecl = Previous.getAsSingle<NamedDecl>();
19132 break;
19133
19135 PrevDecl = Previous.getRepresentativeDecl();
19136 break;
19137
19141 break;
19142 }
19143 Previous.suppressDiagnostics();
19144
19145 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19146 // Maybe we will complain about the shadowed template parameter.
19148 // Just pretend that we didn't see the previous declaration.
19149 PrevDecl = nullptr;
19150 }
19151
19152 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
19153 PrevDecl = nullptr;
19154
19155 bool Mutable
19156 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
19157 SourceLocation TSSL = D.getBeginLoc();
19158 FieldDecl *NewFD
19159 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
19160 TSSL, AS, PrevDecl, &D);
19161
19162 if (NewFD->isInvalidDecl())
19163 Record->setInvalidDecl();
19164
19166 NewFD->setModulePrivate();
19167
19168 if (NewFD->isInvalidDecl() && PrevDecl) {
19169 // Don't introduce NewFD into scope; there's already something
19170 // with the same name in the same scope.
19171 } else if (II) {
19172 PushOnScopeChains(NewFD, S);
19173 } else
19174 Record->addDecl(NewFD);
19175
19176 return NewFD;
19177}
19178
19180 TypeSourceInfo *TInfo,
19182 bool Mutable, Expr *BitWidth,
19183 InClassInitStyle InitStyle,
19184 SourceLocation TSSL,
19185 AccessSpecifier AS, NamedDecl *PrevDecl,
19186 Declarator *D) {
19187 const IdentifierInfo *II = Name.getAsIdentifierInfo();
19188 bool InvalidDecl = false;
19189 if (D) InvalidDecl = D->isInvalidType();
19190
19191 // If we receive a broken type, recover by assuming 'int' and
19192 // marking this declaration as invalid.
19193 if (T.isNull() || T->containsErrors()) {
19194 InvalidDecl = true;
19195 T = Context.IntTy;
19196 }
19197
19198 QualType EltTy = Context.getBaseElementType(T);
19199 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
19200 bool isIncomplete =
19201 LangOpts.HLSL // HLSL allows sizeless builtin types
19202 ? RequireCompleteType(Loc, EltTy, diag::err_incomplete_type)
19203 : RequireCompleteSizedType(Loc, EltTy,
19204 diag::err_field_incomplete_or_sizeless);
19205 if (isIncomplete) {
19206 // Fields of incomplete type force their record to be invalid.
19207 Record->setInvalidDecl();
19208 InvalidDecl = true;
19209 } else {
19210 NamedDecl *Def;
19211 EltTy->isIncompleteType(&Def);
19212 if (Def && Def->isInvalidDecl()) {
19213 Record->setInvalidDecl();
19214 InvalidDecl = true;
19215 }
19216 }
19217 }
19218
19219 // TR 18037 does not allow fields to be declared with address space
19220 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
19221 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
19222 Diag(Loc, diag::err_field_with_address_space);
19223 Record->setInvalidDecl();
19224 InvalidDecl = true;
19225 }
19226
19227 if (LangOpts.OpenCL) {
19228 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
19229 // used as structure or union field: image, sampler, event or block types.
19230 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
19231 T->isBlockPointerType()) {
19232 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
19233 Record->setInvalidDecl();
19234 InvalidDecl = true;
19235 }
19236 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
19237 // is enabled.
19238 if (BitWidth && !getOpenCLOptions().isAvailableOption(
19239 "__cl_clang_bitfields", LangOpts)) {
19240 Diag(Loc, diag::err_opencl_bitfields);
19241 InvalidDecl = true;
19242 }
19243 }
19244
19245 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
19246 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
19247 T.hasQualifiers()) {
19248 InvalidDecl = true;
19249 Diag(Loc, diag::err_anon_bitfield_qualifiers);
19250 }
19251
19252 // C99 6.7.2.1p8: A member of a structure or union may have any type other
19253 // than a variably modified type.
19254 if (!InvalidDecl && T->isVariablyModifiedType()) {
19256 TInfo, T, Loc, diag::err_typecheck_field_variable_size))
19257 InvalidDecl = true;
19258 }
19259
19260 // Fields can not have abstract class types
19261 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
19262 diag::err_abstract_type_in_decl,
19264 InvalidDecl = true;
19265
19266 if (InvalidDecl)
19267 BitWidth = nullptr;
19268 // If this is declared as a bit-field, check the bit-field.
19269 if (BitWidth) {
19270 BitWidth =
19271 VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get();
19272 if (!BitWidth) {
19273 InvalidDecl = true;
19274 BitWidth = nullptr;
19275 }
19276 }
19277
19278 // Check that 'mutable' is consistent with the type of the declaration.
19279 if (!InvalidDecl && Mutable) {
19280 unsigned DiagID = 0;
19281 if (T->isReferenceType())
19282 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
19283 : diag::err_mutable_reference;
19284 else if (T.isConstQualified())
19285 DiagID = diag::err_mutable_const;
19286
19287 if (DiagID) {
19288 SourceLocation ErrLoc = Loc;
19289 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
19290 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
19291 Diag(ErrLoc, DiagID);
19292 if (DiagID != diag::ext_mutable_reference) {
19293 Mutable = false;
19294 InvalidDecl = true;
19295 }
19296 }
19297 }
19298
19299 // C++11 [class.union]p8 (DR1460):
19300 // At most one variant member of a union may have a
19301 // brace-or-equal-initializer.
19302 if (InitStyle != ICIS_NoInit)
19304
19305 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
19306 BitWidth, Mutable, InitStyle);
19307 if (InvalidDecl)
19308 NewFD->setInvalidDecl();
19309
19310 if (!InvalidDecl)
19312
19313 if (PrevDecl && !isa<TagDecl>(PrevDecl) &&
19314 !PrevDecl->isPlaceholderVar(getLangOpts())) {
19315 Diag(Loc, diag::err_duplicate_member) << II;
19316 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
19317 NewFD->setInvalidDecl();
19318 }
19319
19320 if (!InvalidDecl && getLangOpts().CPlusPlus) {
19321 if (Record->isUnion()) {
19322 if (const auto *RD = EltTy->getAsCXXRecordDecl();
19323 RD && (RD->isBeingDefined() || RD->isCompleteDefinition())) {
19324
19325 // C++ [class.union]p1: An object of a class with a non-trivial
19326 // constructor, a non-trivial copy constructor, a non-trivial
19327 // destructor, or a non-trivial copy assignment operator
19328 // cannot be a member of a union, nor can an array of such
19329 // objects.
19330 if (CheckNontrivialField(NewFD))
19331 NewFD->setInvalidDecl();
19332 }
19333
19334 // C++ [class.union]p1: If a union contains a member of reference type,
19335 // the program is ill-formed, except when compiling with MSVC extensions
19336 // enabled.
19337 if (EltTy->isReferenceType()) {
19338 const bool HaveMSExt =
19339 getLangOpts().MicrosoftExt &&
19341
19342 Diag(NewFD->getLocation(),
19343 HaveMSExt ? diag::ext_union_member_of_reference_type
19344 : diag::err_union_member_of_reference_type)
19345 << NewFD->getDeclName() << EltTy;
19346 if (!HaveMSExt)
19347 NewFD->setInvalidDecl();
19348 }
19349 }
19350 }
19351
19352 // FIXME: We need to pass in the attributes given an AST
19353 // representation, not a parser representation.
19354 if (D) {
19355 // FIXME: The current scope is almost... but not entirely... correct here.
19356 ProcessDeclAttributes(getCurScope(), NewFD, *D);
19357
19358 if (NewFD->hasAttrs())
19360 }
19361
19362 // In auto-retain/release, infer strong retension for fields of
19363 // retainable type.
19364 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewFD))
19365 NewFD->setInvalidDecl();
19366
19367 if (T.isObjCGCWeak())
19368 Diag(Loc, diag::warn_attribute_weak_on_field);
19369
19370 // PPC MMA non-pointer types are not allowed as field types.
19371 if (Context.getTargetInfo().getTriple().isPPC64() &&
19372 PPC().CheckPPCMMAType(T, NewFD->getLocation()))
19373 NewFD->setInvalidDecl();
19374
19375 NewFD->setAccess(AS);
19376 return NewFD;
19377}
19378
19380 assert(FD);
19381 assert(getLangOpts().CPlusPlus && "valid check only for C++");
19382
19383 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
19384 return false;
19385
19386 QualType EltTy = Context.getBaseElementType(FD->getType());
19387 if (const auto *RDecl = EltTy->getAsCXXRecordDecl();
19388 RDecl && (RDecl->isBeingDefined() || RDecl->isCompleteDefinition())) {
19389 // We check for copy constructors before constructors
19390 // because otherwise we'll never get complaints about
19391 // copy constructors.
19392
19394 // We're required to check for any non-trivial constructors. Since the
19395 // implicit default constructor is suppressed if there are any
19396 // user-declared constructors, we just need to check that there is a
19397 // trivial default constructor and a trivial copy constructor. (We don't
19398 // worry about move constructors here, since this is a C++98 check.)
19399 if (RDecl->hasNonTrivialCopyConstructor())
19401 else if (!RDecl->hasTrivialDefaultConstructor())
19403 else if (RDecl->hasNonTrivialCopyAssignment())
19405 else if (RDecl->hasNonTrivialDestructor())
19407
19408 if (member != CXXSpecialMemberKind::Invalid) {
19409 if (!getLangOpts().CPlusPlus11 && getLangOpts().ObjCAutoRefCount &&
19410 RDecl->hasObjectMember()) {
19411 // Objective-C++ ARC: it is an error to have a non-trivial field of
19412 // a union. However, system headers in Objective-C programs
19413 // occasionally have Objective-C lifetime objects within unions,
19414 // and rather than cause the program to fail, we make those
19415 // members unavailable.
19416 SourceLocation Loc = FD->getLocation();
19417 if (getSourceManager().isInSystemHeader(Loc)) {
19418 if (!FD->hasAttr<UnavailableAttr>())
19419 FD->addAttr(UnavailableAttr::CreateImplicit(
19420 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
19421 return false;
19422 }
19423 }
19424
19425 Diag(FD->getLocation(),
19427 ? diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member
19428 : diag::err_illegal_union_or_anon_struct_member)
19429 << FD->getParent()->isUnion() << FD->getDeclName() << member;
19430 DiagnoseNontrivial(RDecl, member);
19431 return !getLangOpts().CPlusPlus11;
19432 }
19433 }
19434
19435 return false;
19436}
19437
19439 SmallVectorImpl<Decl *> &AllIvarDecls) {
19440 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
19441 return;
19442
19443 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
19444 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
19445
19446 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField())
19447 return;
19448 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
19449 if (!ID) {
19450 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
19451 if (!CD->IsClassExtension())
19452 return;
19453 }
19454 // No need to add this to end of @implementation.
19455 else
19456 return;
19457 }
19458 // All conditions are met. Add a new bitfield to the tail end of ivars.
19459 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
19460 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
19461 Expr *BitWidth =
19462 ConstantExpr::Create(Context, BW, APValue(llvm::APSInt(Zero)));
19463
19464 Ivar = ObjCIvarDecl::Create(
19465 Context, cast<ObjCContainerDecl>(CurContext), DeclLoc, DeclLoc, nullptr,
19466 Context.CharTy, Context.getTrivialTypeSourceInfo(Context.CharTy, DeclLoc),
19467 ObjCIvarDecl::Private, BitWidth, true);
19468 AllIvarDecls.push_back(Ivar);
19469}
19470
19471/// [class.dtor]p4:
19472/// At the end of the definition of a class, overload resolution is
19473/// performed among the prospective destructors declared in that class with
19474/// an empty argument list to select the destructor for the class, also
19475/// known as the selected destructor.
19476///
19477/// We do the overload resolution here, then mark the selected constructor in the AST.
19478/// Later CXXRecordDecl::getDestructor() will return the selected constructor.
19480 if (!Record->hasUserDeclaredDestructor()) {
19481 return;
19482 }
19483
19484 SourceLocation Loc = Record->getLocation();
19486
19487 for (auto *Decl : Record->decls()) {
19488 if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {
19489 if (DD->isInvalidDecl())
19490 continue;
19491 S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},
19492 OCS);
19493 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
19494 }
19495 }
19496
19497 if (OCS.empty()) {
19498 return;
19499 }
19501 unsigned Msg = 0;
19502 OverloadCandidateDisplayKind DisplayKind;
19503
19504 switch (OCS.BestViableFunction(S, Loc, Best)) {
19505 case OR_Success:
19506 case OR_Deleted:
19507 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function));
19508 break;
19509
19510 case OR_Ambiguous:
19511 Msg = diag::err_ambiguous_destructor;
19512 DisplayKind = OCD_AmbiguousCandidates;
19513 break;
19514
19516 Msg = diag::err_no_viable_destructor;
19517 DisplayKind = OCD_AllCandidates;
19518 break;
19519 }
19520
19521 if (Msg) {
19522 // OpenCL have got their own thing going with destructors. It's slightly broken,
19523 // but we allow it.
19524 if (!S.LangOpts.OpenCL) {
19525 PartialDiagnostic Diag = S.PDiag(Msg) << Record;
19526 OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {});
19527 Record->setInvalidDecl();
19528 }
19529 // It's a bit hacky: At this point we've raised an error but we want the
19530 // rest of the compiler to continue somehow working. However almost
19531 // everything we'll try to do with the class will depend on there being a
19532 // destructor. So let's pretend the first one is selected and hope for the
19533 // best.
19534 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function));
19535 }
19536}
19537
19538/// [class.mem.special]p5
19539/// Two special member functions are of the same kind if:
19540/// - they are both default constructors,
19541/// - they are both copy or move constructors with the same first parameter
19542/// type, or
19543/// - they are both copy or move assignment operators with the same first
19544/// parameter type and the same cv-qualifiers and ref-qualifier, if any.
19546 CXXMethodDecl *M1,
19547 CXXMethodDecl *M2,
19549 // We don't want to compare templates to non-templates: See
19550 // https://github.com/llvm/llvm-project/issues/59206
19552 return bool(M1->getDescribedFunctionTemplate()) ==
19554 // FIXME: better resolve CWG
19555 // https://cplusplus.github.io/CWG/issues/2787.html
19556 if (!Context.hasSameType(M1->getNonObjectParameter(0)->getType(),
19557 M2->getNonObjectParameter(0)->getType()))
19558 return false;
19559 if (!Context.hasSameType(M1->getFunctionObjectParameterReferenceType(),
19561 return false;
19562
19563 return true;
19564}
19565
19566/// [class.mem.special]p6:
19567/// An eligible special member function is a special member function for which:
19568/// - the function is not deleted,
19569/// - the associated constraints, if any, are satisfied, and
19570/// - no special member function of the same kind whose associated constraints
19571/// [CWG2595], if any, are satisfied is more constrained.
19575 SmallVector<bool, 4> SatisfactionStatus;
19576
19577 for (CXXMethodDecl *Method : Methods) {
19578 if (!Method->getTrailingRequiresClause())
19579 SatisfactionStatus.push_back(true);
19580 else {
19581 ConstraintSatisfaction Satisfaction;
19582 if (S.CheckFunctionConstraints(Method, Satisfaction))
19583 SatisfactionStatus.push_back(false);
19584 else
19585 SatisfactionStatus.push_back(Satisfaction.IsSatisfied);
19586 }
19587 }
19588
19589 for (size_t i = 0; i < Methods.size(); i++) {
19590 if (!SatisfactionStatus[i])
19591 continue;
19592 CXXMethodDecl *Method = Methods[i];
19593 CXXMethodDecl *OrigMethod = Method;
19594 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
19595 OrigMethod = cast<CXXMethodDecl>(MF);
19596
19598 bool AnotherMethodIsMoreConstrained = false;
19599 for (size_t j = 0; j < Methods.size(); j++) {
19600 if (i == j || !SatisfactionStatus[j])
19601 continue;
19602 CXXMethodDecl *OtherMethod = Methods[j];
19603 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
19604 OtherMethod = cast<CXXMethodDecl>(MF);
19605
19606 if (!AreSpecialMemberFunctionsSameKind(S.Context, OrigMethod, OtherMethod,
19607 CSM))
19608 continue;
19609
19611 if (!Other)
19612 continue;
19613 if (!Orig) {
19614 AnotherMethodIsMoreConstrained = true;
19615 break;
19616 }
19617 if (S.IsAtLeastAsConstrained(OtherMethod, {Other}, OrigMethod, {Orig},
19618 AnotherMethodIsMoreConstrained)) {
19619 // There was an error with the constraints comparison. Exit the loop
19620 // and don't consider this function eligible.
19621 AnotherMethodIsMoreConstrained = true;
19622 }
19623 if (AnotherMethodIsMoreConstrained)
19624 break;
19625 }
19626 // FIXME: Do not consider deleted methods as eligible after implementing
19627 // DR1734 and DR1496.
19628 if (!AnotherMethodIsMoreConstrained) {
19629 Method->setIneligibleOrNotSelected(false);
19630 Record->addedEligibleSpecialMemberFunction(Method,
19631 1 << llvm::to_underlying(CSM));
19632 }
19633 }
19634}
19635
19638 SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
19639 SmallVector<CXXMethodDecl *, 4> CopyConstructors;
19640 SmallVector<CXXMethodDecl *, 4> MoveConstructors;
19641 SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
19642 SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
19643
19644 for (auto *Decl : Record->decls()) {
19645 auto *MD = dyn_cast<CXXMethodDecl>(Decl);
19646 if (!MD) {
19647 auto *FTD = dyn_cast<FunctionTemplateDecl>(Decl);
19648 if (FTD)
19649 MD = dyn_cast<CXXMethodDecl>(FTD->getTemplatedDecl());
19650 }
19651 if (!MD)
19652 continue;
19653 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
19654 if (CD->isInvalidDecl())
19655 continue;
19656 if (CD->isDefaultConstructor())
19657 DefaultConstructors.push_back(MD);
19658 else if (CD->isCopyConstructor())
19659 CopyConstructors.push_back(MD);
19660 else if (CD->isMoveConstructor())
19661 MoveConstructors.push_back(MD);
19662 } else if (MD->isCopyAssignmentOperator()) {
19663 CopyAssignmentOperators.push_back(MD);
19664 } else if (MD->isMoveAssignmentOperator()) {
19665 MoveAssignmentOperators.push_back(MD);
19666 }
19667 }
19668
19669 SetEligibleMethods(S, Record, DefaultConstructors,
19671 SetEligibleMethods(S, Record, CopyConstructors,
19673 SetEligibleMethods(S, Record, MoveConstructors,
19675 SetEligibleMethods(S, Record, CopyAssignmentOperators,
19677 SetEligibleMethods(S, Record, MoveAssignmentOperators,
19679}
19680
19681bool Sema::EntirelyFunctionPointers(const RecordDecl *Record) {
19682 // Check to see if a FieldDecl is a pointer to a function.
19683 auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
19684 const FieldDecl *FD = dyn_cast<FieldDecl>(D);
19685 if (!FD) {
19686 // Check whether this is a forward declaration that was inserted by
19687 // Clang. This happens when a non-forward declared / defined type is
19688 // used, e.g.:
19689 //
19690 // struct foo {
19691 // struct bar *(*f)();
19692 // struct bar *(*g)();
19693 // };
19694 //
19695 // "struct bar" shows up in the decl AST as a "RecordDecl" with an
19696 // incomplete definition.
19697 if (const auto *TD = dyn_cast<TagDecl>(D))
19698 return !TD->isCompleteDefinition();
19699 return false;
19700 }
19701 QualType FieldType = FD->getType().getDesugaredType(Context);
19702 if (isa<PointerType>(FieldType)) {
19703 QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();
19704 return PointeeType.getDesugaredType(Context)->isFunctionType();
19705 }
19706 // If a member is a struct entirely of function pointers, that counts too.
19707 if (const auto *Record = FieldType->getAsRecordDecl();
19708 Record && Record->isStruct() && EntirelyFunctionPointers(Record))
19709 return true;
19710 return false;
19711 };
19712
19713 return llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl);
19714}
19715
19716void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
19717 ArrayRef<Decl *> Fields, SourceLocation LBrac,
19718 SourceLocation RBrac,
19719 const ParsedAttributesView &Attrs) {
19720 assert(EnclosingDecl && "missing record or interface decl");
19721
19722 // If this is an Objective-C @implementation or category and we have
19723 // new fields here we should reset the layout of the interface since
19724 // it will now change.
19725 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
19726 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
19727 switch (DC->getKind()) {
19728 default: break;
19729 case Decl::ObjCCategory:
19730 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
19731 break;
19732 case Decl::ObjCImplementation:
19733 Context.
19734 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
19735 break;
19736 }
19737 }
19738
19739 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
19740 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
19741
19742 // Start counting up the number of named members; make sure to include
19743 // members of anonymous structs and unions in the total.
19744 unsigned NumNamedMembers = 0;
19745 if (Record) {
19746 for (const auto *I : Record->decls()) {
19747 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
19748 if (IFD->getDeclName())
19749 ++NumNamedMembers;
19750 }
19751 }
19752
19753 // Verify that all the fields are okay.
19755 const FieldDecl *PreviousField = nullptr;
19756 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
19757 i != end; PreviousField = cast<FieldDecl>(*i), ++i) {
19758 FieldDecl *FD = cast<FieldDecl>(*i);
19759
19760 // Get the type for the field.
19761 const Type *FDTy = FD->getType().getTypePtr();
19762
19763 if (!FD->isAnonymousStructOrUnion()) {
19764 // Remember all fields written by the user.
19765 RecFields.push_back(FD);
19766 }
19767
19768 // If the field is already invalid for some reason, don't emit more
19769 // diagnostics about it.
19770 if (FD->isInvalidDecl()) {
19771 EnclosingDecl->setInvalidDecl();
19772 continue;
19773 }
19774
19775 // C99 6.7.2.1p2:
19776 // A structure or union shall not contain a member with
19777 // incomplete or function type (hence, a structure shall not
19778 // contain an instance of itself, but may contain a pointer to
19779 // an instance of itself), except that the last member of a
19780 // structure with more than one named member may have incomplete
19781 // array type; such a structure (and any union containing,
19782 // possibly recursively, a member that is such a structure)
19783 // shall not be a member of a structure or an element of an
19784 // array.
19785 bool IsLastField = (i + 1 == Fields.end());
19786 if (FDTy->isFunctionType()) {
19787 // Field declared as a function.
19788 Diag(FD->getLocation(), diag::err_field_declared_as_function)
19789 << FD->getDeclName();
19790 FD->setInvalidDecl();
19791 EnclosingDecl->setInvalidDecl();
19792 continue;
19793 } else if (FDTy->isIncompleteArrayType() &&
19794 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
19795 if (Record) {
19796 // Flexible array member.
19797 // Microsoft and g++ is more permissive regarding flexible array.
19798 // It will accept flexible array in union and also
19799 // as the sole element of a struct/class.
19800 unsigned DiagID = 0;
19801 if (!Record->isUnion() && !IsLastField) {
19802 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
19803 << FD->getDeclName() << FD->getType() << Record->getTagKind();
19804 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
19805 FD->setInvalidDecl();
19806 EnclosingDecl->setInvalidDecl();
19807 continue;
19808 } else if (Record->isUnion())
19809 DiagID = getLangOpts().MicrosoftExt
19810 ? diag::ext_flexible_array_union_ms
19811 : diag::ext_flexible_array_union_gnu;
19812 else if (NumNamedMembers < 1)
19813 DiagID = getLangOpts().MicrosoftExt
19814 ? diag::ext_flexible_array_empty_aggregate_ms
19815 : diag::ext_flexible_array_empty_aggregate_gnu;
19816
19817 if (DiagID)
19818 Diag(FD->getLocation(), DiagID)
19819 << FD->getDeclName() << Record->getTagKind();
19820 // While the layout of types that contain virtual bases is not specified
19821 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
19822 // virtual bases after the derived members. This would make a flexible
19823 // array member declared at the end of an object not adjacent to the end
19824 // of the type.
19825 if (CXXRecord && CXXRecord->getNumVBases() != 0)
19826 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
19827 << FD->getDeclName() << Record->getTagKind();
19828 if (!getLangOpts().C99)
19829 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
19830 << FD->getDeclName() << Record->getTagKind();
19831
19832 // If the element type has a non-trivial destructor, we would not
19833 // implicitly destroy the elements, so disallow it for now.
19834 //
19835 // FIXME: GCC allows this. We should probably either implicitly delete
19836 // the destructor of the containing class, or just allow this.
19837 QualType BaseElem = Context.getBaseElementType(FD->getType());
19838 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
19839 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
19840 << FD->getDeclName() << FD->getType();
19841 FD->setInvalidDecl();
19842 EnclosingDecl->setInvalidDecl();
19843 continue;
19844 }
19845 // Okay, we have a legal flexible array member at the end of the struct.
19846 Record->setHasFlexibleArrayMember(true);
19847 } else {
19848 // In ObjCContainerDecl ivars with incomplete array type are accepted,
19849 // unless they are followed by another ivar. That check is done
19850 // elsewhere, after synthesized ivars are known.
19851 }
19852 } else if (!FDTy->isDependentType() &&
19853 (LangOpts.HLSL // HLSL allows sizeless builtin types
19855 diag::err_incomplete_type)
19857 FD->getLocation(), FD->getType(),
19858 diag::err_field_incomplete_or_sizeless))) {
19859 // Incomplete type
19860 FD->setInvalidDecl();
19861 EnclosingDecl->setInvalidDecl();
19862 continue;
19863 } else if (const auto *RD = FDTy->getAsRecordDecl()) {
19864 if (Record && RD->hasFlexibleArrayMember()) {
19865 // A type which contains a flexible array member is considered to be a
19866 // flexible array member.
19867 Record->setHasFlexibleArrayMember(true);
19868 if (!Record->isUnion()) {
19869 // If this is a struct/class and this is not the last element, reject
19870 // it. Note that GCC supports variable sized arrays in the middle of
19871 // structures.
19872 if (!IsLastField)
19873 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
19874 << FD->getDeclName() << FD->getType();
19875 else {
19876 // We support flexible arrays at the end of structs in
19877 // other structs as an extension.
19878 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
19879 << FD->getDeclName();
19880 }
19881 }
19882 }
19883 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
19885 diag::err_abstract_type_in_decl,
19887 // Ivars can not have abstract class types
19888 FD->setInvalidDecl();
19889 }
19890 if (Record && RD->hasObjectMember())
19891 Record->setHasObjectMember(true);
19892 if (Record && RD->hasVolatileMember())
19893 Record->setHasVolatileMember(true);
19894 } else if (FDTy->isObjCObjectType()) {
19895 /// A field cannot be an Objective-c object
19896 Diag(FD->getLocation(), diag::err_statically_allocated_object)
19898 QualType T = Context.getObjCObjectPointerType(FD->getType());
19899 FD->setType(T);
19900 } else if (Record && Record->isUnion() &&
19902 getSourceManager().isInSystemHeader(FD->getLocation()) &&
19903 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
19905 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
19906 // For backward compatibility, fields of C unions declared in system
19907 // headers that have non-trivial ObjC ownership qualifications are marked
19908 // as unavailable unless the qualifier is explicit and __strong. This can
19909 // break ABI compatibility between programs compiled with ARC and MRR, but
19910 // is a better option than rejecting programs using those unions under
19911 // ARC.
19912 FD->addAttr(UnavailableAttr::CreateImplicit(
19913 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
19914 FD->getLocation()));
19915 } else if (getLangOpts().ObjC &&
19916 getLangOpts().getGC() != LangOptions::NonGC && Record &&
19917 !Record->hasObjectMember()) {
19918 if (FD->getType()->isObjCObjectPointerType() ||
19919 FD->getType().isObjCGCStrong())
19920 Record->setHasObjectMember(true);
19921 else if (Context.getAsArrayType(FD->getType())) {
19922 QualType BaseType = Context.getBaseElementType(FD->getType());
19923 if (const auto *RD = BaseType->getAsRecordDecl();
19924 RD && RD->hasObjectMember())
19925 Record->setHasObjectMember(true);
19926 else if (BaseType->isObjCObjectPointerType() ||
19927 BaseType.isObjCGCStrong())
19928 Record->setHasObjectMember(true);
19929 }
19930 }
19931
19932 if (Record && !getLangOpts().CPlusPlus &&
19933 !shouldIgnoreForRecordTriviality(FD)) {
19934 QualType FT = FD->getType();
19936 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
19938 Record->isUnion())
19939 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
19940 }
19943 Record->setNonTrivialToPrimitiveCopy(true);
19944 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
19945 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
19946 }
19947 if (FD->hasAttr<ExplicitInitAttr>())
19948 Record->setHasUninitializedExplicitInitFields(true);
19949 if (FT.isDestructedType()) {
19950 Record->setNonTrivialToPrimitiveDestroy(true);
19951 Record->setParamDestroyedInCallee(true);
19952 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
19953 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
19954 }
19955
19956 if (const auto *RD = FT->getAsRecordDecl()) {
19957 if (RD->getArgPassingRestrictions() ==
19959 Record->setArgPassingRestrictions(
19961 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) {
19962 Record->setArgPassingRestrictions(
19964 } else if (PointerAuthQualifier Q = FT.getPointerAuth();
19965 Q && Q.isAddressDiscriminated()) {
19966 Record->setArgPassingRestrictions(
19968 Record->setNonTrivialToPrimitiveCopy(true);
19969 }
19970 }
19971
19972 if (Record && FD->getType().isVolatileQualified())
19973 Record->setHasVolatileMember(true);
19974 bool ReportMSBitfieldStoragePacking =
19975 Record && PreviousField &&
19976 !Diags.isIgnored(diag::warn_ms_bitfield_mismatched_storage_packing,
19977 Record->getLocation());
19978 auto IsNonDependentBitField = [](const FieldDecl *FD) {
19979 return FD->isBitField() && !FD->getType()->isDependentType();
19980 };
19981
19982 if (ReportMSBitfieldStoragePacking && IsNonDependentBitField(FD) &&
19983 IsNonDependentBitField(PreviousField)) {
19984 CharUnits FDStorageSize = Context.getTypeSizeInChars(FD->getType());
19985 CharUnits PreviousFieldStorageSize =
19986 Context.getTypeSizeInChars(PreviousField->getType());
19987 if (FDStorageSize != PreviousFieldStorageSize) {
19988 Diag(FD->getLocation(),
19989 diag::warn_ms_bitfield_mismatched_storage_packing)
19990 << FD << FD->getType() << FDStorageSize.getQuantity()
19991 << PreviousFieldStorageSize.getQuantity();
19992 Diag(PreviousField->getLocation(),
19993 diag::note_ms_bitfield_mismatched_storage_size_previous)
19994 << PreviousField << PreviousField->getType();
19995 }
19996 }
19997 // Keep track of the number of named members.
19998 if (FD->getIdentifier())
19999 ++NumNamedMembers;
20000 }
20001
20002 // Okay, we successfully defined 'Record'.
20003 if (Record) {
20004 bool Completed = false;
20005 if (S) {
20006 Scope *Parent = S->getParent();
20007 if (Parent && Parent->isTypeAliasScope() &&
20008 Parent->isTemplateParamScope())
20009 Record->setInvalidDecl();
20010 }
20011
20012 if (CXXRecord) {
20013 if (!CXXRecord->isInvalidDecl()) {
20014 // Set access bits correctly on the directly-declared conversions.
20016 I = CXXRecord->conversion_begin(),
20017 E = CXXRecord->conversion_end(); I != E; ++I)
20018 I.setAccess((*I)->getAccess());
20019 }
20020
20021 // Add any implicitly-declared members to this class.
20023
20024 if (!CXXRecord->isDependentType()) {
20025 if (!CXXRecord->isInvalidDecl()) {
20026 // If we have virtual base classes, we may end up finding multiple
20027 // final overriders for a given virtual function. Check for this
20028 // problem now.
20029 if (CXXRecord->getNumVBases()) {
20030 CXXFinalOverriderMap FinalOverriders;
20031 CXXRecord->getFinalOverriders(FinalOverriders);
20032
20033 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
20034 MEnd = FinalOverriders.end();
20035 M != MEnd; ++M) {
20036 for (OverridingMethods::iterator SO = M->second.begin(),
20037 SOEnd = M->second.end();
20038 SO != SOEnd; ++SO) {
20039 assert(SO->second.size() > 0 &&
20040 "Virtual function without overriding functions?");
20041 if (SO->second.size() == 1)
20042 continue;
20043
20044 // C++ [class.virtual]p2:
20045 // In a derived class, if a virtual member function of a base
20046 // class subobject has more than one final overrider the
20047 // program is ill-formed.
20048 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
20049 << (const NamedDecl *)M->first << Record;
20050 Diag(M->first->getLocation(),
20051 diag::note_overridden_virtual_function);
20053 OM = SO->second.begin(),
20054 OMEnd = SO->second.end();
20055 OM != OMEnd; ++OM)
20056 Diag(OM->Method->getLocation(), diag::note_final_overrider)
20057 << (const NamedDecl *)M->first << OM->Method->getParent();
20058
20059 Record->setInvalidDecl();
20060 }
20061 }
20062 CXXRecord->completeDefinition(&FinalOverriders);
20063 Completed = true;
20064 }
20065 }
20066 ComputeSelectedDestructor(*this, CXXRecord);
20068 }
20069 }
20070
20071 if (!Completed)
20072 Record->completeDefinition();
20073
20074 // Handle attributes before checking the layout.
20076
20077 // Maybe randomize the record's decls. We automatically randomize a record
20078 // of function pointers, unless it has the "no_randomize_layout" attribute.
20079 if (!getLangOpts().CPlusPlus && !getLangOpts().RandstructSeed.empty() &&
20080 !Record->isRandomized() && !Record->isUnion() &&
20081 (Record->hasAttr<RandomizeLayoutAttr>() ||
20082 (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
20083 EntirelyFunctionPointers(Record)))) {
20084 SmallVector<Decl *, 32> NewDeclOrdering;
20086 NewDeclOrdering))
20087 Record->reorderDecls(NewDeclOrdering);
20088 }
20089
20090 // We may have deferred checking for a deleted destructor. Check now.
20091 if (CXXRecord) {
20092 auto *Dtor = CXXRecord->getDestructor();
20093 if (Dtor && Dtor->isImplicit() &&
20095 CXXRecord->setImplicitDestructorIsDeleted();
20096 SetDeclDeleted(Dtor, CXXRecord->getLocation());
20097 }
20098 }
20099
20100 if (Record->hasAttrs()) {
20102
20103 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
20105 IA->getRange(), IA->getBestCase(),
20106 IA->getInheritanceModel());
20107 }
20108
20109 // Check if the structure/union declaration is a type that can have zero
20110 // size in C. For C this is a language extension, for C++ it may cause
20111 // compatibility problems.
20112 bool CheckForZeroSize;
20113 if (!getLangOpts().CPlusPlus) {
20114 CheckForZeroSize = true;
20115 } else {
20116 // For C++ filter out types that cannot be referenced in C code.
20118 CheckForZeroSize =
20119 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
20120 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
20121 CXXRecord->isCLike();
20122 }
20123 if (CheckForZeroSize) {
20124 bool ZeroSize = true;
20125 bool IsEmpty = true;
20126 unsigned NonBitFields = 0;
20127 for (RecordDecl::field_iterator I = Record->field_begin(),
20128 E = Record->field_end();
20129 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
20130 IsEmpty = false;
20131 if (I->isUnnamedBitField()) {
20132 if (!I->isZeroLengthBitField())
20133 ZeroSize = false;
20134 } else {
20135 ++NonBitFields;
20136 QualType FieldType = I->getType();
20137 if (FieldType->isIncompleteType() ||
20138 !Context.getTypeSizeInChars(FieldType).isZero())
20139 ZeroSize = false;
20140 }
20141 }
20142
20143 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
20144 // allowed in C++, but warn if its declaration is inside
20145 // extern "C" block.
20146 if (ZeroSize) {
20147 Diag(RecLoc, getLangOpts().CPlusPlus ?
20148 diag::warn_zero_size_struct_union_in_extern_c :
20149 diag::warn_zero_size_struct_union_compat)
20150 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
20151 }
20152
20153 // Structs without named members are extension in C (C99 6.7.2.1p7),
20154 // but are accepted by GCC. In C2y, this became implementation-defined
20155 // (C2y 6.7.3.2p10).
20156 if (NonBitFields == 0 && !getLangOpts().CPlusPlus && !getLangOpts().C2y) {
20157 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union
20158 : diag::ext_no_named_members_in_struct_union)
20159 << Record->isUnion();
20160 }
20161 }
20162 } else {
20163 ObjCIvarDecl **ClsFields =
20164 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
20165 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
20166 ID->setEndOfDefinitionLoc(RBrac);
20167 // Add ivar's to class's DeclContext.
20168 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
20169 ClsFields[i]->setLexicalDeclContext(ID);
20170 ID->addDecl(ClsFields[i]);
20171 }
20172 // Must enforce the rule that ivars in the base classes may not be
20173 // duplicates.
20174 if (ID->getSuperClass())
20175 ObjC().DiagnoseDuplicateIvars(ID, ID->getSuperClass());
20176 } else if (ObjCImplementationDecl *IMPDecl =
20177 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
20178 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
20179 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
20180 // Ivar declared in @implementation never belongs to the implementation.
20181 // Only it is in implementation's lexical context.
20182 ClsFields[I]->setLexicalDeclContext(IMPDecl);
20183 ObjC().CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(),
20184 RBrac);
20185 IMPDecl->setIvarLBraceLoc(LBrac);
20186 IMPDecl->setIvarRBraceLoc(RBrac);
20187 } else if (ObjCCategoryDecl *CDecl =
20188 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
20189 // case of ivars in class extension; all other cases have been
20190 // reported as errors elsewhere.
20191 // FIXME. Class extension does not have a LocEnd field.
20192 // CDecl->setLocEnd(RBrac);
20193 // Add ivar's to class extension's DeclContext.
20194 // Diagnose redeclaration of private ivars.
20195 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
20196 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
20197 if (IDecl) {
20198 if (const ObjCIvarDecl *ClsIvar =
20199 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
20200 Diag(ClsFields[i]->getLocation(),
20201 diag::err_duplicate_ivar_declaration);
20202 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
20203 continue;
20204 }
20205 for (const auto *Ext : IDecl->known_extensions()) {
20206 if (const ObjCIvarDecl *ClsExtIvar
20207 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
20208 Diag(ClsFields[i]->getLocation(),
20209 diag::err_duplicate_ivar_declaration);
20210 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
20211 continue;
20212 }
20213 }
20214 }
20215 ClsFields[i]->setLexicalDeclContext(CDecl);
20216 CDecl->addDecl(ClsFields[i]);
20217 }
20218 CDecl->setIvarLBraceLoc(LBrac);
20219 CDecl->setIvarRBraceLoc(RBrac);
20220 }
20221 }
20224}
20225
20226// Given an integral type, return the next larger integral type
20227// (or a NULL type of no such type exists).
20229 // FIXME: Int128/UInt128 support, which also needs to be introduced into
20230 // enum checking below.
20231 assert((T->isIntegralType(Context) ||
20232 T->isEnumeralType()) && "Integral type required!");
20233 const unsigned NumTypes = 4;
20234 QualType SignedIntegralTypes[NumTypes] = {
20235 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
20236 };
20237 QualType UnsignedIntegralTypes[NumTypes] = {
20238 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
20239 Context.UnsignedLongLongTy
20240 };
20241
20242 unsigned BitWidth = Context.getTypeSize(T);
20243 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
20244 : UnsignedIntegralTypes;
20245 for (unsigned I = 0; I != NumTypes; ++I)
20246 if (Context.getTypeSize(Types[I]) > BitWidth)
20247 return Types[I];
20248
20249 return QualType();
20250}
20251
20253 EnumConstantDecl *LastEnumConst,
20254 SourceLocation IdLoc,
20255 IdentifierInfo *Id,
20256 Expr *Val) {
20257 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
20258 llvm::APSInt EnumVal(IntWidth);
20259 QualType EltTy;
20260
20262 Val = nullptr;
20263
20264 if (Val)
20265 Val = DefaultLvalueConversion(Val).get();
20266
20267 if (Val) {
20268 if (Enum->isDependentType() || Val->isTypeDependent() ||
20269 Val->containsErrors())
20270 EltTy = Context.DependentTy;
20271 else {
20272 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
20273 // underlying type, but do allow it in all other contexts.
20274 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
20275 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
20276 // constant-expression in the enumerator-definition shall be a converted
20277 // constant expression of the underlying type.
20278 EltTy = Enum->getIntegerType();
20280 Val, EltTy, EnumVal, CCEKind::Enumerator);
20281 if (Converted.isInvalid())
20282 Val = nullptr;
20283 else
20284 Val = Converted.get();
20285 } else if (!Val->isValueDependent() &&
20286 !(Val = VerifyIntegerConstantExpression(Val, &EnumVal,
20288 .get())) {
20289 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
20290 } else {
20291 if (Enum->isComplete()) {
20292 EltTy = Enum->getIntegerType();
20293
20294 // In Obj-C and Microsoft mode, require the enumeration value to be
20295 // representable in the underlying type of the enumeration. In C++11,
20296 // we perform a non-narrowing conversion as part of converted constant
20297 // expression checking.
20298 if (!Context.isRepresentableIntegerValue(EnumVal, EltTy)) {
20299 if (Context.getTargetInfo()
20300 .getTriple()
20301 .isWindowsMSVCEnvironment()) {
20302 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
20303 } else {
20304 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
20305 }
20306 }
20307
20308 // Cast to the underlying type.
20309 Val = ImpCastExprToType(Val, EltTy,
20310 EltTy->isBooleanType() ? CK_IntegralToBoolean
20311 : CK_IntegralCast)
20312 .get();
20313 } else if (getLangOpts().CPlusPlus) {
20314 // C++11 [dcl.enum]p5:
20315 // If the underlying type is not fixed, the type of each enumerator
20316 // is the type of its initializing value:
20317 // - If an initializer is specified for an enumerator, the
20318 // initializing value has the same type as the expression.
20319 EltTy = Val->getType();
20320 } else {
20321 // C99 6.7.2.2p2:
20322 // The expression that defines the value of an enumeration constant
20323 // shall be an integer constant expression that has a value
20324 // representable as an int.
20325
20326 // Complain if the value is not representable in an int.
20327 if (!Context.isRepresentableIntegerValue(EnumVal, Context.IntTy)) {
20328 Diag(IdLoc, getLangOpts().C23
20329 ? diag::warn_c17_compat_enum_value_not_int
20330 : diag::ext_c23_enum_value_not_int)
20331 << 0 << toString(EnumVal, 10) << Val->getSourceRange()
20332 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
20333 } else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
20334 // Force the type of the expression to 'int'.
20335 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
20336 }
20337 EltTy = Val->getType();
20338 }
20339 }
20340 }
20341 }
20342
20343 if (!Val) {
20344 if (Enum->isDependentType())
20345 EltTy = Context.DependentTy;
20346 else if (!LastEnumConst) {
20347 // C++0x [dcl.enum]p5:
20348 // If the underlying type is not fixed, the type of each enumerator
20349 // is the type of its initializing value:
20350 // - If no initializer is specified for the first enumerator, the
20351 // initializing value has an unspecified integral type.
20352 //
20353 // GCC uses 'int' for its unspecified integral type, as does
20354 // C99 6.7.2.2p3.
20355 if (Enum->isFixed()) {
20356 EltTy = Enum->getIntegerType();
20357 }
20358 else {
20359 EltTy = Context.IntTy;
20360 }
20361 } else {
20362 // Assign the last value + 1.
20363 EnumVal = LastEnumConst->getInitVal();
20364 ++EnumVal;
20365 EltTy = LastEnumConst->getType();
20366
20367 // Check for overflow on increment.
20368 if (EnumVal < LastEnumConst->getInitVal()) {
20369 // C++0x [dcl.enum]p5:
20370 // If the underlying type is not fixed, the type of each enumerator
20371 // is the type of its initializing value:
20372 //
20373 // - Otherwise the type of the initializing value is the same as
20374 // the type of the initializing value of the preceding enumerator
20375 // unless the incremented value is not representable in that type,
20376 // in which case the type is an unspecified integral type
20377 // sufficient to contain the incremented value. If no such type
20378 // exists, the program is ill-formed.
20380 if (T.isNull() || Enum->isFixed()) {
20381 // There is no integral type larger enough to represent this
20382 // value. Complain, then allow the value to wrap around.
20383 EnumVal = LastEnumConst->getInitVal();
20384 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
20385 ++EnumVal;
20386 if (Enum->isFixed())
20387 // When the underlying type is fixed, this is ill-formed.
20388 Diag(IdLoc, diag::err_enumerator_wrapped)
20389 << toString(EnumVal, 10)
20390 << EltTy;
20391 else
20392 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
20393 << toString(EnumVal, 10);
20394 } else {
20395 EltTy = T;
20396 }
20397
20398 // Retrieve the last enumerator's value, extent that type to the
20399 // type that is supposed to be large enough to represent the incremented
20400 // value, then increment.
20401 EnumVal = LastEnumConst->getInitVal();
20402 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20403 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
20404 ++EnumVal;
20405
20406 // If we're not in C++, diagnose the overflow of enumerator values,
20407 // which in C99 means that the enumerator value is not representable in
20408 // an int (C99 6.7.2.2p2). However C23 permits enumerator values that
20409 // are representable in some larger integral type and we allow it in
20410 // older language modes as an extension.
20411 // Exclude fixed enumerators since they are diagnosed with an error for
20412 // this case.
20413 if (!getLangOpts().CPlusPlus && !T.isNull() && !Enum->isFixed())
20414 Diag(IdLoc, getLangOpts().C23
20415 ? diag::warn_c17_compat_enum_value_not_int
20416 : diag::ext_c23_enum_value_not_int)
20417 << 1 << toString(EnumVal, 10) << 1;
20418 } else if (!getLangOpts().CPlusPlus && !EltTy->isDependentType() &&
20419 !Context.isRepresentableIntegerValue(EnumVal, EltTy)) {
20420 // Enforce C99 6.7.2.2p2 even when we compute the next value.
20421 Diag(IdLoc, getLangOpts().C23 ? diag::warn_c17_compat_enum_value_not_int
20422 : diag::ext_c23_enum_value_not_int)
20423 << 1 << toString(EnumVal, 10) << 1;
20424 }
20425 }
20426 }
20427
20428 if (!EltTy->isDependentType()) {
20429 // Make the enumerator value match the signedness and size of the
20430 // enumerator's type.
20431 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
20432 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20433 }
20434
20435 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
20436 Val, EnumVal);
20437}
20438
20440 SourceLocation IILoc) {
20441 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
20443 return SkipBodyInfo();
20444
20445 // We have an anonymous enum definition. Look up the first enumerator to
20446 // determine if we should merge the definition with an existing one and
20447 // skip the body.
20448 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
20450 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
20451 if (!PrevECD)
20452 return SkipBodyInfo();
20453
20454 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
20455 NamedDecl *Hidden;
20456 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
20458 Skip.Previous = Hidden;
20459 return Skip;
20460 }
20461
20462 return SkipBodyInfo();
20463}
20464
20465Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
20466 SourceLocation IdLoc, IdentifierInfo *Id,
20467 const ParsedAttributesView &Attrs,
20468 SourceLocation EqualLoc, Expr *Val,
20469 SkipBodyInfo *SkipBody) {
20470 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
20471 EnumConstantDecl *LastEnumConst =
20472 cast_or_null<EnumConstantDecl>(lastEnumConst);
20473
20474 // The scope passed in may not be a decl scope. Zip up the scope tree until
20475 // we find one that is.
20476 S = getNonFieldDeclScope(S);
20477
20478 // Verify that there isn't already something declared with this name in this
20479 // scope.
20480 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName,
20482 LookupName(R, S);
20483 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
20484
20485 if (PrevDecl && PrevDecl->isTemplateParameter()) {
20486 // Maybe we will complain about the shadowed template parameter.
20487 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
20488 // Just pretend that we didn't see the previous declaration.
20489 PrevDecl = nullptr;
20490 }
20491
20492 // C++ [class.mem]p15:
20493 // If T is the name of a class, then each of the following shall have a name
20494 // different from T:
20495 // - every enumerator of every member of class T that is an unscoped
20496 // enumerated type
20497 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped() &&
20499 DeclarationNameInfo(Id, IdLoc)))
20500 return nullptr;
20501
20503 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
20504 if (!New)
20505 return nullptr;
20506
20507 if (PrevDecl && (!SkipBody || !SkipBody->CheckSameAsPrevious)) {
20508 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
20509 // Check for other kinds of shadowing not already handled.
20510 CheckShadow(New, PrevDecl, R);
20511 }
20512
20513 // When in C++, we may get a TagDecl with the same name; in this case the
20514 // enum constant will 'hide' the tag.
20515 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
20516 "Received TagDecl when not in C++!");
20517 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
20518 if (isa<EnumConstantDecl>(PrevDecl))
20519 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
20520 else
20521 Diag(IdLoc, diag::err_redefinition) << Id;
20522 notePreviousDefinition(PrevDecl, IdLoc);
20523 return nullptr;
20524 }
20525 }
20526
20527 // Process attributes.
20528 ProcessDeclAttributeList(S, New, Attrs);
20531
20532 // Register this decl in the current scope stack.
20533 New->setAccess(TheEnumDecl->getAccess());
20535
20537
20538 return New;
20539}
20540
20541// Returns true when the enum initial expression does not trigger the
20542// duplicate enum warning. A few common cases are exempted as follows:
20543// Element2 = Element1
20544// Element2 = Element1 + 1
20545// Element2 = Element1 - 1
20546// Where Element2 and Element1 are from the same enum.
20548 Expr *InitExpr = ECD->getInitExpr();
20549 if (!InitExpr)
20550 return true;
20551 InitExpr = InitExpr->IgnoreImpCasts();
20552
20553 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
20554 if (!BO->isAdditiveOp())
20555 return true;
20556 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
20557 if (!IL)
20558 return true;
20559 if (IL->getValue() != 1)
20560 return true;
20561
20562 InitExpr = BO->getLHS();
20563 }
20564
20565 // This checks if the elements are from the same enum.
20566 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
20567 if (!DRE)
20568 return true;
20569
20570 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
20571 if (!EnumConstant)
20572 return true;
20573
20575 Enum)
20576 return true;
20577
20578 return false;
20579}
20580
20581// Emits a warning when an element is implicitly set a value that
20582// a previous element has already been set to.
20584 EnumDecl *Enum, QualType EnumType) {
20585 // Avoid anonymous enums
20586 if (!Enum->getIdentifier())
20587 return;
20588
20589 // Only check for small enums.
20590 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
20591 return;
20592
20593 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
20594 return;
20595
20596 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
20597 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
20598
20599 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
20600
20601 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
20602 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
20603
20604 // Use int64_t as a key to avoid needing special handling for map keys.
20605 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
20606 llvm::APSInt Val = D->getInitVal();
20607 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
20608 };
20609
20610 DuplicatesVector DupVector;
20611 ValueToVectorMap EnumMap;
20612
20613 // Populate the EnumMap with all values represented by enum constants without
20614 // an initializer.
20615 for (auto *Element : Elements) {
20616 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
20617
20618 // Null EnumConstantDecl means a previous diagnostic has been emitted for
20619 // this constant. Skip this enum since it may be ill-formed.
20620 if (!ECD) {
20621 return;
20622 }
20623
20624 // Constants with initializers are handled in the next loop.
20625 if (ECD->getInitExpr())
20626 continue;
20627
20628 // Duplicate values are handled in the next loop.
20629 EnumMap.insert({EnumConstantToKey(ECD), ECD});
20630 }
20631
20632 if (EnumMap.size() == 0)
20633 return;
20634
20635 // Create vectors for any values that has duplicates.
20636 for (auto *Element : Elements) {
20637 // The last loop returned if any constant was null.
20639 if (!ValidDuplicateEnum(ECD, Enum))
20640 continue;
20641
20642 auto Iter = EnumMap.find(EnumConstantToKey(ECD));
20643 if (Iter == EnumMap.end())
20644 continue;
20645
20646 DeclOrVector& Entry = Iter->second;
20647 if (EnumConstantDecl *D = dyn_cast<EnumConstantDecl *>(Entry)) {
20648 // Ensure constants are different.
20649 if (D == ECD)
20650 continue;
20651
20652 // Create new vector and push values onto it.
20653 auto Vec = std::make_unique<ECDVector>();
20654 Vec->push_back(D);
20655 Vec->push_back(ECD);
20656
20657 // Update entry to point to the duplicates vector.
20658 Entry = Vec.get();
20659
20660 // Store the vector somewhere we can consult later for quick emission of
20661 // diagnostics.
20662 DupVector.emplace_back(std::move(Vec));
20663 continue;
20664 }
20665
20666 ECDVector *Vec = cast<ECDVector *>(Entry);
20667 // Make sure constants are not added more than once.
20668 if (*Vec->begin() == ECD)
20669 continue;
20670
20671 Vec->push_back(ECD);
20672 }
20673
20674 // Emit diagnostics.
20675 for (const auto &Vec : DupVector) {
20676 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
20677
20678 // Emit warning for one enum constant.
20679 auto *FirstECD = Vec->front();
20680 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
20681 << FirstECD << toString(FirstECD->getInitVal(), 10)
20682 << FirstECD->getSourceRange();
20683
20684 // Emit one note for each of the remaining enum constants with
20685 // the same value.
20686 for (auto *ECD : llvm::drop_begin(*Vec))
20687 S.Diag(ECD->getLocation(), diag::note_duplicate_element)
20688 << ECD << toString(ECD->getInitVal(), 10)
20689 << ECD->getSourceRange();
20690 }
20691}
20692
20693bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
20694 bool AllowMask) const {
20695 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
20696 assert(ED->isCompleteDefinition() && "expected enum definition");
20697
20698 auto R = FlagBitsCache.try_emplace(ED);
20699 llvm::APInt &FlagBits = R.first->second;
20700
20701 if (R.second) {
20702 for (auto *E : ED->enumerators()) {
20703 const auto &EVal = E->getInitVal();
20704 // Only single-bit enumerators introduce new flag values.
20705 if (EVal.isPowerOf2())
20706 FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal;
20707 }
20708 }
20709
20710 // A value is in a flag enum if either its bits are a subset of the enum's
20711 // flag bits (the first condition) or we are allowing masks and the same is
20712 // true of its complement (the second condition). When masks are allowed, we
20713 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
20714 //
20715 // While it's true that any value could be used as a mask, the assumption is
20716 // that a mask will have all of the insignificant bits set. Anything else is
20717 // likely a logic error.
20718 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
20719 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
20720}
20721
20722// Emits a warning when a suspicious comparison operator is used along side
20723// binary operators in enum initializers.
20725 const EnumDecl *Enum) {
20726 bool HasBitwiseOp = false;
20727 SmallVector<const BinaryOperator *, 4> SuspiciousCompares;
20728
20729 // Iterate over all the enum values, gather suspisious comparison ops and
20730 // whether any enum initialisers contain a binary operator.
20731 for (const auto *ECD : Enum->enumerators()) {
20732 const Expr *InitExpr = ECD->getInitExpr();
20733 if (!InitExpr)
20734 continue;
20735
20736 const Expr *E = InitExpr->IgnoreParenImpCasts();
20737
20738 if (const auto *BinOp = dyn_cast<BinaryOperator>(E)) {
20739 BinaryOperatorKind Op = BinOp->getOpcode();
20740
20741 // Check for bitwise ops (<<, >>, &, |)
20742 if (BinOp->isBitwiseOp() || BinOp->isShiftOp()) {
20743 HasBitwiseOp = true;
20744 } else if (Op == BO_LT || Op == BO_GT) {
20745 // Check for the typo pattern (Comparison < or >)
20746 const Expr *LHS = BinOp->getLHS()->IgnoreParenImpCasts();
20747 if (const auto *IntLiteral = dyn_cast<IntegerLiteral>(LHS)) {
20748 // Specifically looking for accidental bitshifts "1 < X" or "1 > X"
20749 if (IntLiteral->getValue() == 1)
20750 SuspiciousCompares.push_back(BinOp);
20751 }
20752 }
20753 }
20754 }
20755
20756 // If we found a bitwise op and some sus compares, iterate over the compares
20757 // and warn.
20758 if (HasBitwiseOp) {
20759 for (const auto *BinOp : SuspiciousCompares) {
20760 StringRef SuggestedOp = (BinOp->getOpcode() == BO_LT)
20763 SourceLocation OperatorLoc = BinOp->getOperatorLoc();
20764
20765 Sema.Diag(OperatorLoc, diag::warn_comparison_in_enum_initializer)
20766 << BinOp->getOpcodeStr() << SuggestedOp;
20767
20768 Sema.Diag(OperatorLoc, diag::note_enum_compare_typo_suggest)
20769 << SuggestedOp
20770 << FixItHint::CreateReplacement(OperatorLoc, SuggestedOp);
20771 }
20772 }
20773}
20774
20776 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
20777 const ParsedAttributesView &Attrs) {
20778 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
20779 CanQualType EnumType = Context.getCanonicalTagType(Enum);
20780
20781 ProcessDeclAttributeList(S, Enum, Attrs);
20783
20784 if (Enum->isDependentType()) {
20785 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
20786 EnumConstantDecl *ECD =
20787 cast_or_null<EnumConstantDecl>(Elements[i]);
20788 if (!ECD) continue;
20789
20790 ECD->setType(EnumType);
20791 }
20792
20793 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
20794 return;
20795 }
20796
20797 // Verify that all the values are okay, compute the size of the values, and
20798 // reverse the list.
20799 unsigned NumNegativeBits = 0;
20800 unsigned NumPositiveBits = 0;
20801 bool MembersRepresentableByInt =
20802 Context.computeEnumBits(Elements, NumNegativeBits, NumPositiveBits);
20803
20804 // Figure out the type that should be used for this enum.
20805 QualType BestType;
20806 unsigned BestWidth;
20807
20808 // C++0x N3000 [conv.prom]p3:
20809 // An rvalue of an unscoped enumeration type whose underlying
20810 // type is not fixed can be converted to an rvalue of the first
20811 // of the following types that can represent all the values of
20812 // the enumeration: int, unsigned int, long int, unsigned long
20813 // int, long long int, or unsigned long long int.
20814 // C99 6.4.4.3p2:
20815 // An identifier declared as an enumeration constant has type int.
20816 // The C99 rule is modified by C23.
20817 QualType BestPromotionType;
20818
20819 bool Packed = Enum->hasAttr<PackedAttr>();
20820 // -fshort-enums is the equivalent to specifying the packed attribute on all
20821 // enum definitions.
20822 if (LangOpts.ShortEnums)
20823 Packed = true;
20824
20825 // If the enum already has a type because it is fixed or dictated by the
20826 // target, promote that type instead of analyzing the enumerators.
20827 if (Enum->isComplete()) {
20828 BestType = Enum->getIntegerType();
20829 if (Context.isPromotableIntegerType(BestType))
20830 BestPromotionType = Context.getPromotedIntegerType(BestType);
20831 else
20832 BestPromotionType = BestType;
20833
20834 BestWidth = Context.getIntWidth(BestType);
20835 } else {
20836 bool EnumTooLarge = Context.computeBestEnumTypes(
20837 Packed, NumNegativeBits, NumPositiveBits, BestType, BestPromotionType);
20838 BestWidth = Context.getIntWidth(BestType);
20839 if (EnumTooLarge)
20840 Diag(Enum->getLocation(), diag::ext_enum_too_large);
20841 }
20842
20843 // Loop over all of the enumerator constants, changing their types to match
20844 // the type of the enum if needed.
20845 for (auto *D : Elements) {
20846 auto *ECD = cast_or_null<EnumConstantDecl>(D);
20847 if (!ECD) continue; // Already issued a diagnostic.
20848
20849 // C99 says the enumerators have int type, but we allow, as an
20850 // extension, the enumerators to be larger than int size. If each
20851 // enumerator value fits in an int, type it as an int, otherwise type it the
20852 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
20853 // that X has type 'int', not 'unsigned'.
20854
20855 // Determine whether the value fits into an int.
20856 llvm::APSInt InitVal = ECD->getInitVal();
20857
20858 // If it fits into an integer type, force it. Otherwise force it to match
20859 // the enum decl type.
20860 QualType NewTy;
20861 unsigned NewWidth;
20862 bool NewSign;
20863 if (!getLangOpts().CPlusPlus && !Enum->isFixed() &&
20864 MembersRepresentableByInt) {
20865 // C23 6.7.3.3.3p15:
20866 // The enumeration member type for an enumerated type without fixed
20867 // underlying type upon completion is:
20868 // - int if all the values of the enumeration are representable as an
20869 // int; or,
20870 // - the enumerated type
20871 NewTy = Context.IntTy;
20872 NewWidth = Context.getTargetInfo().getIntWidth();
20873 NewSign = true;
20874 } else if (ECD->getType() == BestType) {
20875 // Already the right type!
20876 if (getLangOpts().CPlusPlus || (getLangOpts().C23 && Enum->isFixed()))
20877 // C++ [dcl.enum]p4: Following the closing brace of an
20878 // enum-specifier, each enumerator has the type of its
20879 // enumeration.
20880 // C23 6.7.3.3p16: The enumeration member type for an enumerated type
20881 // with fixed underlying type is the enumerated type.
20882 ECD->setType(EnumType);
20883 continue;
20884 } else {
20885 NewTy = BestType;
20886 NewWidth = BestWidth;
20887 NewSign = BestType->isSignedIntegerOrEnumerationType();
20888 }
20889
20890 // Adjust the APSInt value.
20891 InitVal = InitVal.extOrTrunc(NewWidth);
20892 InitVal.setIsSigned(NewSign);
20893 ECD->setInitVal(Context, InitVal);
20894
20895 // Adjust the Expr initializer and type.
20896 if (ECD->getInitExpr() &&
20897 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
20898 ECD->setInitExpr(ImplicitCastExpr::Create(
20899 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
20900 /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
20901 if (getLangOpts().CPlusPlus ||
20902 (getLangOpts().C23 && (Enum->isFixed() || !MembersRepresentableByInt)))
20903 // C++ [dcl.enum]p4: Following the closing brace of an
20904 // enum-specifier, each enumerator has the type of its
20905 // enumeration.
20906 // C23 6.7.3.3p16: The enumeration member type for an enumerated type
20907 // with fixed underlying type is the enumerated type.
20908 ECD->setType(EnumType);
20909 else
20910 ECD->setType(NewTy);
20911 }
20912
20913 Enum->completeDefinition(BestType, BestPromotionType,
20914 NumPositiveBits, NumNegativeBits);
20915
20916 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
20918
20919 if (Enum->isClosedFlag()) {
20920 for (Decl *D : Elements) {
20921 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
20922 if (!ECD) continue; // Already issued a diagnostic.
20923
20924 llvm::APSInt InitVal = ECD->getInitVal();
20925 if (InitVal != 0 && !InitVal.isPowerOf2() &&
20926 !IsValueInFlagEnum(Enum, InitVal, true))
20927 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
20928 << ECD << Enum;
20929 }
20930 }
20931
20932 // Now that the enum type is defined, ensure it's not been underaligned.
20933 if (Enum->hasAttrs())
20935}
20936
20938 SourceLocation EndLoc) {
20939
20941 FileScopeAsmDecl::Create(Context, CurContext, expr, StartLoc, EndLoc);
20942 CurContext->addDecl(New);
20943 return New;
20944}
20945
20947 auto *New = TopLevelStmtDecl::Create(Context, /*Statement=*/nullptr);
20948 CurContext->addDecl(New);
20949 PushDeclContext(S, New);
20951 PushCompoundScope(false);
20952 return New;
20953}
20954
20956 if (Statement)
20957 D->setStmt(Statement);
20961}
20962
20964 IdentifierInfo* AliasName,
20965 SourceLocation PragmaLoc,
20966 SourceLocation NameLoc,
20967 SourceLocation AliasNameLoc) {
20968 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
20970 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
20972 AsmLabelAttr *Attr =
20973 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), Info);
20974
20975 // If a declaration that:
20976 // 1) declares a function or a variable
20977 // 2) has external linkage
20978 // already exists, add a label attribute to it.
20979 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
20980 if (isDeclExternC(PrevDecl))
20981 PrevDecl->addAttr(Attr);
20982 else
20983 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
20984 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
20985 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
20986 } else
20987 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
20988}
20989
20991 SourceLocation PragmaLoc,
20992 SourceLocation NameLoc) {
20993 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
20994
20995 if (PrevDecl) {
20996 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
20997 } else {
20998 (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
20999 }
21000}
21001
21003 IdentifierInfo* AliasName,
21004 SourceLocation PragmaLoc,
21005 SourceLocation NameLoc,
21006 SourceLocation AliasNameLoc) {
21007 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
21009 WeakInfo W = WeakInfo(Name, NameLoc);
21010
21011 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
21012 if (!PrevDecl->hasAttr<AliasAttr>())
21013 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
21015 } else {
21016 (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
21017 }
21018}
21019
21021 bool Final) {
21022 assert(FD && "Expected non-null FunctionDecl");
21023
21024 // SYCL functions can be template, so we check if they have appropriate
21025 // attribute prior to checking if it is a template.
21026 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
21028
21029 // Templates are emitted when they're instantiated.
21030 if (FD->isDependentContext())
21032
21033 // Check whether this function is an externally visible definition.
21034 auto IsEmittedForExternalSymbol = [this, FD]() {
21035 // We have to check the GVA linkage of the function's *definition* -- if we
21036 // only have a declaration, we don't know whether or not the function will
21037 // be emitted, because (say) the definition could include "inline".
21038 const FunctionDecl *Def = FD->getDefinition();
21039
21040 // We can't compute linkage when we skip function bodies.
21041 return Def && !Def->hasSkippedBody() &&
21043 getASTContext().GetGVALinkageForFunction(Def));
21044 };
21045
21046 if (LangOpts.OpenMPIsTargetDevice) {
21047 // In OpenMP device mode we will not emit host only functions, or functions
21048 // we don't need due to their linkage.
21049 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
21050 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
21051 // DevTy may be changed later by
21052 // #pragma omp declare target to(*) device_type(*).
21053 // Therefore DevTy having no value does not imply host. The emission status
21054 // will be checked again at the end of compilation unit with Final = true.
21055 if (DevTy)
21056 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
21058 // If we have an explicit value for the device type, or we are in a target
21059 // declare context, we need to emit all extern and used symbols.
21060 if (OpenMP().isInOpenMPDeclareTargetContext() || DevTy)
21061 if (IsEmittedForExternalSymbol())
21063 // Device mode only emits what it must, if it wasn't tagged yet and needed,
21064 // we'll omit it.
21065 if (Final)
21067 } else if (LangOpts.OpenMP > 45) {
21068 // In OpenMP host compilation prior to 5.0 everything was an emitted host
21069 // function. In 5.0, no_host was introduced which might cause a function to
21070 // be omitted.
21071 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
21072 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
21073 if (DevTy)
21074 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
21076 }
21077
21078 if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
21080
21081 if (LangOpts.CUDA) {
21082 // When compiling for device, host functions are never emitted. Similarly,
21083 // when compiling for host, device and global functions are never emitted.
21084 // (Technically, we do emit a host-side stub for global functions, but this
21085 // doesn't count for our purposes here.)
21087 if (LangOpts.CUDAIsDevice && T == CUDAFunctionTarget::Host)
21089 if (!LangOpts.CUDAIsDevice &&
21092
21093 if (IsEmittedForExternalSymbol())
21095
21096 // If FD is a virtual destructor of an explicit instantiation
21097 // of a template class, return Emitted.
21098 if (auto *Destructor = dyn_cast<CXXDestructorDecl>(FD)) {
21099 if (Destructor->isVirtual()) {
21100 if (auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(
21101 Destructor->getParent())) {
21103 Spec->getTemplateSpecializationKind();
21107 }
21108 }
21109 }
21110 }
21111
21112 // Otherwise, the function is known-emitted if it's in our set of
21113 // known-emitted functions.
21115}
21116
21118 // Host-side references to a __global__ function refer to the stub, so the
21119 // function itself is never emitted and therefore should not be marked.
21120 // If we have host fn calls kernel fn calls host+device, the HD function
21121 // does not get instantiated on the host. We model this by omitting at the
21122 // call to the kernel from the callgraph. This ensures that, when compiling
21123 // for host, only HD functions actually called from the host get marked as
21124 // known-emitted.
21125 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
21127}
21128
21130 bool &Visible) {
21131 Visible = hasVisibleDefinition(D, Suggested);
21132 // The redefinition of D in the **current** TU is allowed if D is invisible or
21133 // D is defined in the global module of other module units. We didn't check if
21134 // it is in global module as, we'll check the redefinition in named module
21135 // later with better diagnostic message.
21136 return D->isInAnotherModuleUnit() || !Visible;
21137}
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:2240
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
static bool hasDefinition(const ObjCObjectPointerType *ObjPtr)
Defines the clang::Expr interface and subclasses for C++ expressions.
TokenType getType() const
Returns the token's type, e.g.
FormatToken * Previous
The previous token in the unwrapped line.
FormatToken * Next
The next token in the unwrapped line.
Defines helper utilities for supporting the HLSL runtime environment.
static const Decl * getCanonicalDecl(const Decl *D)
static const GlobalDecl isTemplate(GlobalDecl GD, const TemplateArgumentList *&TemplateArgs)
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Architecture Architecture
Definition MachO.h:27
llvm::MachO::Record Record
Definition MachO.h:31
static bool isExternC(const NamedDecl *ND)
Definition Mangle.cpp:74
#define SM(sm)
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
Defines the clang::Preprocessor interface.
RedeclarationKind
Specifies whether (or how) name lookup is being performed for a redeclaration (vs.
@ NotForRedeclaration
The lookup is a reference to this name that is not for the purpose of redeclaring the name.
@ ForExternalRedeclaration
The lookup results will be used for redeclaration of a name with external linkage; non-visible lookup...
@ ForVisibleRedeclaration
The lookup results will be used for redeclaration of a name, if an entity by that name already exists...
llvm::SmallVector< std::pair< const MemRegion *, SVal >, 4 > Bindings
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis functions specific to ARM.
static bool hasAttr(const Decl *D, bool IgnoreImplicitAttr)
Definition SemaCUDA.cpp:187
This file declares semantic analysis for CUDA constructs.
static void diagnoseImplicitlyRetainedSelf(Sema &S)
static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D)
static UnqualifiedTypeNameLookupResult lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, SourceLocation NameLoc, const CXXRecordDecl *RD)
Tries to perform unqualified lookup of the type decls in bases for dependent class.
Definition SemaDecl.cpp:179
static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, const FunctionDecl *&PossiblePrototype)
static bool isMainVar(DeclarationName Name, VarDecl *VD)
static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD)
static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, const IdentifierInfo &II, SourceLocation NameLoc)
Definition SemaDecl.cpp:234
static void mergeParamDeclTypes(ParmVarDecl *NewParam, const ParmVarDecl *OldParam, Sema &S)
static void checkHybridPatchableAttr(Sema &S, NamedDecl &ND)
static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, DeclaratorDecl *OldD)
If necessary, adjust the semantic declaration context for a qualified declaration to name the correct...
static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken)
Determine whether the given result set contains either a type name or.
Definition SemaDecl.cpp:834
static void FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL)
static bool AllowOverloadingOfFunction(const LookupResult &Previous, ASTContext &Context, const FunctionDecl *New)
Determine whether overloading is allowed for a new function declaration considering prior declaration...
static TypeSourceInfo * TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, ASTContext &Context, bool &SizeIsNegative, llvm::APSInt &Oversized)
Helper method to turn variable array types into constant array types in certain situations which woul...
static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, ASTContext::GetBuiltinTypeError Error)
static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D)
static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, ExpectedDecl *New)
Check whether a redeclaration of an entity introduced by a using-declaration is valid,...
static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, const DeclContext *OldDC)
Determine what kind of declaration we're shadowing.
static void checkIsValidOpenCLKernelParameter(Sema &S, Declarator &D, ParmVarDecl *Param, llvm::SmallPtrSetImpl< const Type * > &ValidTypes)
static void mergeParamDeclAttributes(ParmVarDecl *newDecl, const ParmVarDecl *oldDecl, Sema &S)
mergeParamDeclAttributes - Copy attributes from the old parameter to the new one.
static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc, QualType T)
static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
Check the validity of a mulitversion function declaration.
static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old)
Merge alignment attributes from Old to New, taking into account the special semantics of C11's _Align...
static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, LookupResult &Previous)
static void CheckConstPureAttributesUsage(Sema &S, FunctionDecl *NewFD)
static bool FindPossiblePrototype(const FunctionDecl *FD, const FunctionDecl *&PossiblePrototype)
static bool MultiVersionTypesCompatible(FunctionDecl *Old, FunctionDecl *New)
static NestedNameSpecifier synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC)
Definition SemaDecl.cpp:598
static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, FixItHint &Hint)
static void CheckExplicitObjectParameter(Sema &S, ParmVarDecl *P, SourceLocation ExplicitThisLoc)
static void checkLifetimeBoundAttr(Sema &S, NamedDecl &ND)
static void patchDefaultTargetVersion(FunctionDecl *From, FunctionDecl *To)
static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD)
Given that we are within the definition of the given function, will that definition behave like C99's...
static void CheckForDuplicateEnumValues(Sema &S, ArrayRef< Decl * > Elements, EnumDecl *Enum, QualType EnumType)
static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS)
static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old)
checkNewAttributesAfterDef - If we already have a definition, check that there are no new attributes ...
static bool isClassCompatTagKind(TagTypeKind Tag)
Determine if tag kind is a class-key compatible with class for redeclaration (class,...
static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, const FunctionDecl *B)
static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND)
static bool hasSimilarParameters(ASTContext &Context, FunctionDecl *Declaration, FunctionDecl *Definition, SmallVectorImpl< unsigned > &Params)
hasSimilarParameters - Determine whether the C++ functions Declaration and Definition have "nearly" m...
static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD)
Determine whether a class is C-like, according to the rules of C++ [dcl.typedef] for anonymous classe...
static unsigned propagateAttribute(ParmVarDecl *To, const ParmVarDecl *From, Sema &S)
static FunctionDecl * CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, DeclContext *DC, QualType &R, TypeSourceInfo *TInfo, StorageClass SC, bool &IsVirtualOkay)
static Scope * getTagInjectionScope(Scope *S, const LangOptions &LangOpts)
Find the Scope in which a tag is implicitly declared if we see an elaborated type specifier in the sp...
static bool methodHasName(const FunctionDecl *FD, StringRef Name)
static std::pair< diag::kind, SourceLocation > getNoteDiagForInvalidRedeclaration(const T *Old, const T *New)
static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, LookupResult &Previous)
Apply special rules for handling extern "C" declarations.
static bool DeclHasAttr(const Decl *D, const Attr *A)
DeclhasAttr - returns true if decl Declaration already has the target attribute.
static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty)
static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, const ConstInitAttr *CIAttr, bool AttrBeforeInit)
static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, const LookupResult &R)
static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, SourceLocation NameLoc)
Add a minimal nested name specifier fixit hint to allow lookup of a tag name from an outer enclosing ...
static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S, DeclContext *Owner, DeclarationName Name, SourceLocation NameLoc, bool IsUnion, StorageClass SC)
We are trying to inject an anonymous member into the given scope; check if there's an existing declar...
static bool checkGlobalOrExternCConflict(Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous)
Check for conflict between this global or extern "C" declaration and previous global or extern "C" de...
static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts, const NamedDecl *D)
static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD, unsigned BuiltinID)
Determine whether a declaration matches a known function in namespace std.
static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, RecordDecl *AnonRecord, AccessSpecifier AS, StorageClass SC, SmallVectorImpl< NamedDecl * > &Chaining)
InjectAnonymousStructOrUnionMembers - Inject the members of the anonymous struct or union AnonRecord ...
OpenCLParamType
@ InvalidAddrSpacePtrKernelParam
@ ValidKernelParam
@ InvalidKernelParam
@ RecordKernelParam
@ PtrKernelParam
@ PtrPtrKernelParam
static bool isFromSystemHeader(SourceManager &SM, const Decl *D)
Returns true if the declaration is declared in a system header or from a system macro.
static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, const ValueDecl *VD)
Return the location of the capture if the given lambda captures the given variable VD,...
static bool AreSpecialMemberFunctionsSameKind(ASTContext &Context, CXXMethodDecl *M1, CXXMethodDecl *M2, CXXSpecialMemberKind CSM)
[class.mem.special]p5 Two special member functions are of the same kind if:
static const CXXRecordDecl * findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC)
Find the parent class with dependent bases of the innermost enclosing method context.
Definition SemaDecl.cpp:617
static void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record)
[class.dtor]p4: At the end of the definition of a class, overload resolution is performed among the p...
static bool shouldConsiderLinkage(const VarDecl *VD)
static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record)
static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, const FunctionDecl *NewFD, bool CausesMV, MultiVersionKind MVKind)
static DeclContext * getTagInjectionContext(DeclContext *DC)
Find the DeclContext in which a tag is implicitly declared if we see an elaborated type specifier in ...
static bool EquivalentArrayTypes(QualType Old, QualType New, const ASTContext &Ctx)
static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New)
static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag)
Get diagnostic select index for tag kind for redeclaration diagnostic message.
static void checkInheritableAttr(Sema &S, NamedDecl &ND)
static void CheckPoppedLabel(LabelDecl *L, Sema &S, Sema::DiagReceiverTy DiagReceiver)
static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl *Old)
static NamedDecl * DiagnoseInvalidRedeclaration(Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S)
Generate diagnostics for an invalid function redeclaration.
static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, DeclarationName Name)
RebuildDeclaratorInCurrentInstantiation - Checks whether the given declarator needs to be rebuilt in ...
static void SetEligibleMethods(Sema &S, CXXRecordDecl *Record, ArrayRef< CXXMethodDecl * > Methods, CXXSpecialMemberKind CSM)
[class.mem.special]p6: An eligible special member function is a special member function for which:
static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc)
Definition SemaDecl.cpp:849
static bool hasParsedAttr(Scope *S, const Declarator &PD, ParsedAttr::Kind Kind)
ShadowedDeclKind
Enum describing the select options in diag::warn_decl_shadow.
@ SDK_StructuredBinding
@ SDK_Field
@ SDK_Global
@ SDK_Local
@ SDK_Typedef
@ SDK_StaticMember
@ SDK_Using
static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S)
static void CheckForComparisonInEnumInitializer(SemaBase &Sema, const EnumDecl *Enum)
static void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD)
static bool canRedefineFunction(const FunctionDecl *FD, const LangOptions &LangOpts)
canRedefineFunction - checks if a function can be redefined.
static void checkWeakAttr(Sema &S, NamedDecl &ND)
static void checkModularFormatAttr(Sema &S, NamedDecl &ND)
static void checkSelectAnyAttr(Sema &S, NamedDecl &ND)
static bool isImplicitInstantiation(NamedDecl *D)
static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT)
static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, SourceLocation DefaultInitLoc)
static bool isDefaultStdCall(FunctionDecl *FD, Sema &S)
static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD)
Returns true if there hasn't been any invalid type diagnosed.
static void RemoveUsingDecls(LookupResult &R)
Removes using shadow declarations not at class scope from the lookup results.
static void ComputeSpecialMemberFunctionsEligiblity(Sema &S, CXXRecordDecl *Record)
static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, MultiVersionKind MVKind)
static bool looksMutable(QualType T, const ASTContext &Ctx)
static bool isUsingDeclNotAtClassScope(NamedDecl *D)
static void propagateAttributes(ParmVarDecl *To, const ParmVarDecl *From, F &&propagator)
static const NamedDecl * getDefinition(const Decl *D)
static QualType TryToFixInvalidVariablyModifiedType(QualType T, ASTContext &Context, bool &SizeIsNegative, llvm::APSInt &Oversized)
Helper method to turn variable array types into constant array types in certain situations which woul...
static bool hasDeducedAuto(DeclaratorDecl *DD)
static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT)
static QualType getCoreType(QualType Ty)
static bool isMainFileLoc(const Sema &S, SourceLocation Loc)
static bool mergeDeclAttribute(Sema &S, NamedDecl *D, const InheritableAttr *Attr, AvailabilityMergeKind AMK)
static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD)
Check the target or target_version attribute of the function for MultiVersion validity.
static bool isOutOfScopePreviousDeclaration(NamedDecl *, DeclContext *, ASTContext &)
Determines whether the given declaration is an out-of-scope previous declaration.
static StorageClass StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS)
StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to a VarDecl::StorageClass.
static bool CheckMultiVersionAdditionalDecl(Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
Check the validity of a new function declaration being added to an existing multiversioned declaratio...
static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD)
Check the validity of a multiversion function declaration that is the first of its kind.
static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, NamedDecl *NewDecl, bool IsSpecialization, bool IsDefinition)
static bool checkNonMultiVersionCompatAttributes(Sema &S, const FunctionDecl *FD, const FunctionDecl *CausedFD, MultiVersionKind MVKind)
static void checkAliasAttr(Sema &S, NamedDecl &ND)
static void filterNonConflictingPreviousTypedefDecls(Sema &S, const TypedefNameDecl *Decl, LookupResult &Previous)
Typedef declarations don't have linkage, but they still denote the same entity if their types are the...
static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum)
static QualType getNextLargerIntegralType(ASTContext &Context, QualType T)
static void checkWeakRefAttr(Sema &S, NamedDecl &ND)
static bool isIncompleteDeclExternC(Sema &S, const T *D)
Determine whether a variable is extern "C" prior to attaching an initializer.
static bool isAttributeTargetADefinition(Decl *D)
static Attr * getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD)
Return a CodeSegAttr from a containing class.
static bool CheckDeclarationCausesMultiVersioning(Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D)
Check for this common pattern:
static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, DeclContext *NewDC)
Determine whether a tag originally declared in context OldDC can be redeclared with an unqualified na...
static bool isRecordType(QualType T)
This file declares semantic analysis for HLSL constructs.
This file declares semantic analysis for Objective-C.
This file declares semantic analysis for OpenACC constructs and clauses.
This file declares semantic analysis for OpenMP constructs and clauses.
This file declares semantic analysis functions specific to PowerPC.
This file declares semantic analysis functions specific to RISC-V.
This file declares semantic analysis for SYCL constructs.
This file declares semantic analysis functions specific to Swift.
This file declares semantic analysis functions specific to Wasm.
static CharSourceRange getRange(const CharSourceRange &EditRange, const SourceManager &SM, const LangOptions &LangOpts, bool IncludeMacroExpansion)
Defines the SourceManager interface.
static QualType getPointeeType(const MemRegion *R)
C Language Family Type Representation.
@ GE_None
No error.
@ GE_Missing_stdio
Missing a type from <stdio.h>
@ GE_Missing_type
Missing a type.
@ GE_Missing_ucontext
Missing a type from <ucontext.h>
@ GE_Missing_setjmp
Missing a type from <setjmp.h>
RAII object that pops an ExpressionEvaluationContext when exiting a function body.
ExitFunctionBodyRAII(Sema &S, bool IsLambda)
llvm::APInt getValue() const
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
virtual void AssignInheritanceModel(CXXRecordDecl *RD)
Callback invoked when an MSInheritanceAttr has been attached to a CXXRecordDecl.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:220
SourceManager & getSourceManager()
Definition ASTContext.h:851
TranslationUnitDecl * getTranslationUnitDecl() const
const ConstantArrayType * getAsConstantArrayType(QualType T) const
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType, const Attr *attr=nullptr) const
IdentifierTable & Idents
Definition ASTContext.h:790
const LangOptions & getLangOpts() const
Definition ASTContext.h:944
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
const VariableArrayType * getAsVariableArrayType(QualType T) const
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:909
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
CanQualType getCanonicalTagType(const TagDecl *TD) const
@ GE_Missing_type
Missing a type.
@ GE_Missing_setjmp
Missing a type from <setjmp.h>
unsigned getTypeAlign(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in bits.
bool isUnset() const
Definition Ownership.h:168
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
Represents a type which was implicitly adjusted by the semantic engine for arbitrary reasons.
Definition TypeBase.h:3490
Wrapper for source info for arrays.
Definition TypeLoc.h:1748
SourceLocation getLBracketLoc() const
Definition TypeLoc.h:1750
Expr * getSizeExpr() const
Definition TypeLoc.h:1770
TypeLoc getElementLoc() const
Definition TypeLoc.h:1778
SourceLocation getRBracketLoc() const
Definition TypeLoc.h:1758
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3723
QualType getElementType() const
Definition TypeBase.h:3735
Attr - This represents one attribute.
Definition Attr.h:46
attr::Kind getKind() const
Definition Attr.h:92
bool isInherited() const
Definition Attr.h:101
Attr * clone(ASTContext &C) const
void setImplicit(bool I)
Definition Attr.h:106
SourceLocation getLocation() const
Definition Attr.h:99
bool isStandardAttributeSyntax() const
The attribute is spelled [[]] in either C or C++ mode, including standard attributes spelled with a k...
A factory, from which one makes pools, from which one creates individual attributes which are dealloc...
Definition ParsedAttr.h:622
AttributeFactory & getFactory() const
Definition ParsedAttr.h:718
Type source information for an attributed type.
Definition TypeLoc.h:1008
TypeLoc getModifiedLoc() const
The modified type, which is generally canonically different from the attribute type.
Definition TypeLoc.h:1022
void setAttr(const Attr *A)
Definition TypeLoc.h:1034
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression which will be evaluated if the condition evaluates to false; ...
Definition Expr.h:4507
Expr * getCond() const
getCond - Return the condition expression; this is defined in terms of the opaque value.
Definition Expr.h:4495
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4038
Expr * getLHS() const
Definition Expr.h:4088
StringRef getOpcodeStr() const
Definition Expr.h:4104
Expr * getRHS() const
Definition Expr.h:4090
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4179
A binding in a decomposition declaration.
Definition DeclCXX.h:4181
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4671
bool doesNotEscape() const
Definition Decl.h:4822
This class is used for builtin types like 'int'.
Definition TypeBase.h:3165
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
Definition Builtins.h:235
const char * getHeaderName(unsigned ID) const
If this is a library function that comes from a specific header, retrieve that header name.
Definition Builtins.h:382
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
Represents a base class of a C++ class.
Definition DeclCXX.h:146
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclCXX.h:194
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclCXX.h:195
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1691
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1611
Represents a C++ constructor within a class.
Definition DeclCXX.h:2604
bool isCopyConstructor(unsigned &TypeQuals) const
Whether this constructor is a copy constructor (C++ [class.copy]p2, which can be used to copy the cla...
Definition DeclCXX.cpp:3008
static CXXConstructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, ExplicitSpecifier ES, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, InheritedConstructor Inherited=InheritedConstructor(), const AssociatedConstraint &TrailingRequiresClause={})
Definition DeclCXX.cpp:2968
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2939
static CXXConversionDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline, ExplicitSpecifier ES, ConstexprSpecKind ConstexprKind, SourceLocation EndLocation, const AssociatedConstraint &TrailingRequiresClause={})
Definition DeclCXX.cpp:3223
static CXXDeductionGuideDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, ExplicitSpecifier ES, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, SourceLocation EndLocation, CXXConstructorDecl *Ctor=nullptr, DeductionCandidate Kind=DeductionCandidate::Normal, const AssociatedConstraint &TrailingRequiresClause={}, const CXXDeductionGuideDecl *SourceDG=nullptr, SourceDeductionGuideKind SK=SourceDeductionGuideKind::None)
Definition DeclCXX.cpp:2367
Represents a C++ destructor within a class.
Definition DeclCXX.h:2869
static CXXDestructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, const AssociatedConstraint &TrailingRequiresClause={})
Definition DeclCXX.cpp:3098
A mapping from each virtual member function to its set of final overriders.
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2129
bool isExplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An explicit object member function is a non-static member function with an explic...
Definition DeclCXX.cpp:2703
void addOverriddenMethod(const CXXMethodDecl *MD)
Definition DeclCXX.cpp:2755
bool isVirtual() const
Definition DeclCXX.h:2184
static CXXMethodDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin, bool isInline, ConstexprSpecKind ConstexprKind, SourceLocation EndLocation, const AssociatedConstraint &TrailingRequiresClause={})
Definition DeclCXX.cpp:2488
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition DeclCXX.cpp:2820
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2255
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition DeclCXX.cpp:2735
Qualifiers getMethodQualifiers() const
Definition DeclCXX.h:2290
bool isConst() const
Definition DeclCXX.h:2181
bool isStatic() const
Definition DeclCXX.cpp:2401
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition DeclCXX.cpp:2714
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2225
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr)
Definition DeclCXX.cpp:132
base_class_iterator bases_end()
Definition DeclCXX.h:617
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition DeclCXX.h:1366
const FunctionDecl * isLocalClass() const
If the class is a local class [class.local], returns the enclosing function declaration.
Definition DeclCXX.h:1554
base_class_range bases()
Definition DeclCXX.h:608
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition DeclCXX.h:602
bool lookupInBases(BaseMatchesCallback BaseMatches, CXXBasePaths &Paths, bool LookupInDependent=false) const
Look for entities within the base classes of this C++ class, transitively searching all base class su...
base_class_iterator bases_begin()
Definition DeclCXX.h:615
capture_const_range captures() const
Definition DeclCXX.h:1097
bool hasInClassInitializer() const
Whether this class has any in-class initializers for non-static data members (including those in anon...
Definition DeclCXX.h:1148
bool hasDefinition() const
Definition DeclCXX.h:561
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition DeclCXX.cpp:2042
bool isInjectedClassName() const
Determines whether this declaration represents the injected class name.
Definition DeclCXX.cpp:2146
LambdaCaptureDefault getLambdaCaptureDefault() const
Definition DeclCXX.h:1059
UnresolvedSetIterator conversion_iterator
Definition DeclCXX.h:1119
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition DeclCXX.cpp:2046
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:522
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:73
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition DeclSpec.h:180
char * location_data() const
Retrieve the data associated with the source-location information.
Definition DeclSpec.h:206
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:185
void MakeTrivial(ASTContext &Context, NestedNameSpecifier Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition DeclSpec.cpp:97
SourceRange getRange() const
Definition DeclSpec.h:79
SourceLocation getBeginLoc() const
Definition DeclSpec.h:83
bool isSet() const
Deprecated.
Definition DeclSpec.h:198
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition DeclSpec.h:94
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition DeclSpec.cpp:123
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition DeclSpec.h:183
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:178
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition DeclSpec.cpp:103
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3147
bool isCallToStdMove() const
Definition Expr.cpp:3623
Expr * getCallee()
Definition Expr.h:3090
arg_range arguments()
Definition Expr.h:3195
CastKind getCastKind() const
Definition Expr.h:3720
Expr * getSubExpr()
Definition Expr.h:3726
static CharSourceRange getCharRange(SourceRange R)
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
Declaration of a class template.
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3761
static unsigned getNumAddressingBits(const ASTContext &Context, QualType ElementType, const llvm::APInt &NumElements)
Determine the number of bits required to address a member of.
Definition Type.cpp:215
static unsigned getMaxSizeBits(const ASTContext &Context)
Determine the maximum number of active bits that an array's size can require, which limits the maximu...
Definition Type.cpp:255
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3817
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:349
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:47
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
DeclListNode::iterator iterator
Definition DeclBase.h:1392
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2238
bool isFileContext() const
Definition DeclBase.h:2180
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
DeclContextLookupResult lookup_result
Definition DeclBase.h:2577
bool isTransparentContext() const
isTransparentContext - Determines whether this context is a "transparent" context,...
Decl * getNonClosureAncestor()
Find the nearest non-closure ancestor of this context, i.e.
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
bool isClosure() const
Definition DeclBase.h:2142
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition DeclBase.h:2125
bool isNamespace() const
Definition DeclBase.h:2198
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
const BlockDecl * getInnermostBlockDecl() const
Return this DeclContext if it is a BlockDecl.
bool isTranslationUnit() const
Definition DeclBase.h:2185
bool isRecord() const
Definition DeclBase.h:2189
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
void removeDecl(Decl *D)
Removes a declaration from this context.
void addDecl(Decl *D)
Add the declaration D into this context.
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2373
bool isFunctionOrMethod() const
Definition DeclBase.h:2161
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
bool isExternCContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context semantically encloses the declaration context DC.
Decl::Kind getDeclKind() const
Definition DeclBase.h:2102
DeclContext * getNonTransparentContext()
Simple template class for restricting typo correction candidates to ones having a single Decl* of the...
static DeclGroupRef Create(ASTContext &C, Decl **Decls, unsigned NumDecls)
Definition DeclGroup.h:64
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1270
ValueDecl * getDecl()
Definition Expr.h:1338
SourceLocation getBeginLoc() const
Definition Expr.h:1349
Captures information about "declaration specifiers".
Definition DeclSpec.h:217
bool isVirtualSpecified() const
Definition DeclSpec.h:618
bool isModulePrivateSpecified() const
Definition DeclSpec.h:799
static const TST TST_typeof_unqualType
Definition DeclSpec.h:279
bool hasAutoTypeSpec() const
Definition DeclSpec.h:565
static const TST TST_typename
Definition DeclSpec.h:276
bool SetStorageClassSpec(Sema &S, SCS SC, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
These methods set the specified attribute of the DeclSpec and return false if there was no error.
Definition DeclSpec.cpp:619
ThreadStorageClassSpecifier TSCS
Definition DeclSpec.h:234
void ClearStorageClassSpecs()
Definition DeclSpec.h:485
bool isNoreturnSpecified() const
Definition DeclSpec.h:631
TST getTypeSpecType() const
Definition DeclSpec.h:507
SourceLocation getStorageClassSpecLoc() const
Definition DeclSpec.h:480
SCS getStorageClassSpec() const
Definition DeclSpec.h:471
bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition DeclSpec.cpp:834
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:545
SourceRange getSourceRange() const LLVM_READONLY
Definition DeclSpec.h:544
void SetRangeEnd(SourceLocation Loc)
Definition DeclSpec.h:679
static const TST TST_interface
Definition DeclSpec.h:274
static const TST TST_typeofExpr
Definition DeclSpec.h:278
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition DeclSpec.h:586
void SetRangeStart(SourceLocation Loc)
Definition DeclSpec.h:678
SourceLocation getNoreturnSpecLoc() const
Definition DeclSpec.h:632
bool isExternInLinkageSpec() const
Definition DeclSpec.h:475
static const TST TST_union
Definition DeclSpec.h:272
SCS
storage-class-specifier
Definition DeclSpec.h:221
SourceLocation getExplicitSpecLoc() const
Definition DeclSpec.h:624
static const TST TST_int
Definition DeclSpec.h:255
SourceLocation getModulePrivateSpecLoc() const
Definition DeclSpec.h:800
bool isMissingDeclaratorOk()
Checks if this DeclSpec can stand alone, without a Declarator.
ParsedType getRepAsType() const
Definition DeclSpec.h:517
void UpdateTypeRep(ParsedType Rep)
Definition DeclSpec.h:758
TSCS getThreadStorageClassSpec() const
Definition DeclSpec.h:472
ParsedAttributes & getAttributes()
Definition DeclSpec.h:843
void ClearTypeQualifiers()
Clear out all of the type qualifiers.
Definition DeclSpec.h:596
SourceLocation getConstSpecLoc() const
Definition DeclSpec.h:587
SourceRange getExplicitSpecRange() const
Definition DeclSpec.h:625
Expr * getRepAsExpr() const
Definition DeclSpec.h:525
static const TST TST_enum
Definition DeclSpec.h:271
static const TST TST_decltype
Definition DeclSpec.h:281
static bool isDeclRep(TST T)
Definition DeclSpec.h:439
bool isInlineSpecified() const
Definition DeclSpec.h:607
SourceLocation getRestrictSpecLoc() const
Definition DeclSpec.h:588
static const TST TST_typeof_unqualExpr
Definition DeclSpec.h:280
static const TST TST_class
Definition DeclSpec.h:275
TypeSpecifierType TST
Definition DeclSpec.h:247
static const TST TST_void
Definition DeclSpec.h:249
void ClearConstexprSpec()
Definition DeclSpec.h:811
static const char * getSpecifierName(DeclSpec::TST T, const PrintingPolicy &Policy)
Turn a type-specifier-type into a string like "_Bool" or "union".
Definition DeclSpec.cpp:532
static const TST TST_atomic
Definition DeclSpec.h:291
SourceLocation getThreadStorageClassSpecLoc() const
Definition DeclSpec.h:481
Decl * getRepAsDecl() const
Definition DeclSpec.h:521
static const TST TST_unspecified
Definition DeclSpec.h:248
SourceLocation getAtomicSpecLoc() const
Definition DeclSpec.h:590
SourceLocation getVirtualSpecLoc() const
Definition DeclSpec.h:619
SourceLocation getConstexprSpecLoc() const
Definition DeclSpec.h:806
SourceLocation getTypeSpecTypeLoc() const
Definition DeclSpec.h:552
void UpdateExprRep(Expr *Rep)
Definition DeclSpec.h:762
static const TSCS TSCS_thread_local
Definition DeclSpec.h:237
static const TST TST_error
Definition DeclSpec.h:298
ExplicitSpecifier getExplicitSpecifier() const
Definition DeclSpec.h:614
bool isTypeSpecOwned() const
Definition DeclSpec.h:511
SourceLocation getInlineSpecLoc() const
Definition DeclSpec.h:610
SourceLocation getUnalignedSpecLoc() const
Definition DeclSpec.h:591
SourceLocation getVolatileSpecLoc() const
Definition DeclSpec.h:589
FriendSpecified isFriendSpecified() const
Definition DeclSpec.h:791
bool hasExplicitSpecifier() const
Definition DeclSpec.h:621
bool hasConstexprSpecifier() const
Definition DeclSpec.h:807
static const TST TST_typeofType
Definition DeclSpec.h:277
static const TST TST_auto
Definition DeclSpec.h:288
ConstexprSpecKind getConstexprSpecifier() const
Definition DeclSpec.h:802
static const TST TST_struct
Definition DeclSpec.h:273
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition DeclBase.h:1061
Decl * getMostRecentDecl()
Retrieve the most recent declaration that declares the same entity as this declaration (which may be ...
Definition DeclBase.h:1076
const DeclContext * getParentFunctionOrMethod(bool LexicalParent=false) const
If this decl is defined inside a function/method/block it returns the corresponding DeclContext,...
Definition DeclBase.cpp:341
bool isInStdNamespace() const
Definition DeclBase.cpp:449
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclBase.h:435
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition DeclBase.h:1226
bool isFromGlobalModule() const
Whether this declaration comes from global module.
T * getAttr() const
Definition DeclBase.h:573
bool hasAttrs() const
Definition DeclBase.h:518
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:546
void addAttr(Attr *A)
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:593
void setAttrs(const AttrVec &Attrs)
Definition DeclBase.h:520
bool isUnavailable(std::string *Message=nullptr) const
Determine whether this declaration is marked 'unavailable'.
Definition DeclBase.h:771
bool isInNamedModule() const
Whether this declaration comes from a named module.
void setLocalExternDecl()
Changes the namespace of this declaration to reflect that it's a function-local extern declaration.
Definition DeclBase.h:1151
virtual bool isOutOfLine() const
Determine whether this declaration is declared out of line (outside its semantic context).
Definition Decl.cpp:99
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition DeclBase.cpp:178
void setTopLevelDeclInObjCContainer(bool V=true)
Definition DeclBase.h:638
bool isInIdentifierNamespace(unsigned NS) const
Definition DeclBase.h:893
@ FOK_Undeclared
A friend of a previously-undeclared entity.
Definition DeclBase.h:1219
@ FOK_None
Not a friend object.
Definition DeclBase.h:1217
@ FOK_Declared
A friend of a previously-declared entity.
Definition DeclBase.h:1218
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition DeclBase.cpp:308
bool isInExportDeclContext() const
Whether this declaration was exported in a lexical context.
bool isReferenced() const
Whether any declaration of this entity was referenced.
Definition DeclBase.cpp:600
bool isInAnotherModuleUnit() const
Whether this declaration comes from another module unit.
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:842
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:273
void dropAttrs()
@ OBJC_TQ_CSNullability
The nullability qualifier is set when the nullability of the result or parameter was expressed via a ...
Definition DeclBase.h:210
void setObjectOfFriendDecl(bool PerformFriendInjection=false)
Changes the namespace of this declaration to reflect that it's the object of a friend declaration.
Definition DeclBase.h:1180
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition DeclBase.h:2793
bool isInvalidDecl() const
Definition DeclBase.h:588
bool isLocalExternDecl() const
Determine whether this is a block-scope declaration with linkage.
Definition DeclBase.h:1169
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:559
void setAccess(AccessSpecifier AS)
Definition DeclBase.h:502
SourceLocation getLocation() const
Definition DeclBase.h:439
@ IDNS_Ordinary
Ordinary names.
Definition DeclBase.h:144
void setImplicit(bool I=true)
Definition DeclBase.h:594
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition DeclBase.cpp:575
DeclContext * getDeclContext()
Definition DeclBase.h:448
attr_range attrs() const
Definition DeclBase.h:535
AccessSpecifier getAccess() const
Definition DeclBase.h:507
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:431
void dropAttr()
Definition DeclBase.h:556
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition DeclBase.cpp:382
Module * getOwningModuleForLinkage() const
Get the module that owns this declaration for linkage purposes.
Definition Decl.cpp:1636
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:918
bool hasAttr() const
Definition DeclBase.h:577
void setNonMemberOperator()
Specifies that this declaration is a C++ overloaded non-member.
Definition DeclBase.h:1235
void setLexicalDeclContext(DeclContext *DC)
Definition DeclBase.cpp:386
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:978
Kind getKind() const
Definition DeclBase.h:442
The name of a declaration.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
bool isAnyOperatorNewOrDelete() const
bool isAnyOperatorDelete() const
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
QualType getCXXNameType() const
If this name is one of the C++ names (of a constructor, destructor, or conversion function),...
NameKind getNameKind() const
Determine what kind of name this is.
bool isEmpty() const
Evaluates true when this declaration name is empty.
bool isIdentifier() const
Predicate functions for querying what type of name this is.
Represents a ValueDecl that came out of a declarator.
Definition Decl.h:780
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition Decl.h:822
SourceLocation getOuterLocStart() const
Return start of source range taking into account any outer template declarations.
Definition Decl.cpp:2061
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2101
SourceLocation getTypeSpecStartLoc() const
Definition Decl.cpp:1999
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:831
const AssociatedConstraint & getTrailingRequiresClause() const
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition Decl.h:855
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition Decl.h:814
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition Decl.cpp:2011
NestedNameSpecifier getQualifier() const
Retrieve the nested-name-specifier that qualifies the name of this declaration, if it was present in ...
Definition Decl.h:837
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:809
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition Decl.cpp:2045
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1874
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition DeclSpec.h:2430
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition DeclSpec.h:2372
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2021
Expr * getAsmLabel() const
Definition DeclSpec.h:2676
FunctionDefinitionKind getFunctionDefinitionKind() const
Definition DeclSpec.h:2715
const ParsedAttributes & getAttributes() const
Definition DeclSpec.h:2657
void setRedeclaration(bool Val)
Definition DeclSpec.h:2738
SourceLocation getIdentifierLoc() const
Definition DeclSpec.h:2310
void SetIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Set the name of this declarator to be the given identifier.
Definition DeclSpec.h:2313
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclSpec.h:2058
Expr * getTrailingRequiresClause()
Sets a trailing requires clause for this declarator.
Definition DeclSpec.h:2607
void takeAttributesAppending(ParsedAttributes &attrs)
takeAttributesAppending - Takes attributes from the given ParsedAttributes set and add them to this d...
Definition DeclSpec.h:2650
void setInvalidType(bool Val=true)
Definition DeclSpec.h:2687
TemplateParameterList * getInventedTemplateParameterList() const
The template parameter list generated from the explicit template parameters along with any invented t...
Definition DeclSpec.h:2637
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition DeclSpec.h:2368
bool isRedeclaration() const
Definition DeclSpec.h:2739
const ParsedAttributesView & getDeclarationAttributes() const
Definition DeclSpec.h:2660
const DecompositionDeclarator & getDecompositionDeclarator() const
Definition DeclSpec.h:2042
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2057
bool isCtorOrDtor()
Returns true if this declares a constructor or a destructor.
Definition DeclSpec.cpp:410
bool isFunctionDefinition() const
Definition DeclSpec.h:2711
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition DeclSpec.h:2040
bool hasInitializer() const
Definition DeclSpec.h:2720
void setFunctionDefinitionKind(FunctionDefinitionKind Val)
Definition DeclSpec.h:2707
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition DeclSpec.h:2036
void AddTypeInfo(const DeclaratorChunk &TI, ParsedAttributes &&attrs, SourceLocation EndLoc)
AddTypeInfo - Add a chunk to this declarator.
Definition DeclSpec.h:2327
bool isInvalidType() const
Definition DeclSpec.h:2688
bool isExplicitObjectMemberFunction()
Definition DeclSpec.cpp:398
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition DeclSpec.h:2056
bool isDecompositionDeclarator() const
Return whether this declarator is a decomposition declarator.
Definition DeclSpec.h:2300
bool isFirstDeclarationOfMember()
Returns true if this declares a real member and not a friend.
Definition DeclSpec.h:2723
bool isStaticMember()
Returns true if this declares a static member.
Definition DeclSpec.cpp:389
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition DeclSpec.h:2028
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition DeclSpec.h:2461
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2304
A decomposition declaration.
Definition DeclCXX.h:4245
static DecompositionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation LSquareLoc, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< BindingDecl * > Bindings)
Definition DeclCXX.cpp:3682
A parsed C++17 decomposition declarator of the form '[' identifier-list ']'.
Definition DeclSpec.h:1762
SourceRange getSourceRange() const
Definition DeclSpec.h:1810
SourceLocation getLSquareLoc() const
Definition DeclSpec.h:1808
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2484
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2572
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2552
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:2561
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:232
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:951
An instance of this object exists for each enum constant that is defined.
Definition Decl.h:3423
llvm::APSInt getInitVal() const
Definition Decl.h:3443
static EnumConstantDecl * Create(ASTContext &C, EnumDecl *DC, SourceLocation L, IdentifierInfo *Id, QualType T, Expr *E, const llvm::APSInt &V)
Definition Decl.cpp:5706
const Expr * getInitExpr() const
Definition Decl.h:3441
Represents an enum.
Definition Decl.h:4010
enumerator_range enumerators() const
Definition Decl.h:4156
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition Decl.h:4228
void setIntegerType(QualType T)
Set the underlying integer type.
Definition Decl.h:4192
void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo)
Set the underlying integer type source info.
Definition Decl.h:4195
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4242
static EnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, bool IsScoped, bool IsScopedUsingClassTag, bool IsFixed)
Definition Decl.cpp:5069
bool isClosedFlag() const
Returns true if this enum is annotated with flag_enum and isn't annotated with enum_extensibility(ope...
Definition Decl.cpp:5108
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition Decl.h:4237
SourceRange getIntegerTypeRange() const LLVM_READONLY
Retrieve the source range that covers the underlying type if specified.
Definition Decl.cpp:5083
void setPromotionType(QualType T)
Set the promotion type.
Definition Decl.h:4178
void setEnumKeyRange(SourceRange Range)
Definition Decl.h:4090
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4183
EvaluatedExprVisitor - This class visits 'Expr *'s.
Store information needed for an explicit specifier.
Definition DeclCXX.h:1924
This represents one expression.
Definition Expr.h:112
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3089
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:246
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3085
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3069
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:276
QualType getType() const
Definition Expr.h:144
Represents difference between two FPOptions values.
bool isFPConstrained() const
Represents a member of a struct/union/class.
Definition Decl.h:3160
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3263
bool isAnonymousStructOrUnion() const
Determines whether this field is a representative for an anonymous struct or union.
Definition Decl.cpp:4715
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3396
static FieldDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
Definition Decl.cpp:4700
bool isZeroLengthBitField() const
Is this a zero-length bit-field?
Definition Decl.cpp:4761
static FileScopeAsmDecl * Create(ASTContext &C, DeclContext *DC, Expr *Str, SourceLocation AsmLoc, SourceLocation RParenLoc)
Definition Decl.cpp:5839
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:79
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:140
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:129
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:103
Represents a function declaration or definition.
Definition Decl.h:2000
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2689
static FunctionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation NLoc, DeclarationName N, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin=false, bool isInlineSpecified=false, bool hasWrittenPrototype=true, ConstexprSpecKind ConstexprKind=ConstexprSpecKind::Unspecified, const AssociatedConstraint &TrailingRequiresClause={})
Definition Decl.h:2189
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2797
ConstexprSpecKind getConstexprKind() const
Definition Decl.h:2476
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4205
void setPreviousDeclaration(FunctionDecl *PrevDecl)
Definition Decl.cpp:3733
void setDescribedFunctionTemplate(FunctionTemplateDecl *Template)
Definition Decl.cpp:4198
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4193
void setIsPureVirtual(bool P=true)
Definition Decl.cpp:3298
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition Decl.h:2314
void setFriendConstraintRefersToEnclosingTemplate(bool V=true)
Definition Decl.h:2701
void setHasSkippedBody(bool Skipped=true)
Definition Decl.h:2680
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition Decl.cpp:4024
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3762
param_iterator param_end()
Definition Decl.h:2787
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:2921
void setIsMultiVersion(bool V=true)
Sets the multiversion state for this declaration and all of its redeclarations.
Definition Decl.h:2695
QualType getReturnType() const
Definition Decl.h:2845
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2774
bool isCPUSpecificMultiVersion() const
True if this function is a multiversioned processor specific function as a part of the cpu_specific/c...
Definition Decl.cpp:3706
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted.
Definition Decl.h:2389
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2377
LanguageLinkage getLanguageLinkage() const
Compute the language linkage.
Definition Decl.cpp:3614
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4313
bool hasWrittenPrototype() const
Whether this function has a written prototype.
Definition Decl.h:2448
void setWillHaveBody(bool V=true)
Definition Decl.h:2686
bool isReplaceableGlobalAllocationFunction(UnsignedOrNone *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions: void *operato...
Definition Decl.h:2594
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition Decl.h:2443
FunctionTemplateSpecializationInfo * getTemplateSpecializationInfo() const
If this function is actually a function template specialization, retrieve information about this func...
Definition Decl.cpp:4323
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3747
param_iterator param_begin()
Definition Decl.h:2786
const ParmVarDecl * getNonObjectParameter(unsigned I) const
Definition Decl.h:2823
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition Decl.h:2326
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2540
FunctionEffectsRef getFunctionEffects() const
Definition Decl.h:3134
bool isMSVCRTEntryPoint() const
Determines whether this function is a MSVCRT user defined entry point.
Definition Decl.cpp:3375
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition Decl.cpp:4257
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:2888
bool isStatic() const
Definition Decl.h:2929
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a member function.
Definition Decl.cpp:4526
void setTrivial(bool IT)
Definition Decl.h:2378
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4144
bool isFirstDecl() const
True if this is the first declaration in its redeclaration chain.
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2470
bool isDeletedAsWritten() const
Definition Decl.h:2544
redecl_iterator redecls_end() const
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition Decl.h:2353
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition Decl.cpp:3618
bool isLateTemplateParsed() const
Whether this templated function will be late parsed.
Definition Decl.h:2357
FunctionDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
bool hasImplicitReturnZero() const
Whether falling off this function implicitly returns null/zero.
Definition Decl.h:2428
void setVirtualAsWritten(bool V)
State that this function is marked as virtual explicitly.
Definition Decl.h:2349
bool hasSkippedBody() const
True if the function was a definition but its body was skipped.
Definition Decl.h:2679
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition Decl.h:2282
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition Decl.cpp:3368
void setImplicitlyInline(bool I=true)
Flag that this function is implicitly inline.
Definition Decl.h:2916
bool param_empty() const
Definition Decl.h:2785
bool isThisDeclarationInstantiatedFromAFriendDefinition() const
Determine whether this specific declaration of the function is a friend declaration that was instanti...
Definition Decl.cpp:3223
void setRangeEnd(SourceLocation E)
Definition Decl.h:2218
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
Definition Decl.cpp:3702
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2385
void setIneligibleOrNotSelected(bool II)
Definition Decl.h:2421
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:4549
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition Decl.h:2933
const IdentifierInfo * getLiteralIdentifier() const
getLiteralIdentifier - The literal suffix identifier this function represents, if any.
Definition Decl.cpp:4138
void setConstexprKind(ConstexprSpecKind CSK)
Definition Decl.h:2473
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4417
void setDefaulted(bool D=true)
Definition Decl.h:2386
bool isConsteval() const
Definition Decl.h:2482
QualType getDeclaredReturnType() const
Get the declared return type, which may differ from the actual return type if the return type is dedu...
Definition Decl.h:2862
void setBody(Stmt *B)
Definition Decl.cpp:3291
bool isGlobal() const
Determines whether this is a global function.
Definition Decl.cpp:3632
void setDeletedAsWritten(bool D=true, StringLiteral *Message=nullptr)
Definition Decl.cpp:3169
bool hasInheritedPrototype() const
Whether this function inherited its prototype from a previous declaration.
Definition Decl.h:2459
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4165
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3826
DeclarationNameInfo getNameInfo() const
Definition Decl.h:2211
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3199
void setHasImplicitReturnZero(bool IRZ)
State that falling off this function implicitly returns null/zero.
Definition Decl.h:2435
bool isDefined(const FunctionDecl *&Definition, bool CheckForPendingFriendDefinition=false) const
Returns true if the function has a definition that does not need to be instantiated.
Definition Decl.cpp:3246
FunctionDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
bool isInlineSpecified() const
Determine whether the "inline" keyword was specified for this function.
Definition Decl.h:2899
MultiVersionKind getMultiVersionKind() const
Gets the kind of multiversioning attribute this declaration has.
Definition Decl.cpp:3688
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition Decl.h:2685
A mutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5205
SmallVector< Conflict > Conflicts
Definition TypeBase.h:5237
static FunctionEffectSet getUnion(FunctionEffectsRef LHS, FunctionEffectsRef RHS, Conflicts &Errs)
Definition Type.cpp:5672
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5069
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5269
unsigned getNumParams() const
Definition TypeBase.h:5547
QualType getParamType(unsigned i) const
Definition TypeBase.h:5549
unsigned getAArch64SMEAttributes() const
Return a bitmask describing the SME attributes on the function type, see AArch64SMETypeAttributes for...
Definition TypeBase.h:5766
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition TypeBase.h:5582
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5673
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5558
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5554
Declaration of a template function.
FunctionTemplateDecl * getInstantiatedFromMemberTemplate() const
static FunctionTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a function template node.
void mergePrevDecl(FunctionTemplateDecl *Prev)
Merge Prev with our RedeclarableTemplateDecl::Common.
bool isExplicitInstantiationOrSpecialization() const
True if this declaration is an explicit specialization, explicit instantiation declaration,...
Wrapper for source info for functions.
Definition TypeLoc.h:1615
A class which abstracts out some details necessary for making a call.
Definition TypeBase.h:4576
ExtInfo withCallingConv(CallingConv cc) const
Definition TypeBase.h:4688
CallingConv getCC() const
Definition TypeBase.h:4635
ExtInfo withProducesResult(bool producesResult) const
Definition TypeBase.h:4654
unsigned getRegParm() const
Definition TypeBase.h:4628
bool getNoCallerSavedRegs() const
Definition TypeBase.h:4624
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4647
ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const
Definition TypeBase.h:4668
ExtInfo withRegParm(unsigned RegParm) const
Definition TypeBase.h:4682
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4465
ExtInfo getExtInfo() const
Definition TypeBase.h:4821
static StringRef getNameForCallConv(CallingConv CC)
Definition Type.cpp:3578
unsigned getRegParmType() const
Definition TypeBase.h:4808
CallingConv getCallConv() const
Definition TypeBase.h:4820
QualType getReturnType() const
Definition TypeBase.h:4805
bool getCmseNSCallAttr() const
Definition TypeBase.h:4819
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
bool isEditorPlaceholder() const
Return true if this identifier is an editor placeholder.
StringRef getName() const
Return the actual identifier string.
iterator - Iterate over the decls of a specified declaration name.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2072
Represents a C array with an unspecified size.
Definition TypeBase.h:3910
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3467
static IndirectFieldDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, const IdentifierInfo *Id, QualType T, MutableArrayRef< NamedDecl * > CH)
Definition Decl.cpp:5733
void setInherited(bool I)
Definition Attr.h:161
Description of a constructor that was inherited from a base class.
Definition DeclCXX.h:2575
child_range children()
Definition Expr.h:5498
Describes the kind of initialization being performed, along with location information for tokens rela...
static InitializationKind CreateDefault(SourceLocation InitLoc)
Create a default initialization.
static InitializationKind CreateForInit(SourceLocation Loc, bool DirectInit, Expr *Init)
Create an initialization from an initializer (which, for direct initialization from a parenthesized l...
step_iterator step_begin() const
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence.
@ SK_ParenthesizedListInit
Initialize an aggreagate with parenthesized list of values.
Describes an entity that is being initialized.
static InitializedEntity InitializeVariable(VarDecl *Var)
Create the initialization entity for a variable.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition Expr.cpp:974
Represents the declaration of a label.
Definition Decl.h:524
bool isResolvedMSAsmLabel() const
Definition Decl.h:559
LabelStmt * getStmt() const
Definition Decl.h:548
bool isMSAsmLabel() const
Definition Decl.h:558
llvm::iterator_range< capture_init_iterator > capture_inits()
Retrieve the initialization expressions for this lambda's captures.
Definition ExprCXX.h:2083
@ FPE_Ignore
Assume that floating-point exceptions are masked.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
FPExceptionModeKind getDefaultExceptionMode() const
bool requiresStrictPrototypes() const
Returns true if functions without prototypes or functions with an identifier list (aka K&R C function...
std::string getOpenCLVersionString() const
Return the OpenCL C or C++ for OpenCL language name and version as a string.
bool IsHeaderFile
Indicates whether the front-end is explicitly told that the input is a header file (i....
bool isCompatibleWithMSVC() const
unsigned getOpenCLCompatibleVersion() const
Return the OpenCL version that kernel language is compatible with.
static SourceLocation findLocationAfterToken(SourceLocation loc, tok::TokenKind TKind, const SourceManager &SM, const LangOptions &LangOpts, bool SkipTrailingWhitespaceAndNewLine)
Checks that the given token is the first token that occurs after the given location (this excludes co...
Definition Lexer.cpp:1387
Visibility getVisibility() const
Definition Visibility.h:89
Linkage getLinkage() const
Definition Visibility.h:88
Represents a linkage specification.
Definition DeclCXX.h:3011
static LinkageSpecDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExternLoc, SourceLocation LangLoc, LinkageSpecLanguageIDs Lang, bool HasBraces)
Definition DeclCXX.cpp:3253
A class for iterating through a result set and possibly filtering out results.
Definition Lookup.h:677
void erase()
Erase the last element returned from this iterator.
Definition Lookup.h:723
Represents the results of name lookup.
Definition Lookup.h:147
DeclClass * getAsSingle() const
Definition Lookup.h:558
bool empty() const
Return true if no decls were found.
Definition Lookup.h:362
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition Lookup.h:666
Filter makeFilter()
Create a filter for this result set.
Definition Lookup.h:751
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition Lookup.h:569
bool isAmbiguous() const
Definition Lookup.h:324
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition Lookup.h:331
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition Lookup.h:275
Sema & getSema() const
Get the Sema object that this lookup result is searching with.
Definition Lookup.h:672
UnresolvedSetImpl::iterator iterator
Definition Lookup.h:154
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition Lookup.h:576
LookupResultKind getResultKind() const
Definition Lookup.h:344
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition Lookup.h:636
DeclarationName getLookupName() const
Gets the name to look up.
Definition Lookup.h:265
iterator end() const
Definition Lookup.h:359
iterator begin() const
Definition Lookup.h:358
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition Lookup.h:255
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
virtual unsigned getManglingNumber(const CXXMethodDecl *CallOperator)=0
Retrieve the mangling number of a new lambda expression with the given call operator within this cont...
virtual unsigned getStaticLocalNumber(const VarDecl *VD)=0
Static locals are numbered by source order.
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3447
Expr * getBase() const
Definition Expr.h:3441
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3654
Describes a module or submodule.
Definition Module.h:144
SourceLocation DefinitionLoc
The location of the module definition.
Definition Module.h:150
Module * Parent
The parent of this module.
Definition Module.h:193
bool isPrivateModule() const
Definition Module.h:249
bool isHeaderLikeModule() const
Is this module have similar semantics as headers.
Definition Module.h:648
bool isModuleImplementation() const
Is this a module implementation.
Definition Module.h:664
bool isModulePartition() const
Is this a module partition.
Definition Module.h:653
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition Module.cpp:239
bool isNamedModule() const
Does this Module is a named module of a standard named module?
Definition Module.h:224
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
Definition Module.h:722
@ ClassId_NSObject
Definition NSAPI.h:30
This represents a decl that may have a name.
Definition Decl.h:274
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:487
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
bool isLinkageValid() const
True if the computed linkage is valid.
Definition Decl.cpp:1085
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition Decl.cpp:1095
Visibility getVisibility() const
Determines the visibility of this entity.
Definition Decl.h:444
bool hasLinkageBeenComputed() const
True if something has required us to compute the linkage of this declaration.
Definition Decl.h:479
bool hasExternalFormalLinkage() const
True if this decl has external linkage.
Definition Decl.h:429
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
bool declarationReplaces(const NamedDecl *OldD, bool IsKnownNewer=true) const
Determine whether this declaration, if known to be well-formed within its context,...
Definition Decl.cpp:1869
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:1941
bool isExternallyVisible() const
Definition Decl.h:433
ReservedIdentifierStatus isReserved(const LangOptions &LangOpts) const
Determine if the declaration obeys the reserved identifier rules of the given language.
Definition Decl.cpp:1132
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition Decl.h:397
Represent a C++ namespace.
Definition Decl.h:592
bool isAnonymousNamespace() const
Returns true if this is an anonymous namespace declaration.
Definition Decl.h:643
Class that aids in the construction of nested-name-specifiers along with source-location information ...
void MakeTrivial(ASTContext &Context, NestedNameSpecifier Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
A C++ nested-name-specifier augmented with source location information.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
static constexpr NestedNameSpecifier getGlobal()
bool containsErrors() const
Whether this nested name specifier contains an error.
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
@ MicrosoftSuper
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
ObjCCategoryDecl - Represents a category declaration.
Definition DeclObjC.h:2329
ObjCCompatibleAliasDecl - Represents alias of a class.
Definition DeclObjC.h:2775
ObjCContainerDecl - Represents a container for method declarations.
Definition DeclObjC.h:948
ObjCIvarDecl * getIvarDecl(IdentifierInfo *Id) const
getIvarDecl - This method looks up an ivar in this ContextDecl.
Definition DeclObjC.cpp:78
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition DeclObjC.h:2597
Represents an ObjC class declaration.
Definition DeclObjC.h:1154
known_extensions_range known_extensions() const
Definition DeclObjC.h:1762
Wrapper for source info for ObjC interfaces.
Definition TypeLoc.h:1274
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:1284
ObjCIvarDecl - Represents an ObjC instance variable.
Definition DeclObjC.h:1952
static ObjCIvarDecl * Create(ASTContext &C, ObjCContainerDecl *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, AccessControl ac, Expr *BW=nullptr, bool synthesized=false)
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
param_const_iterator param_end() const
Definition DeclObjC.h:358
param_const_iterator param_begin() const
Definition DeclObjC.h:354
const ParmVarDecl *const * param_const_iterator
Definition DeclObjC.h:349
bool isOptional() const
Definition DeclObjC.h:505
ParmVarDecl *const * param_iterator
Definition DeclObjC.h:350
ProtocolLAngleLoc, ProtocolRAngleLoc, and the source locations for protocol qualifiers are stored aft...
Definition TypeLoc.h:895
PtrTy get() const
Definition Ownership.h:81
static OpaquePtr make(DeclGroupRef P)
Definition Ownership.h:61
bool isAvailableOption(llvm::StringRef Ext, const LangOptions &LO) const
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1160
@ CSK_Normal
Normal lookup.
Definition Overload.h:1164
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1376
void NoteCandidates(PartialDiagnosticAt PA, Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, StringRef Opc="", SourceLocation Loc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
When overload resolution fails, prints diagnostic messages containing the candidates in the candidate...
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
MapType::iterator iterator
SmallVectorImpl< UniqueVirtualMethod >::iterator overriding_iterator
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:277
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1386
TypeLoc getInnerLoc() const
Definition TypeLoc.h:1399
void setLParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1382
Sugar for parentheses used when specifying types.
Definition TypeBase.h:3303
Represents a parameter to a function.
Definition Decl.h:1790
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition Decl.h:1850
ObjCDeclQualifier getObjCDeclQualifier() const
Definition Decl.h:1854
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition Decl.h:1823
void setExplicitObjectParameterLoc(SourceLocation Loc)
Definition Decl.h:1882
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition Decl.cpp:2957
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2980
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:8110
Pointer-authentication qualifiers.
Definition TypeBase.h:152
bool isAddressDiscriminated() const
Definition TypeBase.h:265
TypeLoc getPointeeLoc() const
Definition TypeLoc.h:1465
Wrapper for source info for pointers.
Definition TypeLoc.h:1484
void setStarLoc(SourceLocation Loc)
Definition TypeLoc.h:1490
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3329
QualType getPointeeType() const
Definition TypeBase.h:3339
StringRef getLastMacroWithSpelling(SourceLocation Loc, ArrayRef< TokenValue > Tokens) const
Return the name of the macro defined before Loc that has spelling Tokens.
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8376
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition TypeBase.h:8370
bool hasNonTrivialToPrimitiveCopyCUnion() const
Check if this is or contains a C union that is non-trivial to copy, which is a union that has a membe...
Definition Type.h:85
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:1453
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition Type.cpp:2921
const IdentifierInfo * getBaseTypeIdentifier() const
Retrieves a pointer to the name of the base type.
Definition Type.cpp:110
QualType withoutLocalFastQualifiers() const
Definition TypeBase.h:1214
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition TypeBase.h:1296
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const
Check if this is a non-trivial type that would cause a C struct transitively containing this type to ...
Definition Type.cpp:2970
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8292
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8418
bool hasNonTrivialToPrimitiveDestructCUnion() const
Check if this is or contains a C union that is non-trivial to destruct, which is a union that has a m...
Definition Type.h:79
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8332
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1438
QualType getCanonicalType() const
Definition TypeBase.h:8344
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8386
PrimitiveDefaultInitializeKind isNonTrivialToPrimitiveDefaultInitialize() const
Functions to query basic properties of non-trivial C struct types.
Definition Type.cpp:2954
bool isObjCGCStrong() const
true when Type is objc's strong.
Definition TypeBase.h:1433
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8365
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1671
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1545
bool isCanonical() const
Definition TypeBase.h:8349
QualType getSingleStepDesugaredType(const ASTContext &Context) const
Return the specified type with one level of "sugar" removed from the type.
Definition TypeBase.h:1309
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1332
bool hasNonTrivialObjCLifetime() const
Definition TypeBase.h:1442
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition Type.cpp:2695
@ PCK_Trivial
The type does not fall into any of the following categories.
Definition TypeBase.h:1493
@ PCK_VolatileTrivial
The type would be trivial except that it is volatile-qualified.
Definition TypeBase.h:1498
bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const
Check if this is or contains a C union that is non-trivial to default-initialize, which is a union th...
Definition Type.h:73
A qualifier set is used to build a set of qualifiers.
Definition TypeBase.h:8232
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8239
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition Type.cpp:4660
The collection of all-type qualifiers we support.
Definition TypeBase.h:331
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:361
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:354
@ OCL_None
There is no lifetime qualification on this type.
Definition TypeBase.h:350
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:364
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition TypeBase.h:367
bool hasConst() const
Definition TypeBase.h:457
bool hasVolatile() const
Definition TypeBase.h:467
ObjCLifetime getObjCLifetime() const
Definition TypeBase.h:545
bool empty() const
Definition TypeBase.h:647
Represents a struct/union/class.
Definition Decl.h:4324
field_range fields() const
Definition Decl.h:4527
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition Decl.cpp:5227
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4524
field_iterator field_begin() const
Definition Decl.cpp:5270
Frontend produces RecoveryExprs on semantic errors that prevent creating other well-formed expression...
Definition Expr.h:7455
void setMemberSpecialization()
Note that this member template is a specialization.
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition Decl.h:5329
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3574
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition Stmt.h:3152
void setNRVOCandidate(const VarDecl *Var)
Set the variable that might be used for the named return value optimization.
Definition Stmt.h:3195
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:1430
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
SemaDiagnosticBuilder DiagCompat(SourceLocation Loc, unsigned CompatDiagId)
Emit a compatibility diagnostic.
Definition SemaBase.cpp:90
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
void checkAllowedInitializer(VarDecl *VD)
Definition SemaCUDA.cpp:757
std::string getConfigureFuncName() const
Returns the name of the launch configuration function.
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition SemaCUDA.cpp:212
void maybeAddHostDeviceAttrs(FunctionDecl *FD, const LookupResult &Previous)
May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD, depending on FD and the current co...
Definition SemaCUDA.cpp:845
void checkTargetOverload(FunctionDecl *NewFD, const LookupResult &Previous)
Check whether NewFD is a valid overload for CUDA.
void MaybeAddConstantAttr(VarDecl *VD)
May add implicit CUDAConstantAttr attribute to VD, depending on VD and current compilation settings.
Definition SemaCUDA.cpp:910
void CheckEntryPoint(FunctionDecl *FD)
Definition SemaHLSL.cpp:891
HLSLVkConstantIdAttr * mergeVkConstantIdAttr(Decl *D, const AttributeCommonInfo &AL, int Id)
Definition SemaHLSL.cpp:657
HLSLNumThreadsAttr * mergeNumThreadsAttr(Decl *D, const AttributeCommonInfo &AL, int X, int Y, int Z)
Definition SemaHLSL.cpp:623
void deduceAddressSpace(VarDecl *Decl)
void ActOnTopLevelFunction(FunctionDecl *FD)
Definition SemaHLSL.cpp:726
HLSLShaderAttr * mergeShaderAttr(Decl *D, const AttributeCommonInfo &AL, llvm::Triple::EnvironmentType ShaderType)
Definition SemaHLSL.cpp:693
HLSLWaveSizeAttr * mergeWaveSizeAttr(Decl *D, const AttributeCommonInfo &AL, int Min, int Max, int Preferred, int SpelledArgsCount)
Definition SemaHLSL.cpp:637
void ActOnVariableDeclarator(VarDecl *VD)
void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID)
DiagnoseDuplicateIvars - Check for duplicate ivars in the entire class at the start of @implementatio...
void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, const ObjCMethodDecl *Overridden)
Check whether the given new method is a valid override of the given overridden method,...
DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, IdentifierInfo *II)
The parser has read a name in, and Sema has detected that we're currently inside an ObjC method.
void checkRetainCycles(ObjCMessageExpr *msg)
checkRetainCycles - Check whether an Objective-C message send might create an obvious retain cycle.
ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV)
void AddCFAuditedAttribute(Decl *D)
AddCFAuditedAttribute - Check whether we're currently within '#pragma clang arc_cf_code_audited' and,...
void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, ObjCIvarDecl **Fields, unsigned nIvars, SourceLocation Loc)
CheckImplementationIvars - This routine checks if the instance variables listed in the implelementati...
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition SemaObjC.h:591
void ActOnVariableDeclarator(VarDecl *VD)
Function called when a variable declarator is created, which lets us implement the 'routine' 'functio...
OpenACCRoutineDeclAttr * mergeRoutineDeclAttr(const OpenACCRoutineDeclAttr &Old)
void ActOnFunctionDeclarator(FunctionDecl *FD)
Called when a function decl is created, which lets us implement the 'routine' 'doesn't match next thi...
void ActOnVariableInit(VarDecl *VD, QualType InitType)
Called when a variable is initialized, so we can implement the 'routine 'doesn't match the next thing...
void ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D)
Act on D, a function definition inside of an omp [begin/end] assumes.
void ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Decl *D, SmallVectorImpl< FunctionDecl * > &Bases)
Register D as specialization of all base functions in Bases in the current omp begin/end declare vari...
void ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists, SmallVectorImpl< FunctionDecl * > &Bases)
The declarator D defines a function in the scope S which is nested in an omp begin/end declare varian...
void ActOnOpenMPDeclareTargetInitializer(Decl *D)
Adds OMPDeclareTargetDeclAttr to referenced variables in declare target directive.
void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, SourceLocation IdLoc=SourceLocation())
Check declaration inside target region.
void checkRVVTypeSupport(QualType Ty, SourceLocation Loc, Decl *D, const llvm::StringMap< bool > &FeatureMap)
void CheckSYCLExternalFunctionDecl(FunctionDecl *FD)
Definition SemaSYCL.cpp:253
StmtResult BuildSYCLKernelCallStmt(FunctionDecl *FD, CompoundStmt *Body)
Definition SemaSYCL.cpp:437
void CheckSYCLEntryPointFunctionDecl(FunctionDecl *FD)
Definition SemaSYCL.cpp:270
SwiftNameAttr * mergeNameAttr(Decl *D, const SwiftNameAttr &SNA, StringRef Name)
Definition SemaSwift.cpp:26
WebAssemblyImportNameAttr * mergeImportNameAttr(Decl *D, const WebAssemblyImportNameAttr &AL)
Definition SemaWasm.cpp:334
WebAssemblyImportModuleAttr * mergeImportModuleAttr(Decl *D, const WebAssemblyImportModuleAttr &AL)
Definition SemaWasm.cpp:313
bool IsAlignAttr() const
Definition Sema.h:1894
Mode getAlignMode() const
Definition Sema.h:1896
A RAII object to temporarily push a declaration context.
Definition Sema.h:3494
A class which encapsulates the logic for delaying diagnostics during parsing and other processing.
Definition Sema.h:1362
bool shouldDelayDiagnostics()
Determines whether diagnostics should be delayed.
Definition Sema.h:1374
void add(const sema::DelayedDiagnostic &diag)
Adds a delayed diagnostic.
static NameClassification DependentNonType()
Definition Sema.h:3710
static NameClassification VarTemplate(TemplateName Name)
Definition Sema.h:3720
static NameClassification Unknown()
Definition Sema.h:3690
static NameClassification OverloadSet(ExprResult E)
Definition Sema.h:3694
static NameClassification UndeclaredTemplate(TemplateName Name)
Definition Sema.h:3738
static NameClassification FunctionTemplate(TemplateName Name)
Definition Sema.h:3726
static NameClassification NonType(NamedDecl *D)
Definition Sema.h:3700
static NameClassification Concept(TemplateName Name)
Definition Sema.h:3732
static NameClassification UndeclaredNonType()
Definition Sema.h:3706
static NameClassification TypeTemplate(TemplateName Name)
Definition Sema.h:3714
static NameClassification Error()
Definition Sema.h:3686
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12476
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12510
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:856
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:3588
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D)
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:13073
sema::CapturingScopeInfo * getEnclosingLambdaOrBlock() const
Get the innermost lambda or block enclosing the current location, if any.
Definition Sema.cpp:2546
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1121
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:8266
CXXSpecialMemberKind getSpecialMember(const CXXMethodDecl *MD)
Definition Sema.h:6327
LookupNameKind
Describes the kind of name lookup to perform.
Definition Sema.h:9349
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9353
@ LookupNestedNameSpecifierName
Look up of a name that precedes the '::' scope resolution operator in C++.
Definition Sema.h:9372
@ LookupLocalFriendName
Look up a friend of a local class.
Definition Sema.h:9388
@ LookupRedeclarationWithLinkage
Look up an ordinary name that is going to be redeclared as a name with linkage.
Definition Sema.h:9385
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9361
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition Sema.h:9356
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:1508
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:1242
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:4760
llvm::SmallSetVector< const TypedefNameDecl *, 4 > UnusedLocalTypedefNameCandidates
Set containing all typedefs that are likely unused.
Definition Sema.h:3570
PragmaClangSection PragmaClangRodataSection
Definition Sema.h:1820
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:6519
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:1448
TemplateDecl * AdjustDeclIfTemplate(Decl *&Decl)
AdjustDeclIfTemplate - If the given decl happens to be a template, reset the parameter D to reference...
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC)
Require that the context specified by SS be complete.
bool TemplateParameterListsAreEqual(const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New, const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc=SourceLocation())
Determine whether the given template parameter lists are equivalent.
bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMemberKind CSM, InheritedConstructorInfo *ICI=nullptr, bool Diagnose=false)
Determine if a special member function should have a deleted definition when it is defaulted.
void ActOnExitFunctionContext()
void inferLifetimeCaptureByAttribute(FunctionDecl *FD)
Add [[clang:lifetime_capture_by(this)]] to STL container methods.
Definition SemaAttr.cpp:277
ExprResult RebuildExprInCurrentInstantiation(Expr *E)
Preprocessor & getPreprocessor() const
Definition Sema.h:926
void deduceOpenCLAddressSpace(ValueDecl *decl)
PragmaStack< FPOptionsOverride > FpPragmaStack
Definition Sema.h:2051
PragmaStack< StringLiteral * > CodeSegStack
Definition Sema.h:2045
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:4163
@ Delete
deleted-function-body
Definition Sema.h:4169
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:1533
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:1660
const AttributedType * getCallingConvAttributedType(QualType T) const
Get the outermost AttributedType node that sets a calling convention.
TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S)
isTagName() - This method is called for error recovery purposes only to determine if the specified na...
Definition SemaDecl.cpp:675
bool CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old)
[module.interface]p6: A redeclaration of an entity X is implicitly exported if X was introduced by an...
void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass &SC)
CheckConversionDeclarator - Called by ActOnDeclarator to check the well-formednes of the conversion f...
VisibilityAttr * mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, VisibilityAttr::VisibilityType Vis)
TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool &MemberOfUnknownSpecialization, bool Disambiguation=false)
Decl * ActOnFileScopeAsmDecl(Expr *expr, SourceLocation AsmLoc, SourceLocation RParenLoc)
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
ASTContext & Context
Definition Sema.h:1288
void FinalizeDeclaration(Decl *D)
FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform any semantic actions neces...
void LazyProcessLifetimeCaptureByParams(FunctionDecl *FD)
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:225
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
llvm::DenseMap< IdentifierInfo *, PendingPragmaInfo > PendingExportedNames
Definition Sema.h:2333
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:924
void ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement)
void * SkippedDefinitionContext
Definition Sema.h:4387
bool LookupBuiltin(LookupResult &R)
Lookup a builtin function, when name lookup would otherwise fail.
SemaObjC & ObjC()
Definition Sema.h:1493
void DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record)
Emit diagnostic warnings for placeholder members.
void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, TypedefNameDecl *NewTD)
bool isRedefinitionAllowedFor(NamedDecl *D, NamedDecl **Suggested, bool &Visible)
Determine if D has a definition which allows we redefine it in current TU.
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType=nullptr)
Definition SemaDecl.cpp:79
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
PragmaStack< bool > StrictGuardStackCheckStack
Definition Sema.h:2048
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:3578
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:927
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:2044
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition Sema.cpp:756
bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S)
isMicrosoftMissingTypename - In Microsoft mode, within class scope, if a CXXScopeSpec's type is equal...
Definition SemaDecl.cpp:699
bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen)
void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord)
Add gsl::Pointer attribute to std::container::iterator.
Definition SemaAttr.cpp:112
void mergeVisibilityType(Decl *D, SourceLocation Loc, VisibilityAttr::VisibilityType Type)
bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn)
We've just determined that Old and New both appear to be definitions of the same variable.
OverloadKind CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &OldDecls, NamedDecl *&OldDecl, bool UseMemberUsingDeclRules)
Determine whether the given New declaration is an overload of the declarations in Old.
bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a literal type.
void ProcessPragmaWeak(Scope *S, Decl *D)
bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee)
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition Sema.h:1192
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:1665
bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag, bool isDefinition, SourceLocation NewTagLoc, const IdentifierInfo *Name)
Determine whether a tag with a given kind is acceptable as a redeclaration of the given tag declarati...
void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F)
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE)
void CheckAttributesOnDeducedType(Decl *D)
CheckAttributesOnDeducedType - Calls Sema functions for attributes that requires the type to be deduc...
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition Sema.h:12174
EnumDecl * getStdAlignValT() const
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition Sema.h:8384
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:2337
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:4598
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:922
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:2355
void PopCompoundScope()
Definition Sema.cpp:2488
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:14429
@ UPPC_EnumeratorValue
The enumerator value.
Definition Sema.h:14432
@ UPPC_Initializer
An initializer.
Definition Sema.h:14444
@ UPPC_FriendDeclaration
A friend declaration.
Definition Sema.h:14438
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition Sema.h:14417
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition Sema.h:14456
@ UPPC_DeclarationQualifier
A declaration qualifier.
Definition Sema.h:14441
@ UPPC_DataMemberType
The type of a data member.
Definition Sema.h:14420
@ UPPC_BitFieldWidth
The size of a bit-field.
Definition Sema.h:14423
const LangOptions & getLangOpts() const
Definition Sema.h:920
void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl, bool SupportedForCompatibility=false)
DiagnoseTemplateParameterShadow - Produce a diagnostic complaining that the template parameter 'PrevD...
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
bool RebuildTemplateParamsInCurrentInstantiation(TemplateParameterList *Params)
Rebuild the template parameters now that we know we're in a current instantiation.
void DiagnoseInvalidJumps(Stmt *Body)
PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, Decl *D=nullptr, QualType BlockType=QualType())
Pop a function (or block or lambda or captured region) scope from the stack.
Definition Sema.cpp:2449
SourceLocation CurInitSegLoc
Definition Sema.h:2087
void inferLifetimeBoundAttribute(FunctionDecl *FD)
Add [[clang:lifetimebound]] attr for std:: functions and methods.
Definition SemaAttr.cpp:220
ModularFormatAttr * mergeModularFormatAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *ModularImplFn, StringRef ImplName, MutableArrayRef< StringRef > Aspects)
bool currentModuleIsHeaderUnit() const
Is the module scope we are in a C++ Header Unit?
Definition Sema.h:3595
SemaOpenACC & OpenACC()
Definition Sema.h:1498
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:1287
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:2127
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:1286
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:2564
bool isReachable(const NamedDecl *D)
Determine whether a declaration is reachable.
Definition Sema.h:15501
Decl * ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody=nullptr, FnBodyKind BodyKind=FnBodyKind::Other)
SemaHLSL & HLSL()
Definition Sema.h:1458
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:1821
SemaRISCV & RISCV()
Definition Sema.h:1523
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:15677
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:214
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:1538
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:2033
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:6983
PragmaStack< StringLiteral * > BSSSegStack
Definition Sema.h:2043
bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true, bool AllowNonTemplateFunctions=false)
DeclContext * getCurLexicalContext() const
Definition Sema.h:1125
bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous)
Perform semantic analysis for the given dependent function template specialization.
bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl)
CheckOverloadedOperatorDeclaration - Check whether the declaration of this overloaded operator is wel...
bool hasExplicitCallingConv(QualType T)
NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc, const Token &NextToken, CorrectionCandidateCallback *CCC=nullptr)
Perform name lookup on the given name, classifying it based on the results of name lookup and the fol...
Definition SemaDecl.cpp:898
void ExitDeclaratorContext(Scope *S)
void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI)
Diagnose shadowing for variables shadowed in the lambda record LambdaRD when these variables are capt...
void CheckConstructor(CXXConstructorDecl *Constructor)
CheckConstructor - Checks a fully-formed constructor for well-formedness, issuing any diagnostics req...
void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMemberKind CSM)
Diagnose why the specified class does not have a trivial special member of the given kind.
llvm::SmallSetVector< Decl *, 4 > DeclsToCheckForDeferredDiags
Function or variable declarations to be checked for whether the deferred diagnostics should be emitte...
Definition Sema.h:4775
void CheckMSVCRTEntryPoint(FunctionDecl *FD)
sema::FunctionScopeInfo * getCurFunction() const
Definition Sema.h:1321
void PushCompoundScope(bool IsStmtExpr)
Definition Sema.cpp:2483
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:6980
void AddPushedVisibilityAttribute(Decl *RD)
AddPushedVisibilityAttribute - If '#pragma GCC visibility' was used, add an appropriate visibility at...
bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method)
Check whether 'this' shows up in the attributes of the given static member function.
void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, SourceLocation FinalLoc, bool IsFinalSpelledSealed, bool IsAbstract, SourceLocation LBraceLoc)
ActOnStartCXXMemberDeclarations - Invoked when we have parsed a C++ record definition's base-specifie...
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:640
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:15495
StringLiteral * CurInitSeg
Last section used with pragma init_seg.
Definition Sema.h:2086
FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl, bool Final=false)
Module * getCurrentModule() const
Get the module unit whose scope we are currently within.
Definition Sema.h:9879
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:1421
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
SemaOpenCL & OpenCL()
Definition Sema.h:1503
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
TypeSourceInfo * RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name)
Rebuilds a type within the context of the current instantiation.
Decl * ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, MultiTemplateParamsArg TemplateParams, SourceLocation EllipsisLoc)
Handle a friend type declaration.
void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
ParmVarDecl * CheckParameter(DeclContext *DC, SourceLocation StartLoc, SourceLocation NameLoc, const IdentifierInfo *Name, QualType T, TypeSourceInfo *TSInfo, StorageClass SC)
bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc=SourceLocation(), bool ForOverloadResolution=false)
Check whether the given function decl's trailing requires clause is satisfied, if any.
DeclContext * getFunctionLevelDeclContext(bool AllowLambda=false) const
If AllowLambda is true, treat lambda as function.
Definition Sema.cpp:1640
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:3592
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:13963
SourceManager & getSourceManager() const
Definition Sema.h:925
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:3545
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:1822
@ NTCUK_Destruct
Definition Sema.h:4102
@ NTCUK_Init
Definition Sema.h:4101
@ NTCUK_Copy
Definition Sema.h:4103
FormatMatchesAttr * mergeFormatMatchesAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Format, int FormatIdx, StringLiteral *FormatStr)
PragmaClangSection PragmaClangDataSection
Definition Sema.h:1819
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:6780
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)
void ProcessPragmaExport(DeclaratorDecl *newDecl)
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:2504
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:6541
ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II, SourceLocation NameLoc, bool IsTemplateTypeArg)
Attempt to behave like MSVC in situations where lookup of an unqualified type name has failed in a de...
Definition SemaDecl.cpp:627
EnforceTCBLeafAttr * mergeEnforceTCBLeafAttr(Decl *D, const EnforceTCBLeafAttr &AL)
void ActOnLastBitfield(SourceLocation DeclStart, SmallVectorImpl< Decl * > &AllIvarDecls)
ActOnLastBitfield - This routine handles synthesized bitfields rules for class and class extensions.
void FinalizeVarWithDestructor(VarDecl *VD, CXXRecordDecl *DeclInit)
FinalizeVarWithDestructor - Prepare for calling destructor on the constructed variable.
void MarkUnusedFileScopedDecl(const DeclaratorDecl *D)
If it's a file scoped decl that must warn if not used, keep track of it.
llvm::DenseMap< IdentifierInfo *, AsmLabelAttr * > ExtnameUndeclaredIdentifiers
ExtnameUndeclaredIdentifiers - Identifiers contained in #pragma redefine_extname before declared.
Definition Sema.h:3566
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=AllowFoldKind::No)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec *SS=nullptr, bool isClassName=false, bool HasTrailingDot=false, ParsedType ObjectType=nullptr, bool IsCtorOrDtorName=false, bool WantNontrivialTypeSourceInfo=false, bool IsClassTemplateDeductionContext=true, ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No, IdentifierInfo **CorrectedII=nullptr)
If the identifier refers to a type name within this scope, return the declaration of that type.
Definition SemaDecl.cpp:274
EnumConstantDecl * CheckEnumConstant(EnumDecl *Enum, EnumConstantDecl *LastEnumConst, SourceLocation IdLoc, IdentifierInfo *Id, Expr *val)
DeclResult ActOnVarTemplateSpecialization(Scope *S, Declarator &D, TypeSourceInfo *TSI, LookupResult &Previous, SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, StorageClass SC, bool IsPartialSpecialization)
bool CheckForConstantInitializer(Expr *Init, unsigned DiagID=diag::err_init_element_not_constant)
type checking declaration initializers (C99 6.7.8)
ASTConsumer & Consumer
Definition Sema.h:1289
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition Sema.h:4661
SmallVector< ExprWithCleanups::CleanupObject, 8 > ExprCleanupObjects
ExprCleanupObjects - This is the stack of objects requiring cleanup that are created by the current f...
Definition Sema.h:6987
void DiagnoseUnusedNestedTypedefs(const RecordDecl *D)
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition Sema.h:1326
bool hasUncompilableErrorOccurred() const
Whether uncompilable error has occurred.
Definition Sema.cpp:1786
@ FirstDecl
Parsing the first decl in a TU.
Definition Sema.h:9907
void CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc)
void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FunctionDecl *FD)
If this function is a C++ replaceable global allocation function (C++2a [basic.stc....
void ActOnDocumentableDecls(ArrayRef< Decl * > Group)
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
void CheckStaticLocalForDllExport(VarDecl *VD)
Check if VD needs to be dllexport/dllimport due to being in a dllexport/import function.
void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery=true)
DeclResult ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, AccessSpecifier AS, SourceLocation ModulePrivateLoc, MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, bool &IsDependent, SourceLocation ScopedEnumKWLoc, bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, bool IsTypeSpecifier, bool IsTemplateParamOrArg, OffsetOfKind OOK, SkipBodyInfo *SkipBody=nullptr)
This is invoked when we see 'struct foo' or 'struct {'.
Decl * ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, const ParsedAttributesView &DeclAttrs, RecordDecl *&AnonRecord)
ParsedFreeStandingDeclSpec - This method is invoked when a declspec with no declarator (e....
SemaPPC & PPC()
Definition Sema.h:1513
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:1247
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:3585
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:8339
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:1291
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:1290
OpenCLOptions & getOpenCLOptions()
Definition Sema.h:921
FPOptions CurFPFeatures
Definition Sema.h:1284
static bool CanBeGetReturnObject(const FunctionDecl *FD)
NamespaceDecl * getStdNamespace() const
bool IsAtLeastAsConstrained(const NamedDecl *D1, MutableArrayRef< AssociatedConstraint > AC1, const NamedDecl *D2, MutableArrayRef< AssociatedConstraint > AC2, bool &Result)
Check whether the given declaration's associated constraints are at least as constrained than another...
void addLifetimeBoundToImplicitThis(CXXMethodDecl *MD)
NamedDecl * ActOnTypedefDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous)
PragmaStack< StringLiteral * > DataSegStack
Definition Sema.h:2042
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:11606
@ TPC_ClassTemplateMember
Definition Sema.h:11604
@ TPC_FunctionTemplate
Definition Sema.h:11603
@ TPC_FriendFunctionTemplateDefinition
Definition Sema.h:11607
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:1563
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:6557
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...
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:3560
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition Sema.cpp:2110
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:1818
Decl * ActOnDeclarator(Scope *S, Declarator &D)
@ AbstractVariableType
Definition Sema.h:6251
@ AbstractReturnType
Definition Sema.h:6249
@ AbstractFieldType
Definition Sema.h:6252
@ AbstractIvarType
Definition Sema.h:6253
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:8388
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:6438
void CheckVariableDeclarationType(VarDecl *NewVD)
OpaquePtr< TemplateName > TemplateTy
Definition Sema.h:1280
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:3541
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:1548
FormatAttr * mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Format, int FormatIdx, int FirstArg)
IdentifierResolver IdResolver
Definition Sema.h:3487
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:2495
void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc, Scope *S, CXXScopeSpec *SS, ParsedType &SuggestedType, bool IsTemplateName=false)
Definition SemaDecl.cpp:718
void DiagnoseSizeOfParametersAndReturnValue(ArrayRef< ParmVarDecl * > Parameters, QualType ReturnTy, NamedDecl *D)
Diagnose whether the size of parameters or return value of a function or obj-c method definition is p...
void checkTypeDeclType(DeclContext *LookupCtx, DiagCtorKind DCK, TypeDecl *TD, SourceLocation NameLoc)
Returns the TypeDeclType for the given type declaration, as ASTContext::getTypeDeclType would,...
Definition SemaDecl.cpp:147
void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD)
llvm::SmallVector< std::pair< SourceLocation, const BlockDecl * >, 1 > ImplicitlyRetainedSelfLocs
List of SourceLocations where 'self' is implicitly retained inside a block.
Definition Sema.h:8347
OpaquePtr< DeclGroupRef > DeclGroupPtrTy
Definition Sema.h:1279
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:3833
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:1428
void inferNullableClassAttribute(CXXRecordDecl *CRD)
Add _Nullable attributes for std:: types.
Definition SemaAttr.cpp:322
AvailabilityAttr * mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Platform, bool Implicit, VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable, StringRef Message, bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK, int Priority, const IdentifierInfo *IIEnvironment)
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8681
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:86
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:362
child_range children()
Definition Stmt.cpp:299
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:338
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:350
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1799
SourceLocation getStrTokenLoc(unsigned TokNum) const
Get one of the string literal token.
Definition Expr.h:1945
StringRef getString() const
Definition Expr.h:1867
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3717
static TagDecl * castFromDeclContext(const DeclContext *DC)
Definition Decl.h:4002
TagDecl * getDefinition() const
Returns the TagDecl that actually defines this struct/union/class/enum.
Definition Decl.cpp:4929
bool isThisDeclarationADefinition() const
Return true if this declaration is a completion definition of the type.
Definition Decl.h:3810
SourceLocation getInnerLocStart() const
Return SourceLocation representing start of source range ignoring outer template declarations.
Definition Decl.h:3796
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3815
bool isStruct() const
Definition Decl.h:3922
void setTypedefNameForAnonDecl(TypedefNameDecl *TDD)
Definition Decl.cpp:4901
bool isUnion() const
Definition Decl.h:3925
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type?
Definition Decl.h:3947
TagKind getTagKind() const
Definition Decl.h:3914
bool isDependentType() const
Whether this declaration declares a type that is dependent, i.e., a type that somehow depends on temp...
Definition Decl.h:3860
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:805
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Exposes information about the current target.
Definition TargetInfo.h:226
virtual bool validateCpuIs(StringRef Name) const
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
virtual llvm::APInt getFMVPriority(ArrayRef< StringRef > Features) const
virtual bool validateCpuSupports(StringRef Name) const
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
virtual bool isValidFeatureName(StringRef Feature) const
Determine whether this TargetInfo supports the given feature.
virtual ParsedTargetAttr parseTargetAttr(StringRef Str) const
bool supportsMultiVersioning() const
Identify whether this target supports multiversioning of functions, which requires support for cpu_su...
virtual bool shouldDLLImportComdatSymbols() const
Does this target aim for semantic compatibility with Microsoft C++ code using dllimport/export attrib...
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
A convenient class for passing around template argument information.
void setLAngleLoc(SourceLocation Loc)
void setRAngleLoc(SourceLocation Loc)
ArrayRef< TemplateArgumentLoc > arguments() const
Location wrapper for a TemplateArgument.
The base class of all kinds of template declarations (e.g., class, function, etc.).
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
Stores a list of template parameters for a TemplateDecl and its derived classes.
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation getRAngleLoc() const
SourceLocation getTemplateLoc() const
Token - This structure provides full information about a lexed token.
Definition Token.h:36
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {....
Definition Token.h:102
bool isOneOf(Ts... Ks) const
Definition Token.h:103
bool isNot(tok::TokenKind K) const
Definition Token.h:109
A declaration that models statements at global scope.
Definition Decl.h:4634
static TopLevelStmtDecl * Create(ASTContext &C, Stmt *Statement)
Definition Decl.cpp:5857
void setStmt(Stmt *S)
Definition Decl.cpp:5877
Represents a declaration of a type.
Definition Decl.h:3513
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
void pushFullCopy(TypeLoc L)
Pushes a copy of the given TypeLoc onto this builder.
TypeSpecTypeLoc pushTypeSpec(QualType T)
Pushes space for a typespec TypeLoc.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:59
UnqualTypeLoc getUnqualifiedLoc() const
Skips past any qualifiers, if this is qualified.
Definition TypeLoc.h:349
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:89
TypeLoc IgnoreParens() const
Definition TypeLoc.h:1408
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition TypeLoc.h:78
void initializeFullCopy(TypeLoc Other)
Initializes this by copying its information from another TypeLoc of the same type.
Definition TypeLoc.h:217
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition TypeLoc.h:154
AutoTypeLoc getContainedAutoTypeLoc() const
Get the typeloc of an AutoType whose type will be deduced for a variable with an initializer of this ...
Definition TypeLoc.cpp:879
SourceLocation getEndLoc() const
Get the end source location.
Definition TypeLoc.cpp:227
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:2706
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:193
A container of type source information.
Definition TypeBase.h:8263
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:267
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8274
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:551
The base class of the type hierarchy.
Definition TypeBase.h:1833
bool isStructureType() const
Definition Type.cpp:679
bool isDependentSizedArrayType() const
Definition TypeBase.h:8648
bool isVoidType() const
Definition TypeBase.h:8891
bool isBooleanType() const
Definition TypeBase.h:9021
bool isFunctionReferenceType() const
Definition TypeBase.h:8603
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2226
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition TypeBase.h:9071
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition Type.cpp:2994
bool isIncompleteArrayType() const
Definition TypeBase.h:8636
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9187
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:8632
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition TypeBase.h:9051
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isArrayType() const
Definition TypeBase.h:8628
bool isFunctionPointerType() const
Definition TypeBase.h:8596
bool isPointerType() const
Definition TypeBase.h:8529
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9178
bool isReferenceType() const
Definition TypeBase.h:8553
bool isScalarType() const
Definition TypeBase.h:8993
bool isVariableArrayType() const
Definition TypeBase.h:8640
bool isClkEventT() const
Definition TypeBase.h:8777
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2104
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:753
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9009
TagDecl * getAsTagDecl() const
Retrieves the TagDecl that this type refers to, either because the type is a TagType or because it is...
Definition Type.h:63
bool isImageType() const
Definition TypeBase.h:8789
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition TypeBase.h:2900
bool isPipeType() const
Definition TypeBase.h:8796
bool isOpenCLSpecificType() const
Definition TypeBase.h:8825
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2783
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition Type.cpp:2412
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool isHalfType() const
Definition TypeBase.h:8895
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition Type.cpp:2057
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition Type.cpp:2558
bool containsErrors() const
Whether this type is an error type.
Definition TypeBase.h:2777
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition TypeBase.h:9064
bool isAtomicType() const
Definition TypeBase.h:8717
bool isFunctionProtoType() const
Definition TypeBase.h:2601
bool isObjCIdType() const
Definition TypeBase.h:8737
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2801
bool isObjCObjectType() const
Definition TypeBase.h:8708
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9027
bool isEventT() const
Definition TypeBase.h:8773
bool isPointerOrReferenceType() const
Definition TypeBase.h:8533
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2436
const T * getAsAdjusted() const
Member-template getAsAdjusted<specific type>.
Definition TypeBase.h:9128
bool isFunctionType() const
Definition TypeBase.h:8525
bool isObjCObjectPointerType() const
Definition TypeBase.h:8704
bool isMemberFunctionPointerType() const
Definition TypeBase.h:8614
bool isFloatingType() const
Definition Type.cpp:2305
bool isAnyPointerType() const
Definition TypeBase.h:8537
bool hasAutoForTrailingReturnType() const
Determine whether this type was written with a leading 'auto' corresponding to a trailing return type...
Definition Type.cpp:2062
bool isSamplerT() const
Definition TypeBase.h:8769
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9111
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:654
bool isNullPtrType() const
Definition TypeBase.h:8928
bool isRecordType() const
Definition TypeBase.h:8656
bool isHLSLResourceRecordArray() const
Definition Type.cpp:5367
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5015
bool isUnionType() const
Definition Type.cpp:719
bool isFunctionNoProtoType() const
Definition TypeBase.h:2600
bool isReserveIDT() const
Definition TypeBase.h:8785
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition Decl.h:3667
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition Decl.cpp:5756
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3562
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:3612
QualType getUnderlyingType() const
Definition Decl.h:3617
void setTypeSourceInfo(TypeSourceInfo *newType)
Definition Decl.h:3623
Wrapper for source info for typedefs.
Definition TypeLoc.h:777
TypedefNameDecl * getDecl() const
Definition TypeBase.h:6114
Simple class containing the result of Sema::CorrectTypo.
IdentifierInfo * getCorrectionAsIdentifierInfo() const
NamedDecl * getCorrectionDecl() const
Gets the pointer to the declaration of the typo correction.
decl_iterator begin()
SmallVectorImpl< NamedDecl * >::const_iterator const_decl_iterator
DeclarationName getCorrection() const
Gets the DeclarationName of the typo correction.
unsigned getEditDistance(bool Normalized=true) const
Gets the "edit distance" of the typo correction from the typo.
SmallVectorImpl< NamedDecl * >::iterator decl_iterator
void setCorrectionDecl(NamedDecl *CDecl)
Clears the list of NamedDecls before adding the new one.
NestedNameSpecifier getCorrectionSpecifier() const
Gets the NestedNameSpecifier needed to use the typo correction.
Expr * getSubExpr() const
Definition Expr.h:2285
Opcode getOpcode() const
Definition Expr.h:2280
static bool isIncrementDecrementOp(Opcode Op)
Definition Expr.h:2340
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:998
struct OFI OperatorFunctionId
When Kind == IK_OperatorFunctionId, the overloaded operator that we parsed.
Definition DeclSpec.h:1030
UnionParsedType ConversionFunctionId
When Kind == IK_ConversionFunctionId, the type that the conversion function names.
Definition DeclSpec.h:1034
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
Definition DeclSpec.h:1086
UnionParsedType ConstructorName
When Kind == IK_ConstructorName, the class-name of the type whose constructor is being referenced.
Definition DeclSpec.h:1038
SourceLocation EndLocation
The location of the last token that describes this unqualified-id.
Definition DeclSpec.h:1059
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition DeclSpec.h:1207
UnionParsedType DestructorName
When Kind == IK_DestructorName, the type referred to by the class-name.
Definition DeclSpec.h:1042
SourceLocation StartLocation
The location of the first token that describes this unqualified-id, which will be the location of the...
Definition DeclSpec.h:1056
UnionParsedTemplateTy TemplateName
When Kind == IK_DeductionGuideName, the parsed template-name.
Definition DeclSpec.h:1045
const IdentifierInfo * Identifier
When Kind == IK_Identifier, the parsed identifier, or when Kind == IK_UserLiteralId,...
Definition DeclSpec.h:1026
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition DeclSpec.h:1080
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition DeclSpec.h:1050
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent, bool KnownInstantiationDependent)
Definition ExprCXX.cpp:432
Wrapper for source info for unresolved typename using decls.
Definition TypeLoc.h:782
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3395
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3459
BaseUsingDecl * getIntroducer() const
Gets the (written or instantiated) using declaration that introduced this declaration.
Definition DeclCXX.cpp:3427
Wrapper for source info for types used via transparent aliases.
Definition TypeLoc.h:785
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
void setType(QualType newType)
Definition Decl.h:724
QualType getType() const
Definition Decl.h:723
bool isParameterPack() const
Determine whether this value is actually a function parameter pack, init-capture pack,...
Definition Decl.cpp:5588
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.cpp:5582
Represents a variable declaration or definition.
Definition Decl.h:926
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition Decl.cpp:2821
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition Decl.cpp:2162
void setCXXForRangeDecl(bool FRD)
Definition Decl.h:1525
bool isFirstDecl() const
True if this is the first declaration in its redeclaration chain.
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition Decl.h:1569
TLSKind getTLSKind() const
Definition Decl.cpp:2179
bool hasInit() const
Definition Decl.cpp:2409
void setInitStyle(InitializationStyle Style)
Definition Decl.h:1452
VarDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
Definition Decl.cpp:2271
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2201
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:2472
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:2268
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.h:1578
bool isCXXCondDecl() const
Definition Decl.h:1611
@ ListInit
Direct list-initialization (C++11)
Definition Decl.h:937
@ ParenListInit
Parenthesized list-initialization (C++20)
Definition Decl.h:940
@ CallInit
Call-style initialization (C++98)
Definition Decl.h:934
void setStorageClass(StorageClass SC)
Definition Decl.cpp:2174
void setPreviousDeclInSameBlockScope(bool Same)
Definition Decl.h:1593
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1283
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition Decl.h:1226
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition Decl.cpp:2377
void setInlineSpecified()
Definition Decl.h:1558
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1208
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition Decl.cpp:2783
bool isFileVarDecl() const
Returns true for file scoped variable declaration.
Definition Decl.h:1342
void setTSCSpec(ThreadStorageClassSpecifier TSC)
Definition Decl.h:1173
bool isInline() const
Whether this variable is (C++1z) inline.
Definition Decl.h:1551
ThreadStorageClassSpecifier getTSCSpec() const
Definition Decl.h:1177
const Expr * getInit() const
Definition Decl.h:1368
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition Decl.h:1217
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition Decl.h:1184
VarDecl * getInitializingDeclaration()
Get the initializing declaration of this variable, if any.
Definition Decl.cpp:2440
void setConstexpr(bool IC)
Definition Decl.h:1572
@ TLS_Static
TLS with a known-constant initializer.
Definition Decl.h:949
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition Decl.h:952
void setInit(Expr *I)
Definition Decl.cpp:2488
VarDecl * getActingDefinition()
Get the tentative definition that acts as the real definition in a TU.
Definition Decl.cpp:2356
@ TentativeDefinition
This declaration is a tentative definition.
Definition Decl.h:1298
@ DeclarationOnly
This declaration is only a declaration.
Definition Decl.h:1295
@ Definition
This declaration is definitely a definition.
Definition Decl.h:1301
void setDescribedVarTemplate(VarTemplateDecl *Template)
Definition Decl.cpp:2826
bool isExternC() const
Determines whether this variable is a variable with external, C linkage.
Definition Decl.cpp:2256
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition Decl.h:1253
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:1168
void setImplicitlyInline()
Definition Decl.h:1563
bool isThisDeclarationADemotedDefinition() const
If this definition should pretend to be a declaration.
Definition Decl.h:1476
bool isPreviousDeclInSameBlockScope() const
Whether this local extern variable declaration's previous declaration was declared in the same block ...
Definition Decl.h:1588
VarDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
bool hasDependentAlignment() const
Determines if this variable's alignment is dependent.
Definition Decl.cpp:2717
bool isLocalVarDeclOrParm() const
Similar to isLocalVarDecl but also includes parameters.
Definition Decl.h:1262
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition Decl.cpp:2790
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition Decl.h:1358
Declaration of a variable template.
VarDecl * getTemplatedDecl() const
Get the underlying variable declarations of the template.
VarTemplateDecl * getInstantiatedFromMemberTemplate() const
static VarTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, VarDecl *Decl)
Create a variable template node.
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:3967
Expr * getSizeExpr() const
Definition TypeBase.h:3981
Captures information about a #pragma weak directive.
Definition Weak.h:25
ValueDecl * getVariable() const
Definition ScopeInfo.h:675
bool isVariableCapture() const
Definition ScopeInfo.h:650
SourceLocation getLocation() const
Retrieve the location at which this variable was captured.
Definition ScopeInfo.h:686
void addVLATypeCapture(SourceLocation Loc, const VariableArrayType *VLAType, QualType CaptureType)
Definition ScopeInfo.h:745
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition ScopeInfo.h:732
SmallVector< Capture, 4 > Captures
Captures - The captures.
Definition ScopeInfo.h:721
ImplicitCaptureStyle ImpCaptureStyle
Definition ScopeInfo.h:708
bool isCXXThisCaptured() const
Determine whether the C++ 'this' is captured.
Definition ScopeInfo.h:755
void addThisCapture(bool isNested, SourceLocation Loc, QualType CaptureType, bool ByCopy)
Definition ScopeInfo.h:1096
void addCapture(ValueDecl *Var, bool isBlock, bool isByref, bool isNested, SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType, bool Invalid)
Definition ScopeInfo.h:737
static DelayedDiagnostic makeForbiddenType(SourceLocation loc, unsigned diagnostic, QualType type, unsigned argument)
Retains information about a function, method, or block that is currently being parsed.
Definition ScopeInfo.h:104
bool UsesFPIntrin
Whether this function uses constrained floating point intrinsics.
Definition ScopeInfo.h:141
void addByrefBlockVar(VarDecl *VD)
Definition ScopeInfo.h:498
bool ObjCShouldCallSuper
A flag that is set when parsing a method that must call super's implementation, such as -dealloc,...
Definition ScopeInfo.h:150
bool ObjCWarnForNoInitDelegation
This starts true for a secondary initializer method and will be set to false if there is an invocatio...
Definition ScopeInfo.h:167
bool HasPotentialAvailabilityViolations
Whether we make reference to a declaration that could be unavailable.
Definition ScopeInfo.h:145
bool ObjCWarnForNoDesignatedInitChain
This starts true for a method marked as designated initializer and will be set to false if there is a...
Definition ScopeInfo.h:158
SourceRange IntroducerRange
Source range covering the lambda introducer [...].
Definition ScopeInfo.h:884
TemplateParameterList * GLTemplateParameterList
If this is a generic lambda, and the template parameter list has been created (from the TemplateParam...
Definition ScopeInfo.h:915
ParmVarDecl * ExplicitObjectParameter
Definition ScopeInfo.h:881
llvm::SmallVector< ShadowedOuterDecl, 4 > ShadowingDecls
Definition ScopeInfo.h:948
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition ScopeInfo.h:871
bool AfterParameterList
Indicate that we parsed the parameter list at which point the mutability of the lambda is known.
Definition ScopeInfo.h:879
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition ScopeInfo.h:874
bool Mutable
Whether this is a mutable lambda.
Definition ScopeInfo.h:896
Provides information about an attempted template argument deduction, whose success or failure was des...
#define bool
Definition gpuintrin.h:32
Defines the clang::TargetInfo interface.
Public enums and private classes that are part of the SourceManager implementation.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
unsigned kind
All of the diagnostics that can be emitted by the frontend.
constexpr bool isInitializedByPipeline(LangAS AS)
Definition HLSLRuntime.h:34
bool implicitObjectParamIsLifetimeBound(const FunctionDecl *FD)
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
bool randomizeStructureLayout(const ASTContext &Context, RecordDecl *RD, llvm::SmallVectorImpl< Decl * > &FinalOrdering)
The JSON file list parser is used to communicate input to InstallAPI.
bool FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI)
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
@ TST_struct
Definition Specifiers.h: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:822
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:818
@ Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition Sema.h:814
bool isa(CodeGen::Address addr)
Definition Address.h:330
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition Specifiers.h:212
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus11
@ CPlusPlus14
@ CPlusPlus17
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition Ownership.h:263
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition Overload.h:55
@ GVA_AvailableExternally
Definition Linkage.h:74
CUDAFunctionTarget
Definition Cuda.h:61
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition ASTLambda.h:102
int hasAttribute(AttributeCommonInfo::Syntax Syntax, llvm::StringRef ScopeName, llvm::StringRef AttrName, const TargetInfo &Target, const LangOptions &LangOpts, bool CheckPlugins)
Return the version number associated with the attribute if we recognize and implement the attribute s...
ConstexprSpecKind
Define the kind of constexpr specifier.
Definition Specifiers.h:35
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition Lookup.h:64
@ NotFound
No entity found met the criteria.
Definition Lookup.h:41
@ FoundOverloaded
Name lookup found a set of overloaded functions that met the criteria.
Definition Lookup.h:54
@ Found
Name lookup found a single declaration that met the criteria.
Definition Lookup.h:50
@ FoundUnresolvedValue
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition Lookup.h:59
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition Lookup.h:46
InClassInitStyle
In-class initialization styles for non-static data members.
Definition Specifiers.h:271
@ ICIS_NoInit
No in-class initializer.
Definition Specifiers.h:272
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
Definition Parser.h:61
OverloadCandidateDisplayKind
Definition Overload.h:64
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
Definition Overload.h:73
@ OCD_AllCandidates
Requests that all candidates be shown.
Definition Overload.h:67
std::pair< FileID, unsigned > FileIDAndOffset
@ LCK_ByRef
Capturing by reference.
Definition Lambda.h:37
@ LCK_StarThis
Capturing the *this object by copy.
Definition Lambda.h:35
NonTagKind
Common ways to introduce type names without a tag for use in diagnostics.
Definition Sema.h:604
@ TemplateTemplateArgument
Definition Sema.h:613
NonTrivialCUnionContext
Definition Sema.h:532
AvailabilityMergeKind
Describes the kind of merge to perform for availability attributes (including "deprecated",...
Definition Sema.h:628
@ None
Don't merge availability attributes at all.
Definition Sema.h:630
@ Override
Merge availability attributes for an override, which requires an exact match or a weakening of constr...
Definition Sema.h:636
@ OptionalProtocolImplementation
Merge availability attributes for an implementation of an optional protocol requirement.
Definition Sema.h:642
@ Redeclaration
Merge availability attributes for a redeclaration, which requires an exact match.
Definition Sema.h:633
@ ProtocolImplementation
Merge availability attributes for an implementation of a protocol requirement.
Definition Sema.h:639
@ IK_DeductionGuideName
A deduction-guide name (a template-name)
Definition DeclSpec.h:994
@ IK_ImplicitSelfParam
An implicit 'self' parameter.
Definition DeclSpec.h:992
@ IK_TemplateId
A template-id, e.g., f<int>.
Definition DeclSpec.h:990
@ IK_ConstructorTemplateId
A constructor named via a template-id.
Definition DeclSpec.h:986
@ IK_ConstructorName
A constructor name.
Definition DeclSpec.h:984
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
Definition DeclSpec.h:982
@ IK_Identifier
An identifier.
Definition DeclSpec.h:976
@ IK_DestructorName
A destructor name.
Definition DeclSpec.h:988
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
Definition DeclSpec.h:978
@ IK_ConversionFunctionId
A conversion function name, e.g., operator int.
Definition DeclSpec.h:980
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition Specifiers.h:123
@ AS_public
Definition Specifiers.h:124
@ AS_protected
Definition Specifiers.h:125
@ AS_none
Definition Specifiers.h:127
SmallVector< Attr *, 4 > AttrVec
AttrVec - A vector of Attr, which is how they are stored on the AST.
ActionResult< Decl * > DeclResult
Definition Ownership.h:255
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
bool DeclAttrsMatchCUDAMode(const LangOptions &LangOpts, Decl *D)
@ AmbiguousTagHiding
Name lookup results in an ambiguity because an entity with a tag name was hidden by an entity with an...
Definition Lookup.h:137
LanguageLinkage
Describes the different kinds of language linkage (C++ [dcl.link]) that an entity may have.
Definition Linkage.h:63
@ CLanguageLinkage
Definition Linkage.h:64
@ CXXLanguageLinkage
Definition Linkage.h:65
StorageClass
Storage classes.
Definition Specifiers.h:248
@ SC_Auto
Definition Specifiers.h:256
@ SC_PrivateExtern
Definition Specifiers.h:253
@ SC_Extern
Definition Specifiers.h:251
@ SC_Register
Definition Specifiers.h:257
@ SC_Static
Definition Specifiers.h:252
@ SC_None
Definition Specifiers.h:250
@ TSCS_thread_local
C++11 thread_local.
Definition Specifiers.h:241
@ TSCS_unspecified
Definition Specifiers.h:236
@ TSCS__Thread_local
C11 _Thread_local.
Definition Specifiers.h:244
@ TSCS___thread
GNU __thread.
Definition Specifiers.h:238
std::pair< NullabilityKind, bool > DiagNullabilityKind
A nullability kind paired with a bit indicating whether it used a context-sensitive keyword.
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
Definition Linkage.h:24
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition Linkage.h:35
@ External
External linkage, which indicates that the entity can be referred to from other translation units.
Definition Linkage.h:58
@ Module
Module linkage, which indicates that the entity can be referred to from other translation units withi...
Definition Linkage.h:54
TemplateDecl * getAsTypeTemplateDecl(Decl *D)
llvm::Expected< Decl * > ExpectedDecl
@ SD_Thread
Thread storage duration.
Definition Specifiers.h:342
@ SD_Static
Static storage duration.
Definition Specifiers.h:343
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition ASTLambda.h:28
@ Parameter
The parameter type of a method or function.
Definition TypeBase.h:908
@ Result
The result type of a method or function.
Definition TypeBase.h:905
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
OffsetOfKind
Definition Sema.h:616
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
const FunctionProtoType * T
bool supportsVariadicCall(CallingConv CC)
Checks whether the given calling convention supports variadic calls.
Definition Specifiers.h:319
@ Template
We are parsing a template declaration.
Definition Parser.h:81
TagUseKind
Definition Sema.h:451
TagTypeKind
The kind of a tag type.
Definition TypeBase.h:5893
@ Interface
The "__interface" keyword.
Definition TypeBase.h:5898
@ Struct
The "struct" keyword.
Definition TypeBase.h:5895
@ Class
The "class" keyword.
Definition TypeBase.h:5904
@ Union
The "union" keyword.
Definition TypeBase.h:5901
@ Enum
The "enum" keyword.
Definition TypeBase.h:5907
LLVM_READONLY bool isWhitespace(unsigned char c)
Return true if this character is horizontal or vertical ASCII whitespace: ' ', '\t',...
Definition CharInfo.h:108
bool isDiscardableGVALinkage(GVALinkage L)
Definition Linkage.h:80
ExprResult ExprError()
Definition Ownership.h:265
LangAS
Defines the address space values used by the address space qualifier of QualType.
@ CanNeverPassInRegs
The argument of this type cannot be passed directly in registers.
Definition Decl.h:4317
@ 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:427
@ TNK_Type_template
The name refers to a template whose specialization produces a type.
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
LambdaCaptureDefault
The default, if any, capture method for a lambda expression.
Definition Lambda.h:22
@ LCD_ByRef
Definition Lambda.h:25
@ LCD_None
Definition Lambda.h:23
@ LCD_ByCopy
Definition Lambda.h:24
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:135
MultiVersionKind
Definition Decl.h:1979
bool isExternalFormalLinkage(Linkage L)
Definition Linkage.h:117
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1288
TemplateDeductionResult
Describes the result of template argument deduction.
Definition Sema.h:369
@ Success
Template argument deduction was successful.
Definition Sema.h:371
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:423
const StreamingDiagnostic & operator<<(const StreamingDiagnostic &DB, const ConceptReference *C)
Insertion operator for diagnostics.
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:188
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition Specifiers.h:206
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:202
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:198
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:194
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:191
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:278
@ CC_X86StdCall
Definition Specifiers.h:280
U cast(CodeGen::Address addr)
Definition Address.h:327
@ None
The alignment was not explicit in code.
Definition ASTContext.h:178
@ Enumerator
Enumerator value with fixed underlying type.
Definition Sema.h:828
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition Ownership.h:230
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5889
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5879
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5882
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition TypeBase.h:5886
ReservedIdentifierStatus
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Other
Other implicit parameter.
Definition Decl.h:1746
@ EST_None
no exception specification
@ EST_BasicNoexcept
noexcept
@ HiddenVisibility
Objects with "hidden" visibility are not seen by the dynamic linker.
Definition Visibility.h:37
ActionResult< Stmt * > StmtResult
Definition Ownership.h:250
bool isGenericLambdaCallOperatorSpecialization(const CXXMethodDecl *MD)
Definition ASTLambda.h:60
const Expr * ConstraintExpr
Definition Decl.h:88
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
DeclarationName getName() const
getName - Returns the embedded declaration name.
void setLoc(SourceLocation L)
setLoc - Sets the main location of the declaration name.
void setCXXLiteralOperatorNameLoc(SourceLocation Loc)
setCXXLiteralOperatorNameLoc - Sets the location of the literal operator name (not the operator keywo...
void setNamedTypeInfo(TypeSourceInfo *TInfo)
setNamedTypeInfo - Sets the source type info associated to the name.
void setCXXOperatorNameRange(SourceRange R)
setCXXOperatorNameRange - Sets the range of the operator name (without the operator keyword).
SourceRange getCXXOperatorNameRange() const
getCXXOperatorNameRange - Gets the range of the operator name (without the operator keyword).
void setName(DeclarationName N)
setName - Sets the embedded declaration name.
ParamInfo * Params
Params - This is a pointer to a new[]'d array of ParamInfo objects that describe the parameters speci...
Definition DeclSpec.h:1398
ArrayRef< NamedDecl * > getDeclsInPrototype() const
Get the non-parameter decls defined within this function prototype.
Definition DeclSpec.h:1549
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition DeclSpec.h:1373
unsigned hasPrototype
hasPrototype - This is true if the function had at least one typed parameter.
Definition DeclSpec.h:1332
const IdentifierInfo * Ident
Definition DeclSpec.h:1304
One instance of this struct is used for each type in a declarator that is parsed.
Definition DeclSpec.h:1221
const ParsedAttributesView & getAttrs() const
If there are attributes applied to this declaratorchunk, return them.
Definition DeclSpec.h:1633
static DeclaratorChunk getFunction(bool HasProto, bool IsAmbiguous, SourceLocation LParenLoc, ParamInfo *Params, unsigned NumParams, SourceLocation EllipsisLoc, SourceLocation RParenLoc, bool RefQualifierIsLvalueRef, SourceLocation RefQualifierLoc, SourceLocation MutableLoc, ExceptionSpecificationType ESpecType, SourceRange ESpecRange, ParsedType *Exceptions, SourceRange *ExceptionRanges, unsigned NumExceptions, Expr *NoexceptExpr, CachedTokens *ExceptionSpecTokens, ArrayRef< NamedDecl * > DeclsInPrototype, SourceLocation LocalRangeBegin, SourceLocation LocalRangeEnd, Declarator &TheDeclarator, TypeResult TrailingReturnType=TypeResult(), SourceLocation TrailingReturnTypeLoc=SourceLocation(), DeclSpec *MethodQualifiers=nullptr)
DeclaratorChunk::getFunction - Return a DeclaratorChunk for a function.
Definition DeclSpec.cpp:132
MemberPointerTypeInfo Mem
Definition DeclSpec.h:1614
FunctionTypeInfo Fun
Definition DeclSpec.h:1612
enum clang::DeclaratorChunk::@340323374315200305336204205154073066142310370142 Kind
static DeclaratorChunk getReference(unsigned TypeQuals, SourceLocation Loc, bool lvalue)
Return a DeclaratorChunk for a reference.
Definition DeclSpec.h:1657
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:645
Extra information about a function prototype.
Definition TypeBase.h:5354
ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI)
Definition TypeBase.h:5381
static StringRef getTagTypeKindName(TagTypeKind Kind)
Definition TypeBase.h:5932
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition Type.cpp:3241
Contains information gathered from parsing the contents of TargetAttr.
Definition TargetInfo.h:60
std::vector< std::string > Features
Definition TargetInfo.h:61
Describes how types, statements, expressions, and declarations should be printed.
ValueType CurrentValue
Definition Sema.h:2018
SourceLocation CurrentPragmaLocation
Definition Sema.h:2019
bool CheckSameAsPrevious
Definition Sema.h:355
NamedDecl * Previous
Definition Sema.h:356
NamedDecl * New
Definition Sema.h:357
Information about a template-id annotation token.
const IdentifierInfo * Name
FIXME: Temporarily stores the name of a specialization.
unsigned NumArgs
NumArgs - The number of template arguments.
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
SourceLocation LAngleLoc
The location of the '<' before the template argument list.
SourceLocation TemplateKWLoc
TemplateKWLoc - The location of the template keyword.
ParsedTemplateTy Template
The declaration of the template corresponding to the template-name.
OpaquePtr< T > get() const
Definition Ownership.h:105
SourceLocation SymbolLocations[3]
The source locations of the individual tokens that name the operator, e.g., the "new",...
Definition DeclSpec.h:1018
OverloadedOperatorKind Operator
The kind of overloaded operator.
Definition DeclSpec.h:1009