Thanks to visit codestin.com
Credit goes to clang.llvm.org

clang 22.0.0git
SemaDecl.cpp
Go to the documentation of this file.
1//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for declarations.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TypeLocBuilder.h"
16#include "clang/AST/ASTLambda.h"
18#include "clang/AST/CharUnits.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclObjC.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
29#include "clang/AST/StmtCXX.h"
30#include "clang/AST/Type.h"
36#include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
37#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
38#include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
39#include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
41#include "clang/Sema/DeclSpec.h"
44#include "clang/Sema/Lookup.h"
46#include "clang/Sema/Scope.h"
48#include "clang/Sema/SemaARM.h"
49#include "clang/Sema/SemaCUDA.h"
50#include "clang/Sema/SemaHLSL.h"
52#include "clang/Sema/SemaObjC.h"
55#include "clang/Sema/SemaPPC.h"
57#include "clang/Sema/SemaSYCL.h"
59#include "clang/Sema/SemaWasm.h"
60#include "clang/Sema/Template.h"
61#include "llvm/ADT/STLForwardCompat.h"
62#include "llvm/ADT/SmallPtrSet.h"
63#include "llvm/ADT/SmallString.h"
64#include "llvm/ADT/StringExtras.h"
65#include "llvm/Support/SaveAndRestore.h"
66#include "llvm/TargetParser/Triple.h"
67#include <algorithm>
68#include <cstring>
69#include <optional>
70#include <unordered_map>
71
72using namespace clang;
73using namespace sema;
74
76 if (OwnedType) {
77 Decl *Group[2] = { OwnedType, Ptr };
79 }
80
82}
83
84namespace {
85
86class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
87 public:
88 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
89 bool AllowTemplates = false,
90 bool AllowNonTemplates = true)
91 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
92 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
93 WantExpressionKeywords = false;
94 WantCXXNamedCasts = false;
95 WantRemainingKeywords = false;
96 }
97
98 bool ValidateCandidate(const TypoCorrection &candidate) override {
99 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
100 if (!AllowInvalidDecl && ND->isInvalidDecl())
101 return false;
102
103 if (getAsTypeTemplateDecl(ND))
104 return AllowTemplates;
105
106 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
107 if (!IsType)
108 return false;
109
110 if (AllowNonTemplates)
111 return true;
112
113 // An injected-class-name of a class template (specialization) is valid
114 // as a template or as a non-template.
115 if (AllowTemplates) {
116 auto *RD = dyn_cast<CXXRecordDecl>(ND);
117 if (!RD || !RD->isInjectedClassName())
118 return false;
119 RD = cast<CXXRecordDecl>(RD->getDeclContext());
120 return RD->getDescribedClassTemplate() ||
122 }
123
124 return false;
125 }
126
127 return !WantClassName && candidate.isKeyword();
128 }
129
130 std::unique_ptr<CorrectionCandidateCallback> clone() override {
131 return std::make_unique<TypeNameValidatorCCC>(*this);
132 }
133
134 private:
135 bool AllowInvalidDecl;
136 bool WantClassName;
137 bool AllowTemplates;
138 bool AllowNonTemplates;
139};
140
141} // end anonymous namespace
142
144 TypeDecl *TD, SourceLocation NameLoc) {
145 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
146 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
147 if (DCK != DiagCtorKind::None && LookupRD && FoundRD &&
148 FoundRD->isInjectedClassName() &&
149 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) {
150 Diag(NameLoc,
152 ? diag::ext_out_of_line_qualified_id_type_names_constructor
153 : diag::err_out_of_line_qualified_id_type_names_constructor)
154 << TD->getIdentifier() << /*Type=*/1
155 << 0 /*if any keyword was present, it was 'typename'*/;
156 }
157
158 DiagnoseUseOfDecl(TD, NameLoc);
159 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
160}
161
162namespace {
163enum class UnqualifiedTypeNameLookupResult {
164 NotFound,
165 FoundNonType,
166 FoundType
167};
168} // end anonymous namespace
169
170/// Tries to perform unqualified lookup of the type decls in bases for
171/// dependent class.
172/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
173/// type decl, \a FoundType if only type decls are found.
174static UnqualifiedTypeNameLookupResult
176 SourceLocation NameLoc,
177 const CXXRecordDecl *RD) {
178 if (!RD->hasDefinition())
179 return UnqualifiedTypeNameLookupResult::NotFound;
180 // Look for type decls in base classes.
181 UnqualifiedTypeNameLookupResult FoundTypeDecl =
182 UnqualifiedTypeNameLookupResult::NotFound;
183 for (const auto &Base : RD->bases()) {
184 const CXXRecordDecl *BaseRD = Base.getType()->getAsCXXRecordDecl();
185 if (BaseRD) {
186 } else if (auto *TST = dyn_cast<TemplateSpecializationType>(
187 Base.getType().getCanonicalType())) {
188 // Look for type decls in dependent base classes that have known primary
189 // templates.
190 if (!TST->isDependentType())
191 continue;
192 auto *TD = TST->getTemplateName().getAsTemplateDecl();
193 if (!TD)
194 continue;
195 if (auto *BasePrimaryTemplate =
196 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
197 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
198 BaseRD = BasePrimaryTemplate;
199 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
201 CTD->findPartialSpecialization(Base.getType()))
202 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
203 BaseRD = PS;
204 }
205 }
206 }
207 if (BaseRD) {
208 for (NamedDecl *ND : BaseRD->lookup(&II)) {
209 if (!isa<TypeDecl>(ND))
210 return UnqualifiedTypeNameLookupResult::FoundNonType;
211 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
212 }
213 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
214 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
215 case UnqualifiedTypeNameLookupResult::FoundNonType:
216 return UnqualifiedTypeNameLookupResult::FoundNonType;
217 case UnqualifiedTypeNameLookupResult::FoundType:
218 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
219 break;
220 case UnqualifiedTypeNameLookupResult::NotFound:
221 break;
222 }
223 }
224 }
225 }
226
227 return FoundTypeDecl;
228}
229
231 const IdentifierInfo &II,
232 SourceLocation NameLoc) {
233 // Lookup in the parent class template context, if any.
234 const CXXRecordDecl *RD = nullptr;
235 UnqualifiedTypeNameLookupResult FoundTypeDecl =
236 UnqualifiedTypeNameLookupResult::NotFound;
237 for (DeclContext *DC = S.CurContext;
238 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
239 DC = DC->getParent()) {
240 // Look for type decls in dependent base classes that have known primary
241 // templates.
242 RD = dyn_cast<CXXRecordDecl>(DC);
243 if (RD && RD->getDescribedClassTemplate())
244 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
245 }
246 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
247 return nullptr;
248
249 // We found some types in dependent base classes. Recover as if the user
250 // wrote 'MyClass::II' instead of 'II', and this implicit typename was
251 // allowed. We'll fully resolve the lookup during template instantiation.
252 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
253
254 ASTContext &Context = S.Context;
255 NestedNameSpecifier NNS(Context.getCanonicalTagType(RD).getTypePtr());
256 QualType T =
257 Context.getDependentNameType(ElaboratedTypeKeyword::None, NNS, &II);
258
259 CXXScopeSpec SS;
260 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
261
262 TypeLocBuilder Builder;
263 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
264 DepTL.setNameLoc(NameLoc);
266 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
267 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
268}
269
271 Scope *S, CXXScopeSpec *SS, bool isClassName,
272 bool HasTrailingDot, ParsedType ObjectTypePtr,
273 bool IsCtorOrDtorName,
274 bool WantNontrivialTypeSourceInfo,
275 bool IsClassTemplateDeductionContext,
276 ImplicitTypenameContext AllowImplicitTypename,
277 IdentifierInfo **CorrectedII) {
278 bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
279 // FIXME: Consider allowing this outside C++1z mode as an extension.
280 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
281 getLangOpts().CPlusPlus17 && IsImplicitTypename &&
282 !HasTrailingDot;
283
284 // Determine where we will perform name lookup.
285 DeclContext *LookupCtx = nullptr;
286 if (ObjectTypePtr) {
287 QualType ObjectType = ObjectTypePtr.get();
288 if (ObjectType->isRecordType())
289 LookupCtx = computeDeclContext(ObjectType);
290 } else if (SS && SS->isNotEmpty()) {
291 LookupCtx = computeDeclContext(*SS, false);
292
293 if (!LookupCtx) {
294 if (isDependentScopeSpecifier(*SS)) {
295 // C++ [temp.res]p3:
296 // A qualified-id that refers to a type and in which the
297 // nested-name-specifier depends on a template-parameter (14.6.2)
298 // shall be prefixed by the keyword typename to indicate that the
299 // qualified-id denotes a type, forming an
300 // elaborated-type-specifier (7.1.5.3).
301 //
302 // We therefore do not perform any name lookup if the result would
303 // refer to a member of an unknown specialization.
304 // In C++2a, in several contexts a 'typename' is not required. Also
305 // allow this as an extension.
306 if (IsImplicitTypename) {
307 if (AllowImplicitTypename == ImplicitTypenameContext::No)
308 return nullptr;
309 SourceLocation QualifiedLoc = SS->getRange().getBegin();
310 // FIXME: Defer the diagnostic after we build the type and use it.
311 auto DB = DiagCompat(QualifiedLoc, diag_compat::implicit_typename)
312 << Context.getDependentNameType(ElaboratedTypeKeyword::None,
313 SS->getScopeRep(), &II);
315 DB << FixItHint::CreateInsertion(QualifiedLoc, "typename ");
316 }
317
318 // We know from the grammar that this name refers to a type,
319 // so build a dependent node to describe the type.
320 if (WantNontrivialTypeSourceInfo)
321 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc,
322 (ImplicitTypenameContext)IsImplicitTypename)
323 .get();
324
327 IsImplicitTypename ? ElaboratedTypeKeyword::Typename
329 SourceLocation(), QualifierLoc, II, NameLoc);
330 return ParsedType::make(T);
331 }
332
333 return nullptr;
334 }
335
336 if (!LookupCtx->isDependentContext() &&
337 RequireCompleteDeclContext(*SS, LookupCtx))
338 return nullptr;
339 }
340
341 // In the case where we know that the identifier is a class name, we know that
342 // it is a type declaration (struct, class, union or enum) so we can use tag
343 // name lookup.
344 //
345 // C++ [class.derived]p2 (wrt lookup in a base-specifier): The lookup for
346 // the component name of the type-name or simple-template-id is type-only.
347 LookupNameKind Kind = isClassName ? LookupTagName : LookupOrdinaryName;
348 LookupResult Result(*this, &II, NameLoc, Kind);
349 if (LookupCtx) {
350 // Perform "qualified" name lookup into the declaration context we
351 // computed, which is either the type of the base of a member access
352 // expression or the declaration context associated with a prior
353 // nested-name-specifier.
354 LookupQualifiedName(Result, LookupCtx);
355
356 if (ObjectTypePtr && Result.empty()) {
357 // C++ [basic.lookup.classref]p3:
358 // If the unqualified-id is ~type-name, the type-name is looked up
359 // in the context of the entire postfix-expression. If the type T of
360 // the object expression is of a class type C, the type-name is also
361 // looked up in the scope of class C. At least one of the lookups shall
362 // find a name that refers to (possibly cv-qualified) T.
363 LookupName(Result, S);
364 }
365 } else {
366 // Perform unqualified name lookup.
367 LookupName(Result, S);
368
369 // For unqualified lookup in a class template in MSVC mode, look into
370 // dependent base classes where the primary class template is known.
371 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
372 if (ParsedType TypeInBase =
373 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
374 return TypeInBase;
375 }
376 }
377
378 NamedDecl *IIDecl = nullptr;
379 UsingShadowDecl *FoundUsingShadow = nullptr;
380 switch (Result.getResultKind()) {
382 if (CorrectedII) {
383 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
384 AllowDeducedTemplate);
385 TypoCorrection Correction =
386 CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS, CCC,
388 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
390 bool MemberOfUnknownSpecialization;
392 TemplateName.setIdentifier(NewII, NameLoc);
394 CXXScopeSpec NewSS, *NewSSPtr = SS;
395 if (SS && NNS) {
396 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
397 NewSSPtr = &NewSS;
398 }
399 if (Correction && (NNS || NewII != &II) &&
400 // Ignore a correction to a template type as the to-be-corrected
401 // identifier is not a template (typo correction for template names
402 // is handled elsewhere).
403 !(getLangOpts().CPlusPlus && NewSSPtr &&
404 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
405 Template, MemberOfUnknownSpecialization))) {
406 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
407 isClassName, HasTrailingDot, ObjectTypePtr,
408 IsCtorOrDtorName,
409 WantNontrivialTypeSourceInfo,
410 IsClassTemplateDeductionContext);
411 if (Ty) {
412 diagnoseTypo(Correction,
413 PDiag(diag::err_unknown_type_or_class_name_suggest)
414 << Result.getLookupName() << isClassName);
415 if (SS && NNS)
416 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
417 *CorrectedII = NewII;
418 return Ty;
419 }
420 }
421 }
422 Result.suppressDiagnostics();
423 return nullptr;
425 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
426 QualType T = Context.getDependentNameType(ElaboratedTypeKeyword::None,
427 SS->getScopeRep(), &II);
428 TypeLocBuilder TLB;
432 TL.setNameLoc(NameLoc);
434 }
435 [[fallthrough]];
438 Result.suppressDiagnostics();
439 return nullptr;
440
442 // Recover from type-hiding ambiguities by hiding the type. We'll
443 // do the lookup again when looking for an object, and we can
444 // diagnose the error then. If we don't do this, then the error
445 // about hiding the type will be immediately followed by an error
446 // that only makes sense if the identifier was treated like a type.
447 if (Result.getAmbiguityKind() == LookupAmbiguityKind::AmbiguousTagHiding) {
448 Result.suppressDiagnostics();
449 return nullptr;
450 }
451
452 // Look to see if we have a type anywhere in the list of results.
453 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
454 Res != ResEnd; ++Res) {
455 NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
457 RealRes) ||
458 (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
459 if (!IIDecl ||
460 // Make the selection of the recovery decl deterministic.
461 RealRes->getLocation() < IIDecl->getLocation()) {
462 IIDecl = RealRes;
463 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
464 }
465 }
466 }
467
468 if (!IIDecl) {
469 // None of the entities we found is a type, so there is no way
470 // to even assume that the result is a type. In this case, don't
471 // complain about the ambiguity. The parser will either try to
472 // perform this lookup again (e.g., as an object name), which
473 // will produce the ambiguity, or will complain that it expected
474 // a type name.
475 Result.suppressDiagnostics();
476 return nullptr;
477 }
478
479 // We found a type within the ambiguous lookup; diagnose the
480 // ambiguity and then return that type. This might be the right
481 // answer, or it might not be, but it suppresses any attempt to
482 // perform the name lookup again.
483 break;
484
486 IIDecl = Result.getFoundDecl();
487 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
488 break;
489 }
490
491 assert(IIDecl && "Didn't find decl");
492
493 TypeLocBuilder TLB;
494 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
495 checkTypeDeclType(LookupCtx,
496 IsImplicitTypename ? DiagCtorKind::Implicit
498 TD, NameLoc);
499 QualType T;
500 if (FoundUsingShadow) {
502 SS ? SS->getScopeRep() : std::nullopt,
503 FoundUsingShadow);
504 if (!WantNontrivialTypeSourceInfo)
505 return ParsedType::make(T);
506 TLB.push<UsingTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),
509 NameLoc);
510 } else if (auto *Tag = dyn_cast<TagDecl>(TD)) {
512 SS ? SS->getScopeRep() : std::nullopt, Tag,
513 /*OwnsTag=*/false);
514 if (!WantNontrivialTypeSourceInfo)
515 return ParsedType::make(T);
516 auto TL = TLB.push<TagTypeLoc>(T);
518 TL.setQualifierLoc(SS ? SS->getWithLocInContext(Context)
520 TL.setNameLoc(NameLoc);
521 } else if (auto *TN = dyn_cast<TypedefNameDecl>(TD);
522 TN && !isa<ObjCTypeParamDecl>(TN)) {
523 T = Context.getTypedefType(ElaboratedTypeKeyword::None,
524 SS ? SS->getScopeRep() : std::nullopt, TN);
525 if (!WantNontrivialTypeSourceInfo)
526 return ParsedType::make(T);
527 TLB.push<TypedefTypeLoc>(T).set(
528 /*ElaboratedKeywordLoc=*/SourceLocation(),
530 NameLoc);
531 } else if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(TD)) {
532 T = Context.getUnresolvedUsingType(ElaboratedTypeKeyword::None,
533 SS ? SS->getScopeRep() : std::nullopt,
534 UD);
535 if (!WantNontrivialTypeSourceInfo)
536 return ParsedType::make(T);
537 TLB.push<UnresolvedUsingTypeLoc>(T).set(
538 /*ElaboratedKeywordLoc=*/SourceLocation(),
540 NameLoc);
541 } else {
542 T = Context.getTypeDeclType(TD);
543 if (!WantNontrivialTypeSourceInfo)
544 return ParsedType::make(T);
546 TLB.push<ObjCTypeParamTypeLoc>(T).setNameLoc(NameLoc);
547 else
548 TLB.pushTypeSpec(T).setNameLoc(NameLoc);
549 }
551 }
552 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
553 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
554 if (!HasTrailingDot) {
555 // FIXME: Support UsingType for this case.
556 QualType T = Context.getObjCInterfaceType(IDecl);
557 if (!WantNontrivialTypeSourceInfo)
558 return ParsedType::make(T);
559 auto TL = TLB.push<ObjCInterfaceTypeLoc>(T);
560 TL.setNameLoc(NameLoc);
561 // FIXME: Pass in this source location.
562 TL.setNameEndLoc(NameLoc);
564 }
565 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
566 (void)DiagnoseUseOfDecl(UD, NameLoc);
567 // Recover with 'int'
568 return ParsedType::make(Context.IntTy);
569 } else if (AllowDeducedTemplate) {
570 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
571 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
572 // FIXME: Support UsingType here.
573 TemplateName Template = Context.getQualifiedTemplateName(
574 SS ? SS->getScopeRep() : std::nullopt, /*TemplateKeyword=*/false,
575 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
576 QualType T = Context.getDeducedTemplateSpecializationType(
580 TL.setNameLoc(NameLoc);
581 TL.setQualifierLoc(SS ? SS->getWithLocInContext(Context)
584 }
585 }
586
587 // As it's not plausibly a type, suppress diagnostics.
588 Result.suppressDiagnostics();
589 return nullptr;
590}
591
592// Builds a fake NNS for the given decl context.
595 for (;; DC = DC->getLookupParent()) {
596 DC = DC->getPrimaryContext();
597 auto *ND = dyn_cast<NamespaceDecl>(DC);
598 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
599 return NestedNameSpecifier(Context, ND, std::nullopt);
600 if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
601 return NestedNameSpecifier(Context.getCanonicalTagType(RD)->getTypePtr());
604 }
605 llvm_unreachable("something isn't in TU scope?");
606}
607
608/// Find the parent class with dependent bases of the innermost enclosing method
609/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
610/// up allowing unqualified dependent type names at class-level, which MSVC
611/// correctly rejects.
612static const CXXRecordDecl *
614 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
615 DC = DC->getPrimaryContext();
616 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
617 if (MD->getParent()->hasAnyDependentBases())
618 return MD->getParent();
619 }
620 return nullptr;
621}
622
624 SourceLocation NameLoc,
625 bool IsTemplateTypeArg) {
626 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
627
628 NestedNameSpecifier NNS = std::nullopt;
629 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
630 // If we weren't able to parse a default template argument, delay lookup
631 // until instantiation time by making a non-dependent DependentTypeName. We
632 // pretend we saw a NestedNameSpecifier referring to the current scope, and
633 // lookup is retried.
634 // FIXME: This hurts our diagnostic quality, since we get errors like "no
635 // type named 'Foo' in 'current_namespace'" when the user didn't write any
636 // name specifiers.
638 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
639 } else if (const CXXRecordDecl *RD =
641 // Build a DependentNameType that will perform lookup into RD at
642 // instantiation time.
643 NNS = NestedNameSpecifier(Context.getCanonicalTagType(RD)->getTypePtr());
644
645 // Diagnose that this identifier was undeclared, and retry the lookup during
646 // template instantiation.
647 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
648 << RD;
649 } else {
650 // This is not a situation that we should recover from.
651 return ParsedType();
652 }
653
654 QualType T =
655 Context.getDependentNameType(ElaboratedTypeKeyword::None, NNS, &II);
656
657 // Build type location information. We synthesized the qualifier, so we have
658 // to build a fake NestedNameSpecifierLoc.
659 NestedNameSpecifierLocBuilder NNSLocBuilder;
660 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
661 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
662
663 TypeLocBuilder Builder;
664 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
665 DepTL.setNameLoc(NameLoc);
667 DepTL.setQualifierLoc(QualifierLoc);
668 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
669}
670
672 // Do a tag name lookup in this scope.
673 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
674 LookupName(R, S, false);
677 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
678 switch (TD->getTagKind()) {
684 return DeclSpec::TST_union;
686 return DeclSpec::TST_class;
688 return DeclSpec::TST_enum;
689 }
690 }
691
693}
694
696 if (!CurContext->isRecord())
697 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
698
699 switch (SS->getScopeRep().getKind()) {
701 return true;
703 QualType T(SS->getScopeRep().getAsType(), 0);
704 for (const auto &Base : cast<CXXRecordDecl>(CurContext)->bases())
705 if (Context.hasSameUnqualifiedType(T, Base.getType()))
706 return true;
707 [[fallthrough]];
708 }
709 default:
710 return S->isFunctionPrototypeScope();
711 }
712}
713
715 SourceLocation IILoc,
716 Scope *S,
717 CXXScopeSpec *SS,
718 ParsedType &SuggestedType,
719 bool IsTemplateName) {
720 // Don't report typename errors for editor placeholders.
721 if (II->isEditorPlaceholder())
722 return;
723 // We don't have anything to suggest (yet).
724 SuggestedType = nullptr;
725
726 // There may have been a typo in the name of the type. Look up typo
727 // results, in case we have something that we can suggest.
728 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
729 /*AllowTemplates=*/IsTemplateName,
730 /*AllowNonTemplates=*/!IsTemplateName);
731 if (TypoCorrection Corrected =
734 // FIXME: Support error recovery for the template-name case.
735 bool CanRecover = !IsTemplateName;
736 if (Corrected.isKeyword()) {
737 // We corrected to a keyword.
738 diagnoseTypo(Corrected,
739 PDiag(IsTemplateName ? diag::err_no_template_suggest
740 : diag::err_unknown_typename_suggest)
741 << II);
742 II = Corrected.getCorrectionAsIdentifierInfo();
743 } else {
744 // We found a similarly-named type or interface; suggest that.
745 if (!SS || !SS->isSet()) {
746 diagnoseTypo(Corrected,
747 PDiag(IsTemplateName ? diag::err_no_template_suggest
748 : diag::err_unknown_typename_suggest)
749 << II, CanRecover);
750 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
751 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
752 bool DroppedSpecifier =
753 Corrected.WillReplaceSpecifier() && II->getName() == CorrectedStr;
754 diagnoseTypo(Corrected,
755 PDiag(IsTemplateName
756 ? diag::err_no_member_template_suggest
757 : diag::err_unknown_nested_typename_suggest)
758 << II << DC << DroppedSpecifier << SS->getRange(),
759 CanRecover);
760 } else {
761 llvm_unreachable("could not have corrected a typo here");
762 }
763
764 if (!CanRecover)
765 return;
766
767 CXXScopeSpec tmpSS;
768 if (Corrected.getCorrectionSpecifier())
769 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
770 SourceRange(IILoc));
771 // FIXME: Support class template argument deduction here.
772 SuggestedType =
773 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
774 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
775 /*IsCtorOrDtorName=*/false,
776 /*WantNontrivialTypeSourceInfo=*/true);
777 }
778 return;
779 }
780
781 if (getLangOpts().CPlusPlus && !IsTemplateName) {
782 // See if II is a class template that the user forgot to pass arguments to.
783 UnqualifiedId Name;
784 Name.setIdentifier(II, IILoc);
785 CXXScopeSpec EmptySS;
786 TemplateTy TemplateResult;
787 bool MemberOfUnknownSpecialization;
788 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
789 Name, nullptr, true, TemplateResult,
790 MemberOfUnknownSpecialization) == TNK_Type_template) {
791 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
792 return;
793 }
794 }
795
796 // FIXME: Should we move the logic that tries to recover from a missing tag
797 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
798
799 if (!SS || (!SS->isSet() && !SS->isInvalid()))
800 Diag(IILoc, IsTemplateName ? diag::err_no_template
801 : diag::err_unknown_typename)
802 << II;
803 else if (DeclContext *DC = computeDeclContext(*SS, false))
804 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
805 : diag::err_typename_nested_not_found)
806 << II << DC << SS->getRange();
807 else if (SS->isValid() && SS->getScopeRep().containsErrors()) {
808 SuggestedType =
809 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
810 } else if (isDependentScopeSpecifier(*SS)) {
811 unsigned DiagID = diag::err_typename_missing;
812 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
813 DiagID = diag::ext_typename_missing;
814
815 SuggestedType =
816 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
817
818 Diag(SS->getRange().getBegin(), DiagID)
819 << GetTypeFromParser(SuggestedType)
820 << SourceRange(SS->getRange().getBegin(), IILoc)
821 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
822 } else {
823 assert(SS && SS->isInvalid() &&
824 "Invalid scope specifier has already been diagnosed");
825 }
826}
827
828/// Determine whether the given result set contains either a type name
829/// or
830static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
831 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
832 NextToken.is(tok::less);
833
834 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
836 return true;
837
838 if (CheckTemplate && isa<TemplateDecl>(*I))
839 return true;
840 }
841
842 return false;
843}
844
845static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
846 Scope *S, CXXScopeSpec &SS,
847 IdentifierInfo *&Name,
848 SourceLocation NameLoc) {
849 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
850 SemaRef.LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
851 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
852 StringRef FixItTagName;
853 switch (Tag->getTagKind()) {
855 FixItTagName = "class ";
856 break;
857
859 FixItTagName = "enum ";
860 break;
861
863 FixItTagName = "struct ";
864 break;
865
867 FixItTagName = "__interface ";
868 break;
869
871 FixItTagName = "union ";
872 break;
873 }
874
875 StringRef TagName = FixItTagName.drop_back();
876 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
877 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
878 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
879
880 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
881 I != IEnd; ++I)
882 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
883 << Name << TagName;
884
885 // Replace lookup results with just the tag decl.
886 Result.clear(Sema::LookupTagName);
887 SemaRef.LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType());
888 return true;
889 }
890
891 return false;
892}
893
895 IdentifierInfo *&Name,
896 SourceLocation NameLoc,
897 const Token &NextToken,
899 DeclarationNameInfo NameInfo(Name, NameLoc);
900 ObjCMethodDecl *CurMethod = getCurMethodDecl();
901
902 assert(NextToken.isNot(tok::coloncolon) &&
903 "parse nested name specifiers before calling ClassifyName");
904 if (getLangOpts().CPlusPlus && SS.isSet() &&
905 isCurrentClassName(*Name, S, &SS)) {
906 // Per [class.qual]p2, this names the constructors of SS, not the
907 // injected-class-name. We don't have a classification for that.
908 // There's not much point caching this result, since the parser
909 // will reject it later.
911 }
912
913 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
914 LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType(),
915 /*AllowBuiltinCreation=*/!CurMethod);
916
917 if (SS.isInvalid())
919
920 // For unqualified lookup in a class template in MSVC mode, look into
921 // dependent base classes where the primary class template is known.
922 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
923 if (ParsedType TypeInBase =
924 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
925 return TypeInBase;
926 }
927
928 // Perform lookup for Objective-C instance variables (including automatically
929 // synthesized instance variables), if we're in an Objective-C method.
930 // FIXME: This lookup really, really needs to be folded in to the normal
931 // unqualified lookup mechanism.
932 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
933 DeclResult Ivar = ObjC().LookupIvarInObjCMethod(Result, S, Name);
934 if (Ivar.isInvalid())
936 if (Ivar.isUsable())
938
939 // We defer builtin creation until after ivar lookup inside ObjC methods.
940 if (Result.empty())
942 }
943
944 bool SecondTry = false;
945 bool IsFilteredTemplateName = false;
946
947Corrected:
948 switch (Result.getResultKind()) {
950 // If an unqualified-id is followed by a '(', then we have a function
951 // call.
952 if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
953 // In C++, this is an ADL-only call.
954 // FIXME: Reference?
957
958 // C90 6.3.2.2:
959 // If the expression that precedes the parenthesized argument list in a
960 // function call consists solely of an identifier, and if no
961 // declaration is visible for this identifier, the identifier is
962 // implicitly declared exactly as if, in the innermost block containing
963 // the function call, the declaration
964 //
965 // extern int identifier ();
966 //
967 // appeared.
968 //
969 // We also allow this in C99 as an extension. However, this is not
970 // allowed in all language modes as functions without prototypes may not
971 // be supported.
972 if (getLangOpts().implicitFunctionsAllowed()) {
973 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
975 }
976 }
977
978 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
979 // In C++20 onwards, this could be an ADL-only call to a function
980 // template, and we're required to assume that this is a template name.
981 //
982 // FIXME: Find a way to still do typo correction in this case.
984 Context.getAssumedTemplateName(NameInfo.getName());
986 }
987
988 // In C, we first see whether there is a tag type by the same name, in
989 // which case it's likely that the user just forgot to write "enum",
990 // "struct", or "union".
991 if (!getLangOpts().CPlusPlus && !SecondTry &&
992 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
993 break;
994 }
995
996 // Perform typo correction to determine if there is another name that is
997 // close to this name.
998 if (!SecondTry && CCC) {
999 SecondTry = true;
1000 if (TypoCorrection Corrected =
1001 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
1002 &SS, *CCC, CorrectTypoKind::ErrorRecovery)) {
1003 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
1004 unsigned QualifiedDiag = diag::err_no_member_suggest;
1005
1006 NamedDecl *FirstDecl = Corrected.getFoundDecl();
1007 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
1008 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1009 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
1010 UnqualifiedDiag = diag::err_no_template_suggest;
1011 QualifiedDiag = diag::err_no_member_template_suggest;
1012 } else if (UnderlyingFirstDecl &&
1013 (isa<TypeDecl>(UnderlyingFirstDecl) ||
1014 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
1015 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
1016 UnqualifiedDiag = diag::err_unknown_typename_suggest;
1017 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
1018 }
1019
1020 if (SS.isEmpty()) {
1021 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
1022 } else {// FIXME: is this even reachable? Test it.
1023 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1024 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
1025 Name->getName() == CorrectedStr;
1026 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
1027 << Name << computeDeclContext(SS, false)
1028 << DroppedSpecifier << SS.getRange());
1029 }
1030
1031 // Update the name, so that the caller has the new name.
1032 Name = Corrected.getCorrectionAsIdentifierInfo();
1033
1034 // Typo correction corrected to a keyword.
1035 if (Corrected.isKeyword())
1036 return Name;
1037
1038 // Also update the LookupResult...
1039 // FIXME: This should probably go away at some point
1040 Result.clear();
1041 Result.setLookupName(Corrected.getCorrection());
1042 if (FirstDecl)
1043 Result.addDecl(FirstDecl);
1044
1045 // If we found an Objective-C instance variable, let
1046 // LookupInObjCMethod build the appropriate expression to
1047 // reference the ivar.
1048 // FIXME: This is a gross hack.
1049 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1050 DeclResult R =
1051 ObjC().LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1052 if (R.isInvalid())
1054 if (R.isUsable())
1055 return NameClassification::NonType(Ivar);
1056 }
1057
1058 goto Corrected;
1059 }
1060 }
1061
1062 // We failed to correct; just fall through and let the parser deal with it.
1063 Result.suppressDiagnostics();
1065
1067 // We performed name lookup into the current instantiation, and there were
1068 // dependent bases, so we treat this result the same way as any other
1069 // dependent nested-name-specifier.
1070
1071 // C++ [temp.res]p2:
1072 // A name used in a template declaration or definition and that is
1073 // dependent on a template-parameter is assumed not to name a type
1074 // unless the applicable name lookup finds a type name or the name is
1075 // qualified by the keyword typename.
1076 //
1077 // FIXME: If the next token is '<', we might want to ask the parser to
1078 // perform some heroics to see if we actually have a
1079 // template-argument-list, which would indicate a missing 'template'
1080 // keyword here.
1082 }
1083
1087 break;
1088
1090 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1091 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1092 /*AllowDependent=*/false)) {
1093 // C++ [temp.local]p3:
1094 // A lookup that finds an injected-class-name (10.2) can result in an
1095 // ambiguity in certain cases (for example, if it is found in more than
1096 // one base class). If all of the injected-class-names that are found
1097 // refer to specializations of the same class template, and if the name
1098 // is followed by a template-argument-list, the reference refers to the
1099 // class template itself and not a specialization thereof, and is not
1100 // ambiguous.
1101 //
1102 // This filtering can make an ambiguous result into an unambiguous one,
1103 // so try again after filtering out template names.
1105 if (!Result.isAmbiguous()) {
1106 IsFilteredTemplateName = true;
1107 break;
1108 }
1109 }
1110
1111 // Diagnose the ambiguity and return an error.
1113 }
1114
1115 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1116 (IsFilteredTemplateName ||
1118 Result, /*AllowFunctionTemplates=*/true,
1119 /*AllowDependent=*/false,
1120 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1122 // C++ [temp.names]p3:
1123 // After name lookup (3.4) finds that a name is a template-name or that
1124 // an operator-function-id or a literal- operator-id refers to a set of
1125 // overloaded functions any member of which is a function template if
1126 // this is followed by a <, the < is always taken as the delimiter of a
1127 // template-argument-list and never as the less-than operator.
1128 // C++2a [temp.names]p2:
1129 // A name is also considered to refer to a template if it is an
1130 // unqualified-id followed by a < and name lookup finds either one
1131 // or more functions or finds nothing.
1132 if (!IsFilteredTemplateName)
1134
1135 bool IsFunctionTemplate;
1136 bool IsVarTemplate;
1138 if (Result.end() - Result.begin() > 1) {
1139 IsFunctionTemplate = true;
1140 Template = Context.getOverloadedTemplateName(Result.begin(),
1141 Result.end());
1142 } else if (!Result.empty()) {
1144 *Result.begin(), /*AllowFunctionTemplates=*/true,
1145 /*AllowDependent=*/false));
1146 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1147 IsVarTemplate = isa<VarTemplateDecl>(TD);
1148
1149 UsingShadowDecl *FoundUsingShadow =
1150 dyn_cast<UsingShadowDecl>(*Result.begin());
1151 assert(!FoundUsingShadow ||
1152 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1153 Template = Context.getQualifiedTemplateName(
1154 SS.getScopeRep(),
1155 /*TemplateKeyword=*/false,
1156 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
1157 } else {
1158 // All results were non-template functions. This is a function template
1159 // name.
1160 IsFunctionTemplate = true;
1161 Template = Context.getAssumedTemplateName(NameInfo.getName());
1162 }
1163
1164 if (IsFunctionTemplate) {
1165 // Function templates always go through overload resolution, at which
1166 // point we'll perform the various checks (e.g., accessibility) we need
1167 // to based on which function we selected.
1168 Result.suppressDiagnostics();
1169
1171 }
1172
1173 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1175 }
1176
1177 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1178 QualType T;
1179 TypeLocBuilder TLB;
1180 if (const auto *USD = dyn_cast<UsingShadowDecl>(Found)) {
1181 T = Context.getUsingType(ElaboratedTypeKeyword::None, SS.getScopeRep(),
1182 USD);
1183 TLB.push<UsingTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),
1184 SS.getWithLocInContext(Context), NameLoc);
1185 } else {
1186 T = Context.getTypeDeclType(ElaboratedTypeKeyword::None, SS.getScopeRep(),
1187 Type);
1188 if (isa<TagType>(T)) {
1189 auto TTL = TLB.push<TagTypeLoc>(T);
1191 TTL.setQualifierLoc(SS.getWithLocInContext(Context));
1192 TTL.setNameLoc(NameLoc);
1193 } else if (isa<TypedefType>(T)) {
1194 TLB.push<TypedefTypeLoc>(T).set(
1195 /*ElaboratedKeywordLoc=*/SourceLocation(),
1196 SS.getWithLocInContext(Context), NameLoc);
1197 } else if (isa<UnresolvedUsingType>(T)) {
1198 TLB.push<UnresolvedUsingTypeLoc>(T).set(
1199 /*ElaboratedKeywordLoc=*/SourceLocation(),
1200 SS.getWithLocInContext(Context), NameLoc);
1201 } else {
1202 TLB.pushTypeSpec(T).setNameLoc(NameLoc);
1203 }
1204 }
1206 };
1207
1208 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1209 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1210 DiagnoseUseOfDecl(Type, NameLoc);
1211 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1212 return BuildTypeFor(Type, *Result.begin());
1213 }
1214
1215 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1216 if (!Class) {
1217 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1218 if (ObjCCompatibleAliasDecl *Alias =
1219 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1220 Class = Alias->getClassInterface();
1221 }
1222
1223 if (Class) {
1224 DiagnoseUseOfDecl(Class, NameLoc);
1225
1226 if (NextToken.is(tok::period)) {
1227 // Interface. <something> is parsed as a property reference expression.
1228 // Just return "unknown" as a fall-through for now.
1229 Result.suppressDiagnostics();
1231 }
1232
1233 QualType T = Context.getObjCInterfaceType(Class);
1234 return ParsedType::make(T);
1235 }
1236
1238 // We want to preserve the UsingShadowDecl for concepts.
1239 if (auto *USD = dyn_cast<UsingShadowDecl>(Result.getRepresentativeDecl()))
1243 }
1244
1245 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1246 (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1248 }
1249
1250 // We can have a type template here if we're classifying a template argument.
1255
1256 // Check for a tag type hidden by a non-type decl in a few cases where it
1257 // seems likely a type is wanted instead of the non-type that was found.
1258 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1259 if ((NextToken.is(tok::identifier) ||
1260 (NextIsOp &&
1261 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1262 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1263 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1264 DiagnoseUseOfDecl(Type, NameLoc);
1265 return BuildTypeFor(Type, *Result.begin());
1266 }
1267
1268 // If we already know which single declaration is referenced, just annotate
1269 // that declaration directly. Defer resolving even non-overloaded class
1270 // member accesses, as we need to defer certain access checks until we know
1271 // the context.
1272 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1273 if (Result.isSingleResult() && !ADL &&
1274 (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(FirstDecl)))
1275 return NameClassification::NonType(Result.getRepresentativeDecl());
1276
1277 // Otherwise, this is an overload set that we will need to resolve later.
1278 Result.suppressDiagnostics();
1280 Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1281 Result.getLookupNameInfo(), ADL, Result.begin(), Result.end(),
1282 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false));
1283}
1284
1287 SourceLocation NameLoc) {
1288 assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1289 CXXScopeSpec SS;
1290 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1291 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1292}
1293
1296 IdentifierInfo *Name,
1297 SourceLocation NameLoc,
1298 bool IsAddressOfOperand) {
1299 DeclarationNameInfo NameInfo(Name, NameLoc);
1300 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1301 NameInfo, IsAddressOfOperand,
1302 /*TemplateArgs=*/nullptr);
1303}
1304
1307 SourceLocation NameLoc,
1308 const Token &NextToken) {
1309 if (getCurMethodDecl() && SS.isEmpty())
1310 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1311 return ObjC().BuildIvarRefExpr(S, NameLoc, Ivar);
1312
1313 // Reconstruct the lookup result.
1314 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1315 Result.addDecl(Found);
1316 Result.resolveKind();
1317
1318 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1319 return BuildDeclarationNameExpr(SS, Result, ADL, /*AcceptInvalidDecl=*/true);
1320}
1321
1323 // For an implicit class member access, transform the result into a member
1324 // access expression if necessary.
1325 auto *ULE = cast<UnresolvedLookupExpr>(E);
1326 if ((*ULE->decls_begin())->isCXXClassMember()) {
1327 CXXScopeSpec SS;
1328 SS.Adopt(ULE->getQualifierLoc());
1329
1330 // Reconstruct the lookup result.
1331 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1333 Result.setNamingClass(ULE->getNamingClass());
1334 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1335 Result.addDecl(*I, I.getAccess());
1336 Result.resolveKind();
1338 nullptr, S);
1339 }
1340
1341 // Otherwise, this is already in the form we needed, and no further checks
1342 // are necessary.
1343 return ULE;
1344}
1345
1365
1367 assert(DC->getLexicalParent() == CurContext &&
1368 "The next DeclContext should be lexically contained in the current one.");
1369 CurContext = DC;
1370 S->setEntity(DC);
1371}
1372
1374 assert(CurContext && "DeclContext imbalance!");
1375
1376 CurContext = CurContext->getLexicalParent();
1377 assert(CurContext && "Popped translation unit!");
1378}
1379
1381 Decl *D) {
1382 // Unlike PushDeclContext, the context to which we return is not necessarily
1383 // the containing DC of TD, because the new context will be some pre-existing
1384 // TagDecl definition instead of a fresh one.
1385 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1386 CurContext = cast<TagDecl>(D)->getDefinition();
1387 assert(CurContext && "skipping definition of undefined tag");
1388 // Start lookups from the parent of the current context; we don't want to look
1389 // into the pre-existing complete definition.
1390 S->setEntity(CurContext->getLookupParent());
1391 return Result;
1392}
1393
1397
1399 // C++0x [basic.lookup.unqual]p13:
1400 // A name used in the definition of a static data member of class
1401 // X (after the qualified-id of the static member) is looked up as
1402 // if the name was used in a member function of X.
1403 // C++0x [basic.lookup.unqual]p14:
1404 // If a variable member of a namespace is defined outside of the
1405 // scope of its namespace then any name used in the definition of
1406 // the variable member (after the declarator-id) is looked up as
1407 // if the definition of the variable member occurred in its
1408 // namespace.
1409 // Both of these imply that we should push a scope whose context
1410 // is the semantic context of the declaration. We can't use
1411 // PushDeclContext here because that context is not necessarily
1412 // lexically contained in the current context. Fortunately,
1413 // the containing scope should have the appropriate information.
1414
1415 assert(!S->getEntity() && "scope already has entity");
1416
1417#ifndef NDEBUG
1418 Scope *Ancestor = S->getParent();
1419 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1420 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1421#endif
1422
1423 CurContext = DC;
1424 S->setEntity(DC);
1425
1426 if (S->getParent()->isTemplateParamScope()) {
1427 // Also set the corresponding entities for all immediately-enclosing
1428 // template parameter scopes.
1430 }
1431}
1432
1434 assert(S->getEntity() == CurContext && "Context imbalance!");
1435
1436 // Switch back to the lexical context. The safety of this is
1437 // enforced by an assert in EnterDeclaratorContext.
1438 Scope *Ancestor = S->getParent();
1439 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1440 CurContext = Ancestor->getEntity();
1441
1442 // We don't need to do anything with the scope, which is going to
1443 // disappear.
1444}
1445
1447 assert(S->isTemplateParamScope() &&
1448 "expected to be initializing a template parameter scope");
1449
1450 // C++20 [temp.local]p7:
1451 // In the definition of a member of a class template that appears outside
1452 // of the class template definition, the name of a member of the class
1453 // template hides the name of a template-parameter of any enclosing class
1454 // templates (but not a template-parameter of the member if the member is a
1455 // class or function template).
1456 // C++20 [temp.local]p9:
1457 // In the definition of a class template or in the definition of a member
1458 // of such a template that appears outside of the template definition, for
1459 // each non-dependent base class (13.8.2.1), if the name of the base class
1460 // or the name of a member of the base class is the same as the name of a
1461 // template-parameter, the base class name or member name hides the
1462 // template-parameter name (6.4.10).
1463 //
1464 // This means that a template parameter scope should be searched immediately
1465 // after searching the DeclContext for which it is a template parameter
1466 // scope. For example, for
1467 // template<typename T> template<typename U> template<typename V>
1468 // void N::A<T>::B<U>::f(...)
1469 // we search V then B<U> (and base classes) then U then A<T> (and base
1470 // classes) then T then N then ::.
1471 unsigned ScopeDepth = getTemplateDepth(S);
1472 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1473 DeclContext *SearchDCAfterScope = DC;
1474 for (; DC; DC = DC->getLookupParent()) {
1475 if (const TemplateParameterList *TPL =
1476 cast<Decl>(DC)->getDescribedTemplateParams()) {
1477 unsigned DCDepth = TPL->getDepth() + 1;
1478 if (DCDepth > ScopeDepth)
1479 continue;
1480 if (ScopeDepth == DCDepth)
1481 SearchDCAfterScope = DC = DC->getLookupParent();
1482 break;
1483 }
1484 }
1485 S->setLookupEntity(SearchDCAfterScope);
1486 }
1487}
1488
1490 // We assume that the caller has already called
1491 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1492 FunctionDecl *FD = D->getAsFunction();
1493 if (!FD)
1494 return;
1495
1496 // Same implementation as PushDeclContext, but enters the context
1497 // from the lexical parent, rather than the top-level class.
1498 assert(CurContext == FD->getLexicalParent() &&
1499 "The next DeclContext should be lexically contained in the current one.");
1500 CurContext = FD;
1502
1503 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1504 ParmVarDecl *Param = FD->getParamDecl(P);
1505 // If the parameter has an identifier, then add it to the scope
1506 if (Param->getIdentifier()) {
1507 S->AddDecl(Param);
1508 IdResolver.AddDecl(Param);
1509 }
1510 }
1511}
1512
1514 // Same implementation as PopDeclContext, but returns to the lexical parent,
1515 // rather than the top-level class.
1516 assert(CurContext && "DeclContext imbalance!");
1517 CurContext = CurContext->getLexicalParent();
1518 assert(CurContext && "Popped translation unit!");
1519}
1520
1521/// Determine whether overloading is allowed for a new function
1522/// declaration considering prior declarations of the same name.
1523///
1524/// This routine determines whether overloading is possible, not
1525/// whether a new declaration actually overloads a previous one.
1526/// It will return true in C++ (where overloads are always permitted)
1527/// or, as a C extension, when either the new declaration or a
1528/// previous one is declared with the 'overloadable' attribute.
1530 ASTContext &Context,
1531 const FunctionDecl *New) {
1532 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1533 return true;
1534
1535 // Multiversion function declarations are not overloads in the
1536 // usual sense of that term, but lookup will report that an
1537 // overload set was found if more than one multiversion function
1538 // declaration is present for the same name. It is therefore
1539 // inadequate to assume that some prior declaration(s) had
1540 // the overloadable attribute; checking is required. Since one
1541 // declaration is permitted to omit the attribute, it is necessary
1542 // to check at least two; hence the 'any_of' check below. Note that
1543 // the overloadable attribute is implicitly added to declarations
1544 // that were required to have it but did not.
1545 if (Previous.getResultKind() == LookupResultKind::FoundOverloaded) {
1546 return llvm::any_of(Previous, [](const NamedDecl *ND) {
1547 return ND->hasAttr<OverloadableAttr>();
1548 });
1549 } else if (Previous.getResultKind() == LookupResultKind::Found)
1550 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1551
1552 return false;
1553}
1554
1555void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1556 // Move up the scope chain until we find the nearest enclosing
1557 // non-transparent context. The declaration will be introduced into this
1558 // scope.
1559 while (S->getEntity() && S->getEntity()->isTransparentContext())
1560 S = S->getParent();
1561
1562 // Add scoped declarations into their context, so that they can be
1563 // found later. Declarations without a context won't be inserted
1564 // into any context.
1565 if (AddToContext)
1566 CurContext->addDecl(D);
1567
1568 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1569 // are function-local declarations.
1570 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1571 return;
1572
1573 // Template instantiations should also not be pushed into scope.
1574 if (isa<FunctionDecl>(D) &&
1575 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1576 return;
1577
1578 if (isa<UsingEnumDecl>(D) && D->getDeclName().isEmpty()) {
1579 S->AddDecl(D);
1580 return;
1581 }
1582 // If this replaces anything in the current scope,
1584 IEnd = IdResolver.end();
1585 for (; I != IEnd; ++I) {
1586 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1587 S->RemoveDecl(*I);
1588 IdResolver.RemoveDecl(*I);
1589
1590 // Should only need to replace one decl.
1591 break;
1592 }
1593 }
1594
1595 S->AddDecl(D);
1596
1597 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1598 // Implicitly-generated labels may end up getting generated in an order that
1599 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1600 // the label at the appropriate place in the identifier chain.
1601 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1602 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1603 if (IDC == CurContext) {
1604 if (!S->isDeclScope(*I))
1605 continue;
1606 } else if (IDC->Encloses(CurContext))
1607 break;
1608 }
1609
1610 IdResolver.InsertDeclAfter(I, D);
1611 } else {
1612 IdResolver.AddDecl(D);
1613 }
1615}
1616
1618 bool AllowInlineNamespace) const {
1619 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1620}
1621
1623 DeclContext *TargetDC = DC->getPrimaryContext();
1624 do {
1625 if (DeclContext *ScopeDC = S->getEntity())
1626 if (ScopeDC->getPrimaryContext() == TargetDC)
1627 return S;
1628 } while ((S = S->getParent()));
1629
1630 return nullptr;
1631}
1632
1634 DeclContext*,
1635 ASTContext&);
1636
1638 bool ConsiderLinkage,
1639 bool AllowInlineNamespace) {
1641 while (F.hasNext()) {
1642 NamedDecl *D = F.next();
1643
1644 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1645 continue;
1646
1647 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1648 continue;
1649
1650 F.erase();
1651 }
1652
1653 F.done();
1654}
1655
1657 if (auto *VD = dyn_cast<VarDecl>(D))
1658 return VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1659 if (auto *FD = dyn_cast<FunctionDecl>(D))
1660 return FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1661 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1662 return RD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1663
1664 return false;
1665}
1666
1668 // [module.interface]p7:
1669 // A declaration is attached to a module as follows:
1670 // - If the declaration is a non-dependent friend declaration that nominates a
1671 // function with a declarator-id that is a qualified-id or template-id or that
1672 // nominates a class other than with an elaborated-type-specifier with neither
1673 // a nested-name-specifier nor a simple-template-id, it is attached to the
1674 // module to which the friend is attached ([basic.link]).
1675 if (New->getFriendObjectKind() &&
1676 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1677 New->setLocalOwningModule(Old->getOwningModule());
1679 return false;
1680 }
1681
1682 // Although we have questions for the module ownership of implicit
1683 // instantiations, it should be sure that we shouldn't diagnose the
1684 // redeclaration of incorrect module ownership for different implicit
1685 // instantiations in different modules. We will diagnose the redeclaration of
1686 // incorrect module ownership for the template itself.
1688 return false;
1689
1690 Module *NewM = New->getOwningModule();
1691 Module *OldM = Old->getOwningModule();
1692
1693 if (NewM && NewM->isPrivateModule())
1694 NewM = NewM->Parent;
1695 if (OldM && OldM->isPrivateModule())
1696 OldM = OldM->Parent;
1697
1698 if (NewM == OldM)
1699 return false;
1700
1701 if (NewM && OldM) {
1702 // A module implementation unit has visibility of the decls in its
1703 // implicitly imported interface.
1704 if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1705 return false;
1706
1707 // Partitions are part of the module, but a partition could import another
1708 // module, so verify that the PMIs agree.
1709 if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1710 getASTContext().isInSameModule(NewM, OldM))
1711 return false;
1712 }
1713
1714 bool NewIsModuleInterface = NewM && NewM->isNamedModule();
1715 bool OldIsModuleInterface = OldM && OldM->isNamedModule();
1716 if (NewIsModuleInterface || OldIsModuleInterface) {
1717 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1718 // if a declaration of D [...] appears in the purview of a module, all
1719 // other such declarations shall appear in the purview of the same module
1720 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1721 << New
1722 << NewIsModuleInterface
1723 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1724 << OldIsModuleInterface
1725 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1726 Diag(Old->getLocation(), diag::note_previous_declaration);
1727 New->setInvalidDecl();
1728 return true;
1729 }
1730
1731 return false;
1732}
1733
1735 // [module.interface]p1:
1736 // An export-declaration shall inhabit a namespace scope.
1737 //
1738 // So it is meaningless to talk about redeclaration which is not at namespace
1739 // scope.
1740 if (!New->getLexicalDeclContext()
1741 ->getNonTransparentContext()
1742 ->isFileContext() ||
1743 !Old->getLexicalDeclContext()
1745 ->isFileContext())
1746 return false;
1747
1748 bool IsNewExported = New->isInExportDeclContext();
1749 bool IsOldExported = Old->isInExportDeclContext();
1750
1751 // It should be irrevelant if both of them are not exported.
1752 if (!IsNewExported && !IsOldExported)
1753 return false;
1754
1755 if (IsOldExported)
1756 return false;
1757
1758 // If the Old declaration are not attached to named modules
1759 // and the New declaration are attached to global module.
1760 // It should be fine to allow the export since it doesn't change
1761 // the linkage of declarations. See
1762 // https://github.com/llvm/llvm-project/issues/98583 for details.
1763 if (!Old->isInNamedModule() && New->getOwningModule() &&
1764 New->getOwningModule()->isImplicitGlobalModule())
1765 return false;
1766
1767 assert(IsNewExported);
1768
1769 auto Lk = Old->getFormalLinkage();
1770 int S = 0;
1771 if (Lk == Linkage::Internal)
1772 S = 1;
1773 else if (Lk == Linkage::Module)
1774 S = 2;
1775 Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1776 Diag(Old->getLocation(), diag::note_previous_declaration);
1777 return true;
1778}
1779
1782 return true;
1783
1785 return true;
1786
1787 return false;
1788}
1789
1791 const NamedDecl *Old) const {
1792 assert(getASTContext().isSameEntity(New, Old) &&
1793 "New and Old are not the same definition, we should diagnostic it "
1794 "immediately instead of checking it.");
1795 assert(const_cast<Sema *>(this)->isReachable(New) &&
1796 const_cast<Sema *>(this)->isReachable(Old) &&
1797 "We shouldn't see unreachable definitions here.");
1798
1799 Module *NewM = New->getOwningModule();
1800 Module *OldM = Old->getOwningModule();
1801
1802 // We only checks for named modules here. The header like modules is skipped.
1803 // FIXME: This is not right if we import the header like modules in the module
1804 // purview.
1805 //
1806 // For example, assuming "header.h" provides definition for `D`.
1807 // ```C++
1808 // //--- M.cppm
1809 // export module M;
1810 // import "header.h"; // or #include "header.h" but import it by clang modules
1811 // actually.
1812 //
1813 // //--- Use.cpp
1814 // import M;
1815 // import "header.h"; // or uses clang modules.
1816 // ```
1817 //
1818 // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1819 // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1820 // reject it. But the current implementation couldn't detect the case since we
1821 // don't record the information about the importee modules.
1822 //
1823 // But this might not be painful in practice. Since the design of C++20 Named
1824 // Modules suggests us to use headers in global module fragment instead of
1825 // module purview.
1826 if (NewM && NewM->isHeaderLikeModule())
1827 NewM = nullptr;
1828 if (OldM && OldM->isHeaderLikeModule())
1829 OldM = nullptr;
1830
1831 if (!NewM && !OldM)
1832 return true;
1833
1834 // [basic.def.odr]p14.3
1835 // Each such definition shall not be attached to a named module
1836 // ([module.unit]).
1837 if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule()))
1838 return true;
1839
1840 // Then New and Old lives in the same TU if their share one same module unit.
1841 if (NewM)
1842 NewM = NewM->getTopLevelModule();
1843 if (OldM)
1844 OldM = OldM->getTopLevelModule();
1845 return OldM == NewM;
1846}
1847
1849 if (D->getDeclContext()->isFileContext())
1850 return false;
1851
1852 return isa<UsingShadowDecl>(D) ||
1855}
1856
1857/// Removes using shadow declarations not at class scope from the lookup
1858/// results.
1861 while (F.hasNext())
1863 F.erase();
1864
1865 F.done();
1866}
1867
1868/// Check for this common pattern:
1869/// @code
1870/// class S {
1871/// S(const S&); // DO NOT IMPLEMENT
1872/// void operator=(const S&); // DO NOT IMPLEMENT
1873/// };
1874/// @endcode
1876 // FIXME: Should check for private access too but access is set after we get
1877 // the decl here.
1879 return false;
1880
1881 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1882 return CD->isCopyConstructor();
1883 return D->isCopyAssignmentOperator();
1884}
1885
1886bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1887 const DeclContext *DC = D->getDeclContext();
1888 while (!DC->isTranslationUnit()) {
1889 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1890 if (!RD->hasNameForLinkage())
1891 return true;
1892 }
1893 DC = DC->getParent();
1894 }
1895
1896 return !D->isExternallyVisible();
1897}
1898
1899// FIXME: This needs to be refactored; some other isInMainFile users want
1900// these semantics.
1901static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1903 return false;
1904 return S.SourceMgr.isInMainFile(Loc);
1905}
1906
1908 assert(D);
1909
1910 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1911 return false;
1912
1913 // Ignore all entities declared within templates, and out-of-line definitions
1914 // of members of class templates.
1915 if (D->getDeclContext()->isDependentContext() ||
1917 return false;
1918
1919 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1920 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1921 return false;
1922 // A non-out-of-line declaration of a member specialization was implicitly
1923 // instantiated; it's the out-of-line declaration that we're interested in.
1924 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1925 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1926 return false;
1927
1928 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1929 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1930 return false;
1931 } else {
1932 // 'static inline' functions are defined in headers; don't warn.
1933 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1934 return false;
1935 }
1936
1937 if (FD->doesThisDeclarationHaveABody() &&
1938 Context.DeclMustBeEmitted(FD))
1939 return false;
1940 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1941 // Constants and utility variables are defined in headers with internal
1942 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1943 // like "inline".)
1944 if (!isMainFileLoc(*this, VD->getLocation()))
1945 return false;
1946
1947 if (Context.DeclMustBeEmitted(VD))
1948 return false;
1949
1950 if (VD->isStaticDataMember() &&
1951 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1952 return false;
1953 if (VD->isStaticDataMember() &&
1954 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1955 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1956 return false;
1957
1958 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1959 return false;
1960 } else {
1961 return false;
1962 }
1963
1964 // Only warn for unused decls internal to the translation unit.
1965 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1966 // for inline functions defined in the main source file, for instance.
1967 return mightHaveNonExternalLinkage(D);
1968}
1969
1971 if (!D)
1972 return;
1973
1974 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1975 const FunctionDecl *First = FD->getFirstDecl();
1977 return; // First should already be in the vector.
1978 }
1979
1980 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1981 const VarDecl *First = VD->getFirstDecl();
1983 return; // First should already be in the vector.
1984 }
1985
1987 UnusedFileScopedDecls.push_back(D);
1988}
1989
1990static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts,
1991 const NamedDecl *D) {
1992 if (D->isInvalidDecl())
1993 return false;
1994
1995 if (const auto *DD = dyn_cast<DecompositionDecl>(D)) {
1996 // For a decomposition declaration, warn if none of the bindings are
1997 // referenced, instead of if the variable itself is referenced (which
1998 // it is, by the bindings' expressions).
1999 bool IsAllIgnored = true;
2000 for (const auto *BD : DD->bindings()) {
2001 if (BD->isReferenced())
2002 return false;
2003 IsAllIgnored = IsAllIgnored && (BD->isPlaceholderVar(LangOpts) ||
2004 BD->hasAttr<UnusedAttr>());
2005 }
2006 if (IsAllIgnored)
2007 return false;
2008 } else if (!D->getDeclName()) {
2009 return false;
2010 } else if (D->isReferenced() || D->isUsed()) {
2011 return false;
2012 }
2013
2014 if (D->isPlaceholderVar(LangOpts))
2015 return false;
2016
2017 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||
2018 D->hasAttr<CleanupAttr>())
2019 return false;
2020
2021 if (isa<LabelDecl>(D))
2022 return true;
2023
2024 // Except for labels, we only care about unused decls that are local to
2025 // functions.
2026 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
2027 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
2028 // For dependent types, the diagnostic is deferred.
2029 WithinFunction =
2030 WithinFunction || (R->isLocalClass() && !R->isDependentType());
2031 if (!WithinFunction)
2032 return false;
2033
2034 if (isa<TypedefNameDecl>(D))
2035 return true;
2036
2037 // White-list anything that isn't a local variable.
2039 return false;
2040
2041 // Types of valid local variables should be complete, so this should succeed.
2042 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2043
2044 const Expr *Init = VD->getInit();
2045 if (const auto *Cleanups = dyn_cast_if_present<ExprWithCleanups>(Init))
2046 Init = Cleanups->getSubExpr();
2047
2048 const auto *Ty = VD->getType().getTypePtr();
2049
2050 // Only look at the outermost level of typedef.
2051 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
2052 // Allow anything marked with __attribute__((unused)).
2053 if (TT->getDecl()->hasAttr<UnusedAttr>())
2054 return false;
2055 }
2056
2057 // Warn for reference variables whose initializtion performs lifetime
2058 // extension.
2059 if (const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(Init);
2060 MTE && MTE->getExtendingDecl()) {
2061 Ty = VD->getType().getNonReferenceType().getTypePtr();
2062 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
2063 }
2064
2065 // If we failed to complete the type for some reason, or if the type is
2066 // dependent, don't diagnose the variable.
2067 if (Ty->isIncompleteType() || Ty->isDependentType())
2068 return false;
2069
2070 // Look at the element type to ensure that the warning behaviour is
2071 // consistent for both scalars and arrays.
2072 Ty = Ty->getBaseElementTypeUnsafe();
2073
2074 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2075 if (Tag->hasAttr<UnusedAttr>())
2076 return false;
2077
2078 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2079 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2080 return false;
2081
2082 if (Init) {
2083 const auto *Construct =
2084 dyn_cast<CXXConstructExpr>(Init->IgnoreImpCasts());
2085 if (Construct && !Construct->isElidable()) {
2086 const CXXConstructorDecl *CD = Construct->getConstructor();
2087 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2088 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2089 return false;
2090 }
2091
2092 // Suppress the warning if we don't know how this is constructed, and
2093 // it could possibly be non-trivial constructor.
2094 if (Init->isTypeDependent()) {
2095 for (const CXXConstructorDecl *Ctor : RD->ctors())
2096 if (!Ctor->isTrivial())
2097 return false;
2098 }
2099
2100 // Suppress the warning if the constructor is unresolved because
2101 // its arguments are dependent.
2103 return false;
2104 }
2105 }
2106 }
2107
2108 // TODO: __attribute__((unused)) templates?
2109 }
2110
2111 return true;
2112}
2113
2115 FixItHint &Hint) {
2116 if (isa<LabelDecl>(D)) {
2118 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
2119 /*SkipTrailingWhitespaceAndNewline=*/false);
2120 if (AfterColon.isInvalid())
2121 return;
2123 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
2124 }
2125}
2126
2129 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2130}
2131
2133 DiagReceiverTy DiagReceiver) {
2134 if (D->isDependentType())
2135 return;
2136
2137 for (auto *TmpD : D->decls()) {
2138 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2139 DiagnoseUnusedDecl(T, DiagReceiver);
2140 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2141 DiagnoseUnusedNestedTypedefs(R, DiagReceiver);
2142 }
2143}
2144
2147 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2148}
2149
2152 return;
2153
2154 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2155 // typedefs can be referenced later on, so the diagnostics are emitted
2156 // at end-of-translation-unit.
2158 return;
2159 }
2160
2161 FixItHint Hint;
2163
2164 unsigned DiagID;
2165 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2166 DiagID = diag::warn_unused_exception_param;
2167 else if (isa<LabelDecl>(D))
2168 DiagID = diag::warn_unused_label;
2169 else
2170 DiagID = diag::warn_unused_variable;
2171
2172 SourceLocation DiagLoc = D->getLocation();
2173 DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
2174}
2175
2177 DiagReceiverTy DiagReceiver) {
2178 // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2179 // it's not really unused.
2180 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>())
2181 return;
2182
2183 // In C++, `_` variables behave as if they were maybe_unused
2184 if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(getLangOpts()))
2185 return;
2186
2187 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2188
2189 if (Ty->isReferenceType() || Ty->isDependentType())
2190 return;
2191
2192 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2193 if (Tag->hasAttr<UnusedAttr>())
2194 return;
2195 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2196 // mimic gcc's behavior.
2197 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag);
2198 RD && !RD->hasAttr<WarnUnusedAttr>())
2199 return;
2200 }
2201
2202 // Don't warn about __block Objective-C pointer variables, as they might
2203 // be assigned in the block but not used elsewhere for the purpose of lifetime
2204 // extension.
2205 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2206 return;
2207
2208 // Don't warn about Objective-C pointer variables with precise lifetime
2209 // semantics; they can be used to ensure ARC releases the object at a known
2210 // time, which may mean assignment but no other references.
2211 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2212 return;
2213
2214 auto iter = RefsMinusAssignments.find(VD);
2215 if (iter == RefsMinusAssignments.end())
2216 return;
2217
2218 assert(iter->getSecond() >= 0 &&
2219 "Found a negative number of references to a VarDecl");
2220 if (int RefCnt = iter->getSecond(); RefCnt > 0) {
2221 // Assume the given VarDecl is "used" if its ref count stored in
2222 // `RefMinusAssignments` is positive, with one exception.
2223 //
2224 // For a C++ variable whose decl (with initializer) entirely consist the
2225 // condition expression of a if/while/for construct,
2226 // Clang creates a DeclRefExpr for the condition expression rather than a
2227 // BinaryOperator of AssignmentOp. Thus, the C++ variable's ref
2228 // count stored in `RefMinusAssignment` equals 1 when the variable is never
2229 // used in the body of the if/while/for construct.
2230 bool UnusedCXXCondDecl = VD->isCXXCondDecl() && (RefCnt == 1);
2231 if (!UnusedCXXCondDecl)
2232 return;
2233 }
2234
2235 unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2236 : diag::warn_unused_but_set_variable;
2237 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2238}
2239
2241 Sema::DiagReceiverTy DiagReceiver) {
2242 // Verify that we have no forward references left. If so, there was a goto
2243 // or address of a label taken, but no definition of it. Label fwd
2244 // definitions are indicated with a null substmt which is also not a resolved
2245 // MS inline assembly label name.
2246 bool Diagnose = false;
2247 if (L->isMSAsmLabel())
2248 Diagnose = !L->isResolvedMSAsmLabel();
2249 else
2250 Diagnose = L->getStmt() == nullptr;
2251 if (Diagnose)
2252 DiagReceiver(L->getLocation(), S.PDiag(diag::err_undeclared_label_use)
2253 << L);
2254}
2255
2257 S->applyNRVO();
2258
2259 if (S->decl_empty()) return;
2261 "Scope shouldn't contain decls!");
2262
2263 /// We visit the decls in non-deterministic order, but we want diagnostics
2264 /// emitted in deterministic order. Collect any diagnostic that may be emitted
2265 /// and sort the diagnostics before emitting them, after we visited all decls.
2266 struct LocAndDiag {
2267 SourceLocation Loc;
2268 std::optional<SourceLocation> PreviousDeclLoc;
2270 };
2272 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2273 DeclDiags.push_back(LocAndDiag{Loc, std::nullopt, std::move(PD)});
2274 };
2275 auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2276 SourceLocation PreviousDeclLoc,
2277 PartialDiagnostic PD) {
2278 DeclDiags.push_back(LocAndDiag{Loc, PreviousDeclLoc, std::move(PD)});
2279 };
2280
2281 for (auto *TmpD : S->decls()) {
2282 assert(TmpD && "This decl didn't get pushed??");
2283
2284 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2285 NamedDecl *D = cast<NamedDecl>(TmpD);
2286
2287 // Diagnose unused variables in this scope.
2289 DiagnoseUnusedDecl(D, addDiag);
2290 if (const auto *RD = dyn_cast<RecordDecl>(D))
2291 DiagnoseUnusedNestedTypedefs(RD, addDiag);
2292 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2293 DiagnoseUnusedButSetDecl(VD, addDiag);
2294 RefsMinusAssignments.erase(VD);
2295 }
2296 }
2297
2298 if (!D->getDeclName()) continue;
2299
2300 // If this was a forward reference to a label, verify it was defined.
2301 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2302 CheckPoppedLabel(LD, *this, addDiag);
2303
2304 // Partial translation units that are created in incremental processing must
2305 // not clean up the IdResolver because PTUs should take into account the
2306 // declarations that came from previous PTUs.
2307 if (!PP.isIncrementalProcessingEnabled() || getLangOpts().ObjC ||
2309 IdResolver.RemoveDecl(D);
2310
2311 // Warn on it if we are shadowing a declaration.
2312 auto ShadowI = ShadowingDecls.find(D);
2313 if (ShadowI != ShadowingDecls.end()) {
2314 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2315 addDiagWithPrev(D->getLocation(), FD->getLocation(),
2316 PDiag(diag::warn_ctor_parm_shadows_field)
2317 << D << FD << FD->getParent());
2318 }
2319 ShadowingDecls.erase(ShadowI);
2320 }
2321 }
2322
2323 llvm::sort(DeclDiags,
2324 [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2325 // The particular order for diagnostics is not important, as long
2326 // as the order is deterministic. Using the raw location is going
2327 // to generally be in source order unless there are macro
2328 // expansions involved.
2329 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2330 });
2331 for (const LocAndDiag &D : DeclDiags) {
2332 Diag(D.Loc, D.PD);
2333 if (D.PreviousDeclLoc)
2334 Diag(*D.PreviousDeclLoc, diag::note_previous_declaration);
2335 }
2336}
2337
2339 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2340 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2341 (S->isClassScope() && !getLangOpts().CPlusPlus))
2342 S = S->getParent();
2343 return S;
2344}
2345
2346static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2348 switch (Error) {
2350 return "";
2352 return BuiltinInfo.getHeaderName(ID);
2354 return "stdio.h";
2356 return "setjmp.h";
2358 return "ucontext.h";
2359 }
2360 llvm_unreachable("unhandled error kind");
2361}
2362
2364 unsigned ID, SourceLocation Loc) {
2365 DeclContext *Parent = Context.getTranslationUnitDecl();
2366
2367 if (getLangOpts().CPlusPlus) {
2369 Context, Parent, Loc, Loc, LinkageSpecLanguageIDs::C, false);
2370 CLinkageDecl->setImplicit();
2371 Parent->addDecl(CLinkageDecl);
2372 Parent = CLinkageDecl;
2373 }
2374
2376 if (Context.BuiltinInfo.isImmediate(ID)) {
2377 assert(getLangOpts().CPlusPlus20 &&
2378 "consteval builtins should only be available in C++20 mode");
2379 ConstexprKind = ConstexprSpecKind::Consteval;
2380 }
2381
2383 Context, Parent, Loc, Loc, II, Type, /*TInfo=*/nullptr, SC_Extern,
2384 getCurFPFeatures().isFPConstrained(), /*isInlineSpecified=*/false,
2385 Type->isFunctionProtoType(), ConstexprKind);
2386 New->setImplicit();
2387 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2388
2389 // Create Decl objects for each parameter, adding them to the
2390 // FunctionDecl.
2391 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2393 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2395 Context, New, SourceLocation(), SourceLocation(), nullptr,
2396 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2397 parm->setScopeInfo(0, i);
2398 Params.push_back(parm);
2399 }
2400 New->setParams(Params);
2401 }
2402
2404 return New;
2405}
2406
2408 Scope *S, bool ForRedeclaration,
2409 SourceLocation Loc) {
2411
2413 QualType R = Context.GetBuiltinType(ID, Error);
2414 if (Error) {
2415 if (!ForRedeclaration)
2416 return nullptr;
2417
2418 // If we have a builtin without an associated type we should not emit a
2419 // warning when we were not able to find a type for it.
2421 Context.BuiltinInfo.allowTypeMismatch(ID))
2422 return nullptr;
2423
2424 // If we could not find a type for setjmp it is because the jmp_buf type was
2425 // not defined prior to the setjmp declaration.
2427 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2428 << Context.BuiltinInfo.getName(ID);
2429 return nullptr;
2430 }
2431
2432 // Generally, we emit a warning that the declaration requires the
2433 // appropriate header.
2434 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2435 << getHeaderName(Context.BuiltinInfo, ID, Error)
2436 << Context.BuiltinInfo.getName(ID);
2437 return nullptr;
2438 }
2439
2440 if (!ForRedeclaration &&
2441 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2442 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2443 Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2444 : diag::ext_implicit_lib_function_decl)
2445 << Context.BuiltinInfo.getName(ID) << R;
2446 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2447 Diag(Loc, diag::note_include_header_or_declare)
2448 << Header << Context.BuiltinInfo.getName(ID);
2449 }
2450
2451 if (R.isNull())
2452 return nullptr;
2453
2454 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2456
2457 // TUScope is the translation-unit scope to insert this function into.
2458 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2459 // relate Scopes to DeclContexts, and probably eliminate CurContext
2460 // entirely, but we're not there yet.
2461 DeclContext *SavedContext = CurContext;
2462 CurContext = New->getDeclContext();
2464 CurContext = SavedContext;
2465 return New;
2466}
2467
2468/// Typedef declarations don't have linkage, but they still denote the same
2469/// entity if their types are the same.
2470/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2471/// isSameEntity.
2472static void
2475 // This is only interesting when modules are enabled.
2476 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2477 return;
2478
2479 // Empty sets are uninteresting.
2480 if (Previous.empty())
2481 return;
2482
2483 LookupResult::Filter Filter = Previous.makeFilter();
2484 while (Filter.hasNext()) {
2485 NamedDecl *Old = Filter.next();
2486
2487 // Non-hidden declarations are never ignored.
2488 if (S.isVisible(Old))
2489 continue;
2490
2491 // Declarations of the same entity are not ignored, even if they have
2492 // different linkages.
2493 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2494 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2495 Decl->getUnderlyingType()))
2496 continue;
2497
2498 // If both declarations give a tag declaration a typedef name for linkage
2499 // purposes, then they declare the same entity.
2500 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2501 Decl->getAnonDeclWithTypedefName())
2502 continue;
2503 }
2504
2505 Filter.erase();
2506 }
2507
2508 Filter.done();
2509}
2510
2512 QualType OldType;
2513 if (const TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2514 OldType = OldTypedef->getUnderlyingType();
2515 else
2516 OldType = Context.getTypeDeclType(Old);
2517 QualType NewType = New->getUnderlyingType();
2518
2519 if (NewType->isVariablyModifiedType()) {
2520 // Must not redefine a typedef with a variably-modified type.
2521 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2522 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2523 << Kind << NewType;
2524 if (Old->getLocation().isValid())
2525 notePreviousDefinition(Old, New->getLocation());
2526 New->setInvalidDecl();
2527 return true;
2528 }
2529
2530 if (OldType != NewType &&
2531 !OldType->isDependentType() &&
2532 !NewType->isDependentType() &&
2533 !Context.hasSameType(OldType, NewType)) {
2534 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2535 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2536 << Kind << NewType << OldType;
2537 if (Old->getLocation().isValid())
2538 notePreviousDefinition(Old, New->getLocation());
2539 New->setInvalidDecl();
2540 return true;
2541 }
2542 return false;
2543}
2544
2546 LookupResult &OldDecls) {
2547 // If the new decl is known invalid already, don't bother doing any
2548 // merging checks.
2549 if (New->isInvalidDecl()) return;
2550
2551 // Allow multiple definitions for ObjC built-in typedefs.
2552 // FIXME: Verify the underlying types are equivalent!
2553 if (getLangOpts().ObjC) {
2554 const IdentifierInfo *TypeID = New->getIdentifier();
2555 switch (TypeID->getLength()) {
2556 default: break;
2557 case 2:
2558 {
2559 if (!TypeID->isStr("id"))
2560 break;
2561 QualType T = New->getUnderlyingType();
2562 if (!T->isPointerType())
2563 break;
2564 if (!T->isVoidPointerType()) {
2565 QualType PT = T->castAs<PointerType>()->getPointeeType();
2566 if (!PT->isStructureType())
2567 break;
2568 }
2569 Context.setObjCIdRedefinitionType(T);
2570 // Install the built-in type for 'id', ignoring the current definition.
2571 New->setModedTypeSourceInfo(New->getTypeSourceInfo(),
2572 Context.getObjCIdType());
2573 return;
2574 }
2575 case 5:
2576 if (!TypeID->isStr("Class"))
2577 break;
2578 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2579 // Install the built-in type for 'Class', ignoring the current definition.
2580 New->setModedTypeSourceInfo(New->getTypeSourceInfo(),
2581 Context.getObjCClassType());
2582 return;
2583 case 3:
2584 if (!TypeID->isStr("SEL"))
2585 break;
2586 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2587 // Install the built-in type for 'SEL', ignoring the current definition.
2588 New->setModedTypeSourceInfo(New->getTypeSourceInfo(),
2589 Context.getObjCSelType());
2590 return;
2591 }
2592 // Fall through - the typedef name was not a builtin type.
2593 }
2594
2595 // Verify the old decl was also a type.
2596 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2597 if (!Old) {
2598 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2599 << New->getDeclName();
2600
2601 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2602 if (OldD->getLocation().isValid())
2603 notePreviousDefinition(OldD, New->getLocation());
2604
2605 return New->setInvalidDecl();
2606 }
2607
2608 // If the old declaration is invalid, just give up here.
2609 if (Old->isInvalidDecl())
2610 return New->setInvalidDecl();
2611
2612 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2613 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2614 auto *NewTag = New->getAnonDeclWithTypedefName();
2615 NamedDecl *Hidden = nullptr;
2616 if (OldTag && NewTag &&
2617 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2618 !hasVisibleDefinition(OldTag, &Hidden)) {
2619 // There is a definition of this tag, but it is not visible. Use it
2620 // instead of our tag.
2621 if (OldTD->isModed())
2622 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2623 OldTD->getUnderlyingType());
2624 else
2625 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2626
2627 // Make the old tag definition visible.
2629
2631 }
2632 }
2633
2634 // If the typedef types are not identical, reject them in all languages and
2635 // with any extensions enabled.
2636 if (isIncompatibleTypedef(Old, New))
2637 return;
2638
2639 // The types match. Link up the redeclaration chain and merge attributes if
2640 // the old declaration was a typedef.
2641 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2642 New->setPreviousDecl(Typedef);
2644 }
2645
2646 if (getLangOpts().MicrosoftExt)
2647 return;
2648
2649 if (getLangOpts().CPlusPlus) {
2650 // C++ [dcl.typedef]p2:
2651 // In a given non-class scope, a typedef specifier can be used to
2652 // redefine the name of any type declared in that scope to refer
2653 // to the type to which it already refers.
2655 return;
2656
2657 // C++0x [dcl.typedef]p4:
2658 // In a given class scope, a typedef specifier can be used to redefine
2659 // any class-name declared in that scope that is not also a typedef-name
2660 // to refer to the type to which it already refers.
2661 //
2662 // This wording came in via DR424, which was a correction to the
2663 // wording in DR56, which accidentally banned code like:
2664 //
2665 // struct S {
2666 // typedef struct A { } A;
2667 // };
2668 //
2669 // in the C++03 standard. We implement the C++0x semantics, which
2670 // allow the above but disallow
2671 //
2672 // struct S {
2673 // typedef int I;
2674 // typedef int I;
2675 // };
2676 //
2677 // since that was the intent of DR56.
2678 if (!isa<TypedefNameDecl>(Old))
2679 return;
2680
2681 Diag(New->getLocation(), diag::err_redefinition)
2682 << New->getDeclName();
2683 notePreviousDefinition(Old, New->getLocation());
2684 return New->setInvalidDecl();
2685 }
2686
2687 // Modules always permit redefinition of typedefs, as does C11.
2688 if (getLangOpts().Modules || getLangOpts().C11)
2689 return;
2690
2691 // If we have a redefinition of a typedef in C, emit a warning. This warning
2692 // is normally mapped to an error, but can be controlled with
2693 // -Wtypedef-redefinition. If either the original or the redefinition is
2694 // in a system header, don't emit this for compatibility with GCC.
2695 if (getDiagnostics().getSuppressSystemWarnings() &&
2696 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2697 (Old->isImplicit() ||
2698 Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2699 Context.getSourceManager().isInSystemHeader(New->getLocation())))
2700 return;
2701
2702 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2703 << New->getDeclName();
2704 notePreviousDefinition(Old, New->getLocation());
2705}
2706
2708 // If this was an unscoped enumeration, yank all of its enumerators
2709 // out of the scope.
2710 if (auto *ED = dyn_cast<EnumDecl>(New); ED && !ED->isScoped()) {
2711 Scope *EnumScope = getNonFieldDeclScope(S);
2712 for (auto *ECD : ED->enumerators()) {
2713 assert(EnumScope->isDeclScope(ECD));
2714 EnumScope->RemoveDecl(ECD);
2715 IdResolver.RemoveDecl(ECD);
2716 }
2717 }
2718}
2719
2720/// DeclhasAttr - returns true if decl Declaration already has the target
2721/// attribute.
2722static bool DeclHasAttr(const Decl *D, const Attr *A) {
2723 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2724 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2725 for (const auto *i : D->attrs())
2726 if (i->getKind() == A->getKind()) {
2727 if (Ann) {
2728 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2729 return true;
2730 continue;
2731 }
2732 // FIXME: Don't hardcode this check
2733 if (OA && isa<OwnershipAttr>(i))
2734 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2735 return true;
2736 }
2737
2738 return false;
2739}
2740
2742 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2743 return VD->isThisDeclarationADefinition();
2744 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2745 return TD->isCompleteDefinition() || TD->isBeingDefined();
2746 return true;
2747}
2748
2749/// Merge alignment attributes from \p Old to \p New, taking into account the
2750/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2751///
2752/// \return \c true if any attributes were added to \p New.
2753static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2754 // Look for alignas attributes on Old, and pick out whichever attribute
2755 // specifies the strictest alignment requirement.
2756 AlignedAttr *OldAlignasAttr = nullptr;
2757 AlignedAttr *OldStrictestAlignAttr = nullptr;
2758 unsigned OldAlign = 0;
2759 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2760 // FIXME: We have no way of representing inherited dependent alignments
2761 // in a case like:
2762 // template<int A, int B> struct alignas(A) X;
2763 // template<int A, int B> struct alignas(B) X {};
2764 // For now, we just ignore any alignas attributes which are not on the
2765 // definition in such a case.
2766 if (I->isAlignmentDependent())
2767 return false;
2768
2769 if (I->isAlignas())
2770 OldAlignasAttr = I;
2771
2772 unsigned Align = I->getAlignment(S.Context);
2773 if (Align > OldAlign) {
2774 OldAlign = Align;
2775 OldStrictestAlignAttr = I;
2776 }
2777 }
2778
2779 // Look for alignas attributes on New.
2780 AlignedAttr *NewAlignasAttr = nullptr;
2781 unsigned NewAlign = 0;
2782 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2783 if (I->isAlignmentDependent())
2784 return false;
2785
2786 if (I->isAlignas())
2787 NewAlignasAttr = I;
2788
2789 unsigned Align = I->getAlignment(S.Context);
2790 if (Align > NewAlign)
2791 NewAlign = Align;
2792 }
2793
2794 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2795 // Both declarations have 'alignas' attributes. We require them to match.
2796 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2797 // fall short. (If two declarations both have alignas, they must both match
2798 // every definition, and so must match each other if there is a definition.)
2799
2800 // If either declaration only contains 'alignas(0)' specifiers, then it
2801 // specifies the natural alignment for the type.
2802 if (OldAlign == 0 || NewAlign == 0) {
2803 QualType Ty;
2804 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2805 Ty = VD->getType();
2806 else
2808
2809 if (OldAlign == 0)
2810 OldAlign = S.Context.getTypeAlign(Ty);
2811 if (NewAlign == 0)
2812 NewAlign = S.Context.getTypeAlign(Ty);
2813 }
2814
2815 if (OldAlign != NewAlign) {
2816 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2819 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2820 }
2821 }
2822
2823 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2824 // C++11 [dcl.align]p6:
2825 // if any declaration of an entity has an alignment-specifier,
2826 // every defining declaration of that entity shall specify an
2827 // equivalent alignment.
2828 // C11 6.7.5/7:
2829 // If the definition of an object does not have an alignment
2830 // specifier, any other declaration of that object shall also
2831 // have no alignment specifier.
2832 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2833 << OldAlignasAttr;
2834 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2835 << OldAlignasAttr;
2836 }
2837
2838 bool AnyAdded = false;
2839
2840 // Ensure we have an attribute representing the strictest alignment.
2841 if (OldAlign > NewAlign) {
2842 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2843 Clone->setInherited(true);
2844 New->addAttr(Clone);
2845 AnyAdded = true;
2846 }
2847
2848 // Ensure we have an alignas attribute if the old declaration had one.
2849 if (OldAlignasAttr && !NewAlignasAttr &&
2850 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2851 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2852 Clone->setInherited(true);
2853 New->addAttr(Clone);
2854 AnyAdded = true;
2855 }
2856
2857 return AnyAdded;
2858}
2859
2860#define WANT_DECL_MERGE_LOGIC
2861#include "clang/Sema/AttrParsedAttrImpl.inc"
2862#undef WANT_DECL_MERGE_LOGIC
2863
2865 const InheritableAttr *Attr,
2867 // Diagnose any mutual exclusions between the attribute that we want to add
2868 // and attributes that already exist on the declaration.
2869 if (!DiagnoseMutualExclusions(S, D, Attr))
2870 return false;
2871
2872 // This function copies an attribute Attr from a previous declaration to the
2873 // new declaration D if the new declaration doesn't itself have that attribute
2874 // yet or if that attribute allows duplicates.
2875 // If you're adding a new attribute that requires logic different from
2876 // "use explicit attribute on decl if present, else use attribute from
2877 // previous decl", for example if the attribute needs to be consistent
2878 // between redeclarations, you need to call a custom merge function here.
2879 InheritableAttr *NewAttr = nullptr;
2880 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2881 NewAttr = S.mergeAvailabilityAttr(
2882 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2883 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2884 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2885 AA->getPriority(), AA->getEnvironment());
2886 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2887 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2888 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2889 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2890 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2891 NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2892 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2893 NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2894 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2895 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2896 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2897 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2898 FA->getFirstArg());
2899 else if (const auto *FMA = dyn_cast<FormatMatchesAttr>(Attr))
2900 NewAttr = S.mergeFormatMatchesAttr(
2901 D, *FMA, FMA->getType(), FMA->getFormatIdx(), FMA->getFormatString());
2902 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2903 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2904 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2905 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2906 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2907 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2908 IA->getInheritanceModel());
2909 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2910 NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2911 &S.Context.Idents.get(AA->getSpelling()));
2912 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2915 // CUDA target attributes are part of function signature for
2916 // overloading purposes and must not be merged.
2917 return false;
2918 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2919 NewAttr = S.mergeMinSizeAttr(D, *MA);
2920 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2921 NewAttr = S.Swift().mergeNameAttr(D, *SNA, SNA->getName());
2922 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2923 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2924 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2925 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2926 else if (isa<AlignedAttr>(Attr))
2927 // AlignedAttrs are handled separately, because we need to handle all
2928 // such attributes on a declaration at the same time.
2929 NewAttr = nullptr;
2934 NewAttr = nullptr;
2935 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2936 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2937 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2938 NewAttr = S.Wasm().mergeImportModuleAttr(D, *IMA);
2939 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2940 NewAttr = S.Wasm().mergeImportNameAttr(D, *INA);
2941 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2942 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2943 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2944 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2945 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2946 NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2947 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
2948 NewAttr = S.HLSL().mergeNumThreadsAttr(D, *NT, NT->getX(), NT->getY(),
2949 NT->getZ());
2950 else if (const auto *WS = dyn_cast<HLSLWaveSizeAttr>(Attr))
2951 NewAttr = S.HLSL().mergeWaveSizeAttr(D, *WS, WS->getMin(), WS->getMax(),
2952 WS->getPreferred(),
2953 WS->getSpelledArgsCount());
2954 else if (const auto *CI = dyn_cast<HLSLVkConstantIdAttr>(Attr))
2955 NewAttr = S.HLSL().mergeVkConstantIdAttr(D, *CI, CI->getId());
2956 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
2957 NewAttr = S.HLSL().mergeShaderAttr(D, *SA, SA->getType());
2958 else if (isa<SuppressAttr>(Attr))
2959 // Do nothing. Each redeclaration should be suppressed separately.
2960 NewAttr = nullptr;
2961 else if (const auto *RD = dyn_cast<OpenACCRoutineDeclAttr>(Attr))
2962 NewAttr = S.OpenACC().mergeRoutineDeclAttr(*RD);
2963 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2964 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2965
2966 if (NewAttr) {
2967 NewAttr->setInherited(true);
2968 D->addAttr(NewAttr);
2969 if (isa<MSInheritanceAttr>(NewAttr))
2971 return true;
2972 }
2973
2974 return false;
2975}
2976
2977static const NamedDecl *getDefinition(const Decl *D) {
2978 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
2979 if (const auto *Def = TD->getDefinition(); Def && !Def->isBeingDefined())
2980 return Def;
2981 return nullptr;
2982 }
2983 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2984 const VarDecl *Def = VD->getDefinition();
2985 if (Def)
2986 return Def;
2987 return VD->getActingDefinition();
2988 }
2989 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2990 const FunctionDecl *Def = nullptr;
2991 if (FD->isDefined(Def, true))
2992 return Def;
2993 }
2994 return nullptr;
2995}
2996
2997static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2998 for (const auto *Attribute : D->attrs())
2999 if (Attribute->getKind() == Kind)
3000 return true;
3001 return false;
3002}
3003
3004/// checkNewAttributesAfterDef - If we already have a definition, check that
3005/// there are no new attributes in this declaration.
3006static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
3007 if (!New->hasAttrs())
3008 return;
3009
3010 const NamedDecl *Def = getDefinition(Old);
3011 if (!Def || Def == New)
3012 return;
3013
3014 AttrVec &NewAttributes = New->getAttrs();
3015 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
3016 Attr *NewAttribute = NewAttributes[I];
3017
3018 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
3019 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
3020 SkipBodyInfo SkipBody;
3021 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
3022
3023 // If we're skipping this definition, drop the "alias" attribute.
3024 if (SkipBody.ShouldSkip) {
3025 NewAttributes.erase(NewAttributes.begin() + I);
3026 --E;
3027 continue;
3028 }
3029 } else {
3030 VarDecl *VD = cast<VarDecl>(New);
3031 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
3033 ? diag::err_alias_after_tentative
3034 : diag::err_redefinition;
3035 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
3036 if (Diag == diag::err_redefinition)
3037 S.notePreviousDefinition(Def, VD->getLocation());
3038 else
3039 S.Diag(Def->getLocation(), diag::note_previous_definition);
3040 VD->setInvalidDecl();
3041 }
3042 ++I;
3043 continue;
3044 }
3045
3046 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
3047 // Tentative definitions are only interesting for the alias check above.
3048 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
3049 ++I;
3050 continue;
3051 }
3052 }
3053
3054 if (hasAttribute(Def, NewAttribute->getKind())) {
3055 ++I;
3056 continue; // regular attr merging will take care of validating this.
3057 }
3058
3059 if (isa<C11NoReturnAttr>(NewAttribute)) {
3060 // C's _Noreturn is allowed to be added to a function after it is defined.
3061 ++I;
3062 continue;
3063 } else if (isa<UuidAttr>(NewAttribute)) {
3064 // msvc will allow a subsequent definition to add an uuid to a class
3065 ++I;
3066 continue;
3068 NewAttribute) &&
3069 NewAttribute->isStandardAttributeSyntax()) {
3070 // C++14 [dcl.attr.deprecated]p3: A name or entity declared without the
3071 // deprecated attribute can later be re-declared with the attribute and
3072 // vice-versa.
3073 // C++17 [dcl.attr.unused]p4: A name or entity declared without the
3074 // maybe_unused attribute can later be redeclared with the attribute and
3075 // vice versa.
3076 // C++20 [dcl.attr.nodiscard]p2: A name or entity declared without the
3077 // nodiscard attribute can later be redeclared with the attribute and
3078 // vice-versa.
3079 // C23 6.7.13.3p3, 6.7.13.4p3. and 6.7.13.5p5 give the same allowances.
3080 ++I;
3081 continue;
3082 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
3083 if (AA->isAlignas()) {
3084 // C++11 [dcl.align]p6:
3085 // if any declaration of an entity has an alignment-specifier,
3086 // every defining declaration of that entity shall specify an
3087 // equivalent alignment.
3088 // C11 6.7.5/7:
3089 // If the definition of an object does not have an alignment
3090 // specifier, any other declaration of that object shall also
3091 // have no alignment specifier.
3092 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
3093 << AA;
3094 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
3095 << AA;
3096 NewAttributes.erase(NewAttributes.begin() + I);
3097 --E;
3098 continue;
3099 }
3100 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
3101 // If there is a C definition followed by a redeclaration with this
3102 // attribute then there are two different definitions. In C++, prefer the
3103 // standard diagnostics.
3104 if (!S.getLangOpts().CPlusPlus) {
3105 S.Diag(NewAttribute->getLocation(),
3106 diag::err_loader_uninitialized_redeclaration);
3107 S.Diag(Def->getLocation(), diag::note_previous_definition);
3108 NewAttributes.erase(NewAttributes.begin() + I);
3109 --E;
3110 continue;
3111 }
3112 } else if (isa<SelectAnyAttr>(NewAttribute) &&
3113 cast<VarDecl>(New)->isInline() &&
3114 !cast<VarDecl>(New)->isInlineSpecified()) {
3115 // Don't warn about applying selectany to implicitly inline variables.
3116 // Older compilers and language modes would require the use of selectany
3117 // to make such variables inline, and it would have no effect if we
3118 // honored it.
3119 ++I;
3120 continue;
3121 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
3122 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3123 // declarations after definitions.
3124 ++I;
3125 continue;
3126 } else if (isa<SYCLKernelEntryPointAttr>(NewAttribute)) {
3127 // Elevate latent uses of the sycl_kernel_entry_point attribute to an
3128 // error since the definition will have already been created without
3129 // the semantic effects of the attribute having been applied.
3130 S.Diag(NewAttribute->getLocation(),
3131 diag::err_sycl_entry_point_after_definition)
3132 << NewAttribute;
3133 S.Diag(Def->getLocation(), diag::note_previous_definition);
3134 cast<SYCLKernelEntryPointAttr>(NewAttribute)->setInvalidAttr();
3135 ++I;
3136 continue;
3137 } else if (isa<SYCLExternalAttr>(NewAttribute)) {
3138 // SYCLExternalAttr may be added after a definition.
3139 ++I;
3140 continue;
3141 }
3142
3143 S.Diag(NewAttribute->getLocation(),
3144 diag::warn_attribute_precede_definition);
3145 S.Diag(Def->getLocation(), diag::note_previous_definition);
3146 NewAttributes.erase(NewAttributes.begin() + I);
3147 --E;
3148 }
3149}
3150
3151static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3152 const ConstInitAttr *CIAttr,
3153 bool AttrBeforeInit) {
3154 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3155
3156 // Figure out a good way to write this specifier on the old declaration.
3157 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3158 // enough of the attribute list spelling information to extract that without
3159 // heroics.
3160 std::string SuitableSpelling;
3161 if (S.getLangOpts().CPlusPlus20)
3162 SuitableSpelling = std::string(
3163 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
3164 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3165 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3166 InsertLoc, {tok::l_square, tok::l_square,
3167 S.PP.getIdentifierInfo("clang"), tok::coloncolon,
3168 S.PP.getIdentifierInfo("require_constant_initialization"),
3169 tok::r_square, tok::r_square}));
3170 if (SuitableSpelling.empty())
3171 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3172 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
3173 S.PP.getIdentifierInfo("require_constant_initialization"),
3174 tok::r_paren, tok::r_paren}));
3175 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3176 SuitableSpelling = "constinit";
3177 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3178 SuitableSpelling = "[[clang::require_constant_initialization]]";
3179 if (SuitableSpelling.empty())
3180 SuitableSpelling = "__attribute__((require_constant_initialization))";
3181 SuitableSpelling += " ";
3182
3183 if (AttrBeforeInit) {
3184 // extern constinit int a;
3185 // int a = 0; // error (missing 'constinit'), accepted as extension
3186 assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3187 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3188 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3189 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3190 } else {
3191 // int a = 0;
3192 // constinit extern int a; // error (missing 'constinit')
3193 S.Diag(CIAttr->getLocation(),
3194 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3195 : diag::warn_require_const_init_added_too_late)
3196 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3197 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3198 << CIAttr->isConstinit()
3199 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3200 }
3201}
3202
3205 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3206 UsedAttr *NewAttr = OldAttr->clone(Context);
3207 NewAttr->setInherited(true);
3208 New->addAttr(NewAttr);
3209 }
3210 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3211 RetainAttr *NewAttr = OldAttr->clone(Context);
3212 NewAttr->setInherited(true);
3213 New->addAttr(NewAttr);
3214 }
3215
3216 if (!Old->hasAttrs() && !New->hasAttrs())
3217 return;
3218
3219 // [dcl.constinit]p1:
3220 // If the [constinit] specifier is applied to any declaration of a
3221 // variable, it shall be applied to the initializing declaration.
3222 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3223 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3224 if (bool(OldConstInit) != bool(NewConstInit)) {
3225 const auto *OldVD = cast<VarDecl>(Old);
3226 auto *NewVD = cast<VarDecl>(New);
3227
3228 // Find the initializing declaration. Note that we might not have linked
3229 // the new declaration into the redeclaration chain yet.
3230 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3231 if (!InitDecl &&
3232 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3233 InitDecl = NewVD;
3234
3235 if (InitDecl == NewVD) {
3236 // This is the initializing declaration. If it would inherit 'constinit',
3237 // that's ill-formed. (Note that we do not apply this to the attribute
3238 // form).
3239 if (OldConstInit && OldConstInit->isConstinit())
3240 diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3241 /*AttrBeforeInit=*/true);
3242 } else if (NewConstInit) {
3243 // This is the first time we've been told that this declaration should
3244 // have a constant initializer. If we already saw the initializing
3245 // declaration, this is too late.
3246 if (InitDecl && InitDecl != NewVD) {
3247 diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3248 /*AttrBeforeInit=*/false);
3249 NewVD->dropAttr<ConstInitAttr>();
3250 }
3251 }
3252 }
3253
3254 // Attributes declared post-definition are currently ignored.
3255 checkNewAttributesAfterDef(*this, New, Old);
3256
3257 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3258 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3259 if (!OldA->isEquivalent(NewA)) {
3260 // This redeclaration changes __asm__ label.
3261 Diag(New->getLocation(), diag::err_different_asm_label);
3262 Diag(OldA->getLocation(), diag::note_previous_declaration);
3263 }
3264 } else if (Old->isUsed()) {
3265 // This redeclaration adds an __asm__ label to a declaration that has
3266 // already been ODR-used.
3267 Diag(New->getLocation(), diag::err_late_asm_label_name)
3268 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3269 }
3270 }
3271
3272 // Re-declaration cannot add abi_tag's.
3273 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3274 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3275 for (const auto &NewTag : NewAbiTagAttr->tags()) {
3276 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3277 Diag(NewAbiTagAttr->getLocation(),
3278 diag::err_new_abi_tag_on_redeclaration)
3279 << NewTag;
3280 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3281 }
3282 }
3283 } else {
3284 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3285 Diag(Old->getLocation(), diag::note_previous_declaration);
3286 }
3287 }
3288
3289 // This redeclaration adds a section attribute.
3290 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3291 if (auto *VD = dyn_cast<VarDecl>(New)) {
3292 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3293 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3294 Diag(Old->getLocation(), diag::note_previous_declaration);
3295 }
3296 }
3297 }
3298
3299 // Redeclaration adds code-seg attribute.
3300 const auto *NewCSA = New->getAttr<CodeSegAttr>();
3301 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3302 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3303 Diag(New->getLocation(), diag::warn_mismatched_section)
3304 << 0 /*codeseg*/;
3305 Diag(Old->getLocation(), diag::note_previous_declaration);
3306 }
3307
3308 if (!Old->hasAttrs())
3309 return;
3310
3311 bool foundAny = New->hasAttrs();
3312
3313 // Ensure that any moving of objects within the allocated map is done before
3314 // we process them.
3315 if (!foundAny) New->setAttrs(AttrVec());
3316
3317 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3318 // Ignore deprecated/unavailable/availability attributes if requested.
3320 if (isa<DeprecatedAttr>(I) ||
3323 switch (AMK) {
3325 continue;
3326
3331 LocalAMK = AMK;
3332 break;
3333 }
3334 }
3335
3336 // Already handled.
3337 if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3338 continue;
3339
3341 if (auto *FD = dyn_cast<FunctionDecl>(New);
3342 FD &&
3343 FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
3344 continue; // Don't propagate inferred noreturn attributes to explicit
3345 }
3346
3347 if (mergeDeclAttribute(*this, New, I, LocalAMK))
3348 foundAny = true;
3349 }
3350
3351 if (mergeAlignedAttrs(*this, New, Old))
3352 foundAny = true;
3353
3354 if (!foundAny) New->dropAttrs();
3355}
3356
3357// Returns the number of added attributes.
3358template <class T>
3359static unsigned propagateAttribute(ParmVarDecl *To, const ParmVarDecl *From,
3360 Sema &S) {
3361 unsigned found = 0;
3362 for (const auto *I : From->specific_attrs<T>()) {
3363 if (!DeclHasAttr(To, I)) {
3364 T *newAttr = cast<T>(I->clone(S.Context));
3365 newAttr->setInherited(true);
3366 To->addAttr(newAttr);
3367 ++found;
3368 }
3369 }
3370 return found;
3371}
3372
3373template <class F>
3374static void propagateAttributes(ParmVarDecl *To, const ParmVarDecl *From,
3375 F &&propagator) {
3376 if (!From->hasAttrs()) {
3377 return;
3378 }
3379
3380 bool foundAny = To->hasAttrs();
3381
3382 // Ensure that any moving of objects within the allocated map is
3383 // done before we process them.
3384 if (!foundAny)
3385 To->setAttrs(AttrVec());
3386
3387 foundAny |= std::forward<F>(propagator)(To, From) != 0;
3388
3389 if (!foundAny)
3390 To->dropAttrs();
3391}
3392
3393/// mergeParamDeclAttributes - Copy attributes from the old parameter
3394/// to the new one.
3396 const ParmVarDecl *oldDecl,
3397 Sema &S) {
3398 // C++11 [dcl.attr.depend]p2:
3399 // The first declaration of a function shall specify the
3400 // carries_dependency attribute for its declarator-id if any declaration
3401 // of the function specifies the carries_dependency attribute.
3402 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3403 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3404 S.Diag(CDA->getLocation(),
3405 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3406 // Find the first declaration of the parameter.
3407 // FIXME: Should we build redeclaration chains for function parameters?
3408 const FunctionDecl *FirstFD =
3409 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3410 const ParmVarDecl *FirstVD =
3411 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3412 S.Diag(FirstVD->getLocation(),
3413 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3414 }
3415
3417 newDecl, oldDecl, [&S](ParmVarDecl *To, const ParmVarDecl *From) {
3418 unsigned found = 0;
3419 found += propagateAttribute<InheritableParamAttr>(To, From, S);
3420 // Propagate the lifetimebound attribute from parameters to the
3421 // most recent declaration. Note that this doesn't include the implicit
3422 // 'this' parameter, as the attribute is applied to the function type in
3423 // that case.
3424 found += propagateAttribute<LifetimeBoundAttr>(To, From, S);
3425 return found;
3426 });
3427}
3428
3430 const ASTContext &Ctx) {
3431
3432 auto NoSizeInfo = [&Ctx](QualType Ty) {
3433 if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3434 return true;
3435 if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))
3436 return VAT->getSizeModifier() == ArraySizeModifier::Star;
3437 return false;
3438 };
3439
3440 // `type[]` is equivalent to `type *` and `type[*]`.
3441 if (NoSizeInfo(Old) && NoSizeInfo(New))
3442 return true;
3443
3444 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3445 if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3446 const auto *OldVAT = Ctx.getAsVariableArrayType(Old);
3447 const auto *NewVAT = Ctx.getAsVariableArrayType(New);
3448 if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^
3449 (NewVAT->getSizeModifier() == ArraySizeModifier::Star))
3450 return false;
3451 return true;
3452 }
3453
3454 // Only compare size, ignore Size modifiers and CVR.
3455 if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3456 return Ctx.getAsConstantArrayType(Old)->getSize() ==
3458 }
3459
3460 // Don't try to compare dependent sized array
3461 if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) {
3462 return true;
3463 }
3464
3465 return Old == New;
3466}
3467
3468static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3469 const ParmVarDecl *OldParam,
3470 Sema &S) {
3471 if (auto Oldnullability = OldParam->getType()->getNullability()) {
3472 if (auto Newnullability = NewParam->getType()->getNullability()) {
3473 if (*Oldnullability != *Newnullability) {
3474 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3476 *Newnullability,
3478 != 0))
3480 *Oldnullability,
3482 != 0));
3483 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3484 }
3485 } else {
3486 QualType NewT = NewParam->getType();
3487 NewT = S.Context.getAttributedType(*Oldnullability, NewT, NewT);
3488 NewParam->setType(NewT);
3489 }
3490 }
3491 const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
3492 const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
3493 if (OldParamDT && NewParamDT &&
3494 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3495 QualType OldParamOT = OldParamDT->getOriginalType();
3496 QualType NewParamOT = NewParamDT->getOriginalType();
3497 if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) {
3498 S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
3499 << NewParam << NewParamOT;
3500 S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
3501 << OldParamOT;
3502 }
3503 }
3504}
3505
3506namespace {
3507
3508/// Used in MergeFunctionDecl to keep track of function parameters in
3509/// C.
3510struct GNUCompatibleParamWarning {
3511 ParmVarDecl *OldParm;
3512 ParmVarDecl *NewParm;
3513 QualType PromotedType;
3514};
3515
3516} // end anonymous namespace
3517
3518// Determine whether the previous declaration was a definition, implicit
3519// declaration, or a declaration.
3520template <typename T>
3521static std::pair<diag::kind, SourceLocation>
3523 diag::kind PrevDiag;
3524 SourceLocation OldLocation = Old->getLocation();
3525 if (Old->isThisDeclarationADefinition())
3526 PrevDiag = diag::note_previous_definition;
3527 else if (Old->isImplicit()) {
3528 PrevDiag = diag::note_previous_implicit_declaration;
3529 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3530 if (FD->getBuiltinID())
3531 PrevDiag = diag::note_previous_builtin_declaration;
3532 }
3533 if (OldLocation.isInvalid())
3534 OldLocation = New->getLocation();
3535 } else
3536 PrevDiag = diag::note_previous_declaration;
3537 return std::make_pair(PrevDiag, OldLocation);
3538}
3539
3540/// canRedefineFunction - checks if a function can be redefined. Currently,
3541/// only extern inline functions can be redefined, and even then only in
3542/// GNU89 mode.
3543static bool canRedefineFunction(const FunctionDecl *FD,
3544 const LangOptions& LangOpts) {
3545 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3546 !LangOpts.CPlusPlus &&
3547 FD->isInlineSpecified() &&
3548 FD->getStorageClass() == SC_Extern);
3549}
3550
3551const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3552 const AttributedType *AT = T->getAs<AttributedType>();
3553 while (AT && !AT->isCallingConv())
3554 AT = AT->getModifiedType()->getAs<AttributedType>();
3555 return AT;
3556}
3557
3558template <typename T>
3559static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3560 const DeclContext *DC = Old->getDeclContext();
3561 if (DC->isRecord())
3562 return false;
3563
3564 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3565 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3566 return true;
3567 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3568 return true;
3569 return false;
3570}
3571
3572template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3573static bool isExternC(VarTemplateDecl *) { return false; }
3574static bool isExternC(FunctionTemplateDecl *) { return false; }
3575
3576/// Check whether a redeclaration of an entity introduced by a
3577/// using-declaration is valid, given that we know it's not an overload
3578/// (nor a hidden tag declaration).
3579template<typename ExpectedDecl>
3581 ExpectedDecl *New) {
3582 // C++11 [basic.scope.declarative]p4:
3583 // Given a set of declarations in a single declarative region, each of
3584 // which specifies the same unqualified name,
3585 // -- they shall all refer to the same entity, or all refer to functions
3586 // and function templates; or
3587 // -- exactly one declaration shall declare a class name or enumeration
3588 // name that is not a typedef name and the other declarations shall all
3589 // refer to the same variable or enumerator, or all refer to functions
3590 // and function templates; in this case the class name or enumeration
3591 // name is hidden (3.3.10).
3592
3593 // C++11 [namespace.udecl]p14:
3594 // If a function declaration in namespace scope or block scope has the
3595 // same name and the same parameter-type-list as a function introduced
3596 // by a using-declaration, and the declarations do not declare the same
3597 // function, the program is ill-formed.
3598
3599 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3600 if (Old &&
3601 !Old->getDeclContext()->getRedeclContext()->Equals(
3602 New->getDeclContext()->getRedeclContext()) &&
3603 !(isExternC(Old) && isExternC(New)))
3604 Old = nullptr;
3605
3606 if (!Old) {
3607 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3608 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3609 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3610 return true;
3611 }
3612 return false;
3613}
3614
3616 const FunctionDecl *B) {
3617 assert(A->getNumParams() == B->getNumParams());
3618
3619 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3620 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3621 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3622 if (AttrA == AttrB)
3623 return true;
3624 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3625 AttrA->isDynamic() == AttrB->isDynamic();
3626 };
3627
3628 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3629}
3630
3631/// If necessary, adjust the semantic declaration context for a qualified
3632/// declaration to name the correct inline namespace within the qualifier.
3634 DeclaratorDecl *OldD) {
3635 // The only case where we need to update the DeclContext is when
3636 // redeclaration lookup for a qualified name finds a declaration
3637 // in an inline namespace within the context named by the qualifier:
3638 //
3639 // inline namespace N { int f(); }
3640 // int ::f(); // Sema DC needs adjusting from :: to N::.
3641 //
3642 // For unqualified declarations, the semantic context *can* change
3643 // along the redeclaration chain (for local extern declarations,
3644 // extern "C" declarations, and friend declarations in particular).
3645 if (!NewD->getQualifier())
3646 return;
3647
3648 // NewD is probably already in the right context.
3649 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3650 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3651 if (NamedDC->Equals(SemaDC))
3652 return;
3653
3654 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3655 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3656 "unexpected context for redeclaration");
3657
3658 auto *LexDC = NewD->getLexicalDeclContext();
3659 auto FixSemaDC = [=](NamedDecl *D) {
3660 if (!D)
3661 return;
3662 D->setDeclContext(SemaDC);
3663 D->setLexicalDeclContext(LexDC);
3664 };
3665
3666 FixSemaDC(NewD);
3667 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3668 FixSemaDC(FD->getDescribedFunctionTemplate());
3669 else if (auto *VD = dyn_cast<VarDecl>(NewD))
3670 FixSemaDC(VD->getDescribedVarTemplate());
3671}
3672
3674 bool MergeTypeWithOld, bool NewDeclIsDefn) {
3675 // Verify the old decl was also a function.
3676 FunctionDecl *Old = OldD->getAsFunction();
3677 if (!Old) {
3678 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3679 // We don't need to check the using friend pattern from other module unit
3680 // since we should have diagnosed such cases in its unit already.
3681 if (New->getFriendObjectKind() && !OldD->isInAnotherModuleUnit()) {
3682 Diag(New->getLocation(), diag::err_using_decl_friend);
3683 Diag(Shadow->getTargetDecl()->getLocation(),
3684 diag::note_using_decl_target);
3685 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3686 << 0;
3687 return true;
3688 }
3689
3690 // Check whether the two declarations might declare the same function or
3691 // function template.
3692 if (FunctionTemplateDecl *NewTemplate =
3693 New->getDescribedFunctionTemplate()) {
3695 NewTemplate))
3696 return true;
3697 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3698 ->getAsFunction();
3699 } else {
3700 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3701 return true;
3702 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3703 }
3704 } else {
3705 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3706 << New->getDeclName();
3707 notePreviousDefinition(OldD, New->getLocation());
3708 return true;
3709 }
3710 }
3711
3712 // If the old declaration was found in an inline namespace and the new
3713 // declaration was qualified, update the DeclContext to match.
3715
3716 // If the old declaration is invalid, just give up here.
3717 if (Old->isInvalidDecl())
3718 return true;
3719
3720 // Disallow redeclaration of some builtins.
3721 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3722 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3723 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3724 << Old << Old->getType();
3725 return true;
3726 }
3727
3728 diag::kind PrevDiag;
3729 SourceLocation OldLocation;
3730 std::tie(PrevDiag, OldLocation) =
3732
3733 // Don't complain about this if we're in GNU89 mode and the old function
3734 // is an extern inline function.
3735 // Don't complain about specializations. They are not supposed to have
3736 // storage classes.
3737 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3738 New->getStorageClass() == SC_Static &&
3739 Old->hasExternalFormalLinkage() &&
3740 !New->getTemplateSpecializationInfo() &&
3742 if (getLangOpts().MicrosoftExt) {
3743 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3744 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3745 } else {
3746 Diag(New->getLocation(), diag::err_static_non_static) << New;
3747 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3748 return true;
3749 }
3750 }
3751
3752 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3753 if (!Old->hasAttr<InternalLinkageAttr>()) {
3754 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3755 << ILA;
3756 Diag(Old->getLocation(), diag::note_previous_declaration);
3757 New->dropAttr<InternalLinkageAttr>();
3758 }
3759
3760 if (auto *EA = New->getAttr<ErrorAttr>()) {
3761 if (!Old->hasAttr<ErrorAttr>()) {
3762 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3763 Diag(Old->getLocation(), diag::note_previous_declaration);
3764 New->dropAttr<ErrorAttr>();
3765 }
3766 }
3767
3769 return true;
3770
3771 if (!getLangOpts().CPlusPlus) {
3772 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3773 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3774 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3775 << New << OldOvl;
3776
3777 // Try our best to find a decl that actually has the overloadable
3778 // attribute for the note. In most cases (e.g. programs with only one
3779 // broken declaration/definition), this won't matter.
3780 //
3781 // FIXME: We could do this if we juggled some extra state in
3782 // OverloadableAttr, rather than just removing it.
3783 const Decl *DiagOld = Old;
3784 if (OldOvl) {
3785 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3786 const auto *A = D->getAttr<OverloadableAttr>();
3787 return A && !A->isImplicit();
3788 });
3789 // If we've implicitly added *all* of the overloadable attrs to this
3790 // chain, emitting a "previous redecl" note is pointless.
3791 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3792 }
3793
3794 if (DiagOld)
3795 Diag(DiagOld->getLocation(),
3796 diag::note_attribute_overloadable_prev_overload)
3797 << OldOvl;
3798
3799 if (OldOvl)
3800 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3801 else
3802 New->dropAttr<OverloadableAttr>();
3803 }
3804 }
3805
3806 // It is not permitted to redeclare an SME function with different SME
3807 // attributes.
3808 if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
3809 Diag(New->getLocation(), diag::err_sme_attr_mismatch)
3810 << New->getType() << Old->getType();
3811 Diag(OldLocation, diag::note_previous_declaration);
3812 return true;
3813 }
3814
3815 // If a function is first declared with a calling convention, but is later
3816 // declared or defined without one, all following decls assume the calling
3817 // convention of the first.
3818 //
3819 // It's OK if a function is first declared without a calling convention,
3820 // but is later declared or defined with the default calling convention.
3821 //
3822 // To test if either decl has an explicit calling convention, we look for
3823 // AttributedType sugar nodes on the type as written. If they are missing or
3824 // were canonicalized away, we assume the calling convention was implicit.
3825 //
3826 // Note also that we DO NOT return at this point, because we still have
3827 // other tests to run.
3828 QualType OldQType = Context.getCanonicalType(Old->getType());
3829 QualType NewQType = Context.getCanonicalType(New->getType());
3830 const FunctionType *OldType = cast<FunctionType>(OldQType);
3831 const FunctionType *NewType = cast<FunctionType>(NewQType);
3832 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3833 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3834 bool RequiresAdjustment = false;
3835
3836 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3838 const FunctionType *FT =
3839 First->getType().getCanonicalType()->castAs<FunctionType>();
3841 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3842 if (!NewCCExplicit) {
3843 // Inherit the CC from the previous declaration if it was specified
3844 // there but not here.
3845 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3846 RequiresAdjustment = true;
3847 } else if (Old->getBuiltinID()) {
3848 // Builtin attribute isn't propagated to the new one yet at this point,
3849 // so we check if the old one is a builtin.
3850
3851 // Calling Conventions on a Builtin aren't really useful and setting a
3852 // default calling convention and cdecl'ing some builtin redeclarations is
3853 // common, so warn and ignore the calling convention on the redeclaration.
3854 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3855 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3857 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3858 RequiresAdjustment = true;
3859 } else {
3860 // Calling conventions aren't compatible, so complain.
3861 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3862 Diag(New->getLocation(), diag::err_cconv_change)
3863 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3864 << !FirstCCExplicit
3865 << (!FirstCCExplicit ? "" :
3867
3868 // Put the note on the first decl, since it is the one that matters.
3869 Diag(First->getLocation(), diag::note_previous_declaration);
3870 return true;
3871 }
3872 }
3873
3874 // FIXME: diagnose the other way around?
3875 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3876 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3877 RequiresAdjustment = true;
3878 }
3879
3880 // If the declaration is marked with cfi_unchecked_callee but the definition
3881 // isn't, the definition is also cfi_unchecked_callee.
3882 if (auto *FPT1 = OldType->getAs<FunctionProtoType>()) {
3883 if (auto *FPT2 = NewType->getAs<FunctionProtoType>()) {
3884 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
3885 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
3886
3887 if (EPI1.CFIUncheckedCallee && !EPI2.CFIUncheckedCallee) {
3888 EPI2.CFIUncheckedCallee = true;
3889 NewQType = Context.getFunctionType(FPT2->getReturnType(),
3890 FPT2->getParamTypes(), EPI2);
3891 NewType = cast<FunctionType>(NewQType);
3892 New->setType(NewQType);
3893 }
3894 }
3895 }
3896
3897 // Merge regparm attribute.
3898 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3899 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3900 if (NewTypeInfo.getHasRegParm()) {
3901 Diag(New->getLocation(), diag::err_regparm_mismatch)
3902 << NewType->getRegParmType()
3903 << OldType->getRegParmType();
3904 Diag(OldLocation, diag::note_previous_declaration);
3905 return true;
3906 }
3907
3908 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3909 RequiresAdjustment = true;
3910 }
3911
3912 // Merge ns_returns_retained attribute.
3913 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3914 if (NewTypeInfo.getProducesResult()) {
3915 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3916 << "'ns_returns_retained'";
3917 Diag(OldLocation, diag::note_previous_declaration);
3918 return true;
3919 }
3920
3921 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3922 RequiresAdjustment = true;
3923 }
3924
3925 if (OldTypeInfo.getNoCallerSavedRegs() !=
3926 NewTypeInfo.getNoCallerSavedRegs()) {
3927 if (NewTypeInfo.getNoCallerSavedRegs()) {
3928 AnyX86NoCallerSavedRegistersAttr *Attr =
3929 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3930 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3931 Diag(OldLocation, diag::note_previous_declaration);
3932 return true;
3933 }
3934
3935 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3936 RequiresAdjustment = true;
3937 }
3938
3939 if (RequiresAdjustment) {
3940 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3941 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3942 New->setType(QualType(AdjustedType, 0));
3943 NewQType = Context.getCanonicalType(New->getType());
3944 }
3945
3946 // If this redeclaration makes the function inline, we may need to add it to
3947 // UndefinedButUsed.
3948 if (!Old->isInlined() && New->isInlined() && !New->hasAttr<GNUInlineAttr>() &&
3949 !getLangOpts().GNUInline && Old->isUsed(false) && !Old->isDefined() &&
3950 !New->isThisDeclarationADefinition() && !Old->isInAnotherModuleUnit())
3951 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3952 SourceLocation()));
3953
3954 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3955 // about it.
3956 if (New->hasAttr<GNUInlineAttr>() &&
3957 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3958 UndefinedButUsed.erase(Old->getCanonicalDecl());
3959 }
3960
3961 // If pass_object_size params don't match up perfectly, this isn't a valid
3962 // redeclaration.
3963 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3965 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3966 << New->getDeclName();
3967 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3968 return true;
3969 }
3970
3971 QualType OldQTypeForComparison = OldQType;
3972 if (Context.hasAnyFunctionEffects()) {
3973 const auto OldFX = Old->getFunctionEffects();
3974 const auto NewFX = New->getFunctionEffects();
3975 if (OldFX != NewFX) {
3976 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
3977 for (const auto &Diff : Diffs) {
3978 if (Diff.shouldDiagnoseRedeclaration(*Old, OldFX, *New, NewFX)) {
3979 Diag(New->getLocation(),
3980 diag::warn_mismatched_func_effect_redeclaration)
3981 << Diff.effectName();
3982 Diag(Old->getLocation(), diag::note_previous_declaration);
3983 }
3984 }
3985 // Following a warning, we could skip merging effects from the previous
3986 // declaration, but that would trigger an additional "conflicting types"
3987 // error.
3988 if (const auto *NewFPT = NewQType->getAs<FunctionProtoType>()) {
3990 FunctionEffectSet MergedFX =
3991 FunctionEffectSet::getUnion(OldFX, NewFX, MergeErrs);
3992 if (!MergeErrs.empty())
3993 diagnoseFunctionEffectMergeConflicts(MergeErrs, New->getLocation(),
3994 Old->getLocation());
3995
3996 FunctionProtoType::ExtProtoInfo EPI = NewFPT->getExtProtoInfo();
3997 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
3998 QualType ModQT = Context.getFunctionType(NewFPT->getReturnType(),
3999 NewFPT->getParamTypes(), EPI);
4000
4001 New->setType(ModQT);
4002 NewQType = New->getType();
4003
4004 // Revise OldQTForComparison to include the merged effects,
4005 // so as not to fail due to differences later.
4006 if (const auto *OldFPT = OldQType->getAs<FunctionProtoType>()) {
4007 EPI = OldFPT->getExtProtoInfo();
4008 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
4009 OldQTypeForComparison = Context.getFunctionType(
4010 OldFPT->getReturnType(), OldFPT->getParamTypes(), EPI);
4011 }
4012 if (OldFX.empty()) {
4013 // A redeclaration may add the attribute to a previously seen function
4014 // body which needs to be verified.
4015 maybeAddDeclWithEffects(Old, MergedFX);
4016 }
4017 }
4018 }
4019 }
4020
4021 if (getLangOpts().CPlusPlus) {
4022 OldQType = Context.getCanonicalType(Old->getType());
4023 NewQType = Context.getCanonicalType(New->getType());
4024
4025 // Go back to the type source info to compare the declared return types,
4026 // per C++1y [dcl.type.auto]p13:
4027 // Redeclarations or specializations of a function or function template
4028 // with a declared return type that uses a placeholder type shall also
4029 // use that placeholder, not a deduced type.
4030 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
4031 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
4032 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
4033 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
4034 OldDeclaredReturnType)) {
4035 QualType ResQT;
4036 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
4037 OldDeclaredReturnType->isObjCObjectPointerType())
4038 // FIXME: This does the wrong thing for a deduced return type.
4039 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
4040 if (ResQT.isNull()) {
4041 if (New->isCXXClassMember() && New->isOutOfLine())
4042 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
4043 << New << New->getReturnTypeSourceRange();
4044 else if (Old->isExternC() && New->isExternC() &&
4045 !Old->hasAttr<OverloadableAttr>() &&
4046 !New->hasAttr<OverloadableAttr>())
4047 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4048 else
4049 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
4050 << New->getReturnTypeSourceRange();
4051 Diag(OldLocation, PrevDiag) << Old << Old->getType()
4052 << Old->getReturnTypeSourceRange();
4053 return true;
4054 }
4055 else
4056 NewQType = ResQT;
4057 }
4058
4059 QualType OldReturnType = OldType->getReturnType();
4060 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
4061 if (OldReturnType != NewReturnType) {
4062 // If this function has a deduced return type and has already been
4063 // defined, copy the deduced value from the old declaration.
4064 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
4065 if (OldAT && OldAT->isDeduced()) {
4066 QualType DT = OldAT->getDeducedType();
4067 if (DT.isNull()) {
4068 New->setType(SubstAutoTypeDependent(New->getType()));
4069 NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
4070 } else {
4071 New->setType(SubstAutoType(New->getType(), DT));
4072 NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
4073 }
4074 }
4075 }
4076
4077 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
4078 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
4079 if (OldMethod && NewMethod) {
4080 // Preserve triviality.
4081 NewMethod->setTrivial(OldMethod->isTrivial());
4082
4083 // MSVC allows explicit template specialization at class scope:
4084 // 2 CXXMethodDecls referring to the same function will be injected.
4085 // We don't want a redeclaration error.
4086 bool IsClassScopeExplicitSpecialization =
4087 OldMethod->isFunctionTemplateSpecialization() &&
4089 bool isFriend = NewMethod->getFriendObjectKind();
4090
4091 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
4092 !IsClassScopeExplicitSpecialization) {
4093 // -- Member function declarations with the same name and the
4094 // same parameter types cannot be overloaded if any of them
4095 // is a static member function declaration.
4096 if (OldMethod->isStatic() != NewMethod->isStatic()) {
4097 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
4098 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4099 return true;
4100 }
4101
4102 // C++ [class.mem]p1:
4103 // [...] A member shall not be declared twice in the
4104 // member-specification, except that a nested class or member
4105 // class template can be declared and then later defined.
4106 if (!inTemplateInstantiation()) {
4107 unsigned NewDiag;
4108 if (isa<CXXConstructorDecl>(OldMethod))
4109 NewDiag = diag::err_constructor_redeclared;
4110 else if (isa<CXXDestructorDecl>(NewMethod))
4111 NewDiag = diag::err_destructor_redeclared;
4112 else if (isa<CXXConversionDecl>(NewMethod))
4113 NewDiag = diag::err_conv_function_redeclared;
4114 else
4115 NewDiag = diag::err_member_redeclared;
4116
4117 Diag(New->getLocation(), NewDiag);
4118 } else {
4119 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
4120 << New << New->getType();
4121 }
4122 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4123 return true;
4124
4125 // Complain if this is an explicit declaration of a special
4126 // member that was initially declared implicitly.
4127 //
4128 // As an exception, it's okay to befriend such methods in order
4129 // to permit the implicit constructor/destructor/operator calls.
4130 } else if (OldMethod->isImplicit()) {
4131 if (isFriend) {
4132 NewMethod->setImplicit();
4133 } else {
4134 Diag(NewMethod->getLocation(),
4135 diag::err_definition_of_implicitly_declared_member)
4136 << New << getSpecialMember(OldMethod);
4137 return true;
4138 }
4139 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
4140 Diag(NewMethod->getLocation(),
4141 diag::err_definition_of_explicitly_defaulted_member)
4142 << getSpecialMember(OldMethod);
4143 return true;
4144 }
4145 }
4146
4147 // C++1z [over.load]p2
4148 // Certain function declarations cannot be overloaded:
4149 // -- Function declarations that differ only in the return type,
4150 // the exception specification, or both cannot be overloaded.
4151
4152 // Check the exception specifications match. This may recompute the type of
4153 // both Old and New if it resolved exception specifications, so grab the
4154 // types again after this. Because this updates the type, we do this before
4155 // any of the other checks below, which may update the "de facto" NewQType
4156 // but do not necessarily update the type of New.
4158 return true;
4159
4160 // C++11 [dcl.attr.noreturn]p1:
4161 // The first declaration of a function shall specify the noreturn
4162 // attribute if any declaration of that function specifies the noreturn
4163 // attribute.
4164 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4165 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4166 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
4167 << NRA;
4168 Diag(Old->getLocation(), diag::note_previous_declaration);
4169 }
4170
4171 // C++11 [dcl.attr.depend]p2:
4172 // The first declaration of a function shall specify the
4173 // carries_dependency attribute for its declarator-id if any declaration
4174 // of the function specifies the carries_dependency attribute.
4175 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
4176 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
4177 Diag(CDA->getLocation(),
4178 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
4179 Diag(Old->getFirstDecl()->getLocation(),
4180 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
4181 }
4182
4183 // SYCL 2020 section 5.10.1, "SYCL functions and member functions linkage":
4184 // When a function is declared with SYCL_EXTERNAL, that macro must be
4185 // used on the first declaration of that function in the translation unit.
4186 // Redeclarations of the function in the same translation unit may
4187 // optionally use SYCL_EXTERNAL, but this is not required.
4188 const SYCLExternalAttr *SEA = New->getAttr<SYCLExternalAttr>();
4189 if (SEA && !Old->hasAttr<SYCLExternalAttr>()) {
4190 Diag(SEA->getLocation(), diag::warn_sycl_external_missing_on_first_decl)
4191 << SEA;
4192 Diag(Old->getLocation(), diag::note_previous_declaration);
4193 }
4194
4195 // (C++98 8.3.5p3):
4196 // All declarations for a function shall agree exactly in both the
4197 // return type and the parameter-type-list.
4198 // We also want to respect all the extended bits except noreturn.
4199
4200 // noreturn should now match unless the old type info didn't have it.
4201 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4202 auto *OldType = OldQTypeForComparison->castAs<FunctionProtoType>();
4203 const FunctionType *OldTypeForComparison
4204 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
4205 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4206 assert(OldQTypeForComparison.isCanonical());
4207 }
4208
4210 // As a special case, retain the language linkage from previous
4211 // declarations of a friend function as an extension.
4212 //
4213 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4214 // and is useful because there's otherwise no way to specify language
4215 // linkage within class scope.
4216 //
4217 // Check cautiously as the friend object kind isn't yet complete.
4218 if (New->getFriendObjectKind() != Decl::FOK_None) {
4219 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
4220 Diag(OldLocation, PrevDiag);
4221 } else {
4222 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4223 Diag(OldLocation, PrevDiag);
4224 return true;
4225 }
4226 }
4227
4228 // HLSL check parameters for matching ABI specifications.
4229 if (getLangOpts().HLSL) {
4230 if (HLSL().CheckCompatibleParameterABI(New, Old))
4231 return true;
4232
4233 // If no errors are generated when checking parameter ABIs we can check if
4234 // the two declarations have the same type ignoring the ABIs and if so,
4235 // the declarations can be merged. This case for merging is only valid in
4236 // HLSL because there are no valid cases of merging mismatched parameter
4237 // ABIs except the HLSL implicit in and explicit in.
4238 if (Context.hasSameFunctionTypeIgnoringParamABI(OldQTypeForComparison,
4239 NewQType))
4240 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4241 // Fall through for conflicting redeclarations and redefinitions.
4242 }
4243
4244 // If the function types are compatible, merge the declarations. Ignore the
4245 // exception specifier because it was already checked above in
4246 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4247 // about incompatible types under -fms-compatibility.
4248 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
4249 NewQType))
4250 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4251
4252 // If the types are imprecise (due to dependent constructs in friends or
4253 // local extern declarations), it's OK if they differ. We'll check again
4254 // during instantiation.
4255 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
4256 return false;
4257
4258 // Fall through for conflicting redeclarations and redefinitions.
4259 }
4260
4261 // C: Function types need to be compatible, not identical. This handles
4262 // duplicate function decls like "void f(int); void f(enum X);" properly.
4263 if (!getLangOpts().CPlusPlus) {
4264 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4265 // type is specified by a function definition that contains a (possibly
4266 // empty) identifier list, both shall agree in the number of parameters
4267 // and the type of each parameter shall be compatible with the type that
4268 // results from the application of default argument promotions to the
4269 // type of the corresponding identifier. ...
4270 // This cannot be handled by ASTContext::typesAreCompatible() because that
4271 // doesn't know whether the function type is for a definition or not when
4272 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4273 // we need to cover here is that the number of arguments agree as the
4274 // default argument promotion rules were already checked by
4275 // ASTContext::typesAreCompatible().
4276 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4277 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4278 if (Old->hasInheritedPrototype())
4279 Old = Old->getCanonicalDecl();
4280 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4281 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
4282 return true;
4283 }
4284
4285 // If we are merging two functions where only one of them has a prototype,
4286 // we may have enough information to decide to issue a diagnostic that the
4287 // function without a prototype will change behavior in C23. This handles
4288 // cases like:
4289 // void i(); void i(int j);
4290 // void i(int j); void i();
4291 // void i(); void i(int j) {}
4292 // See ActOnFinishFunctionBody() for other cases of the behavior change
4293 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4294 // type without a prototype.
4295 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4296 !New->isImplicit() && !Old->isImplicit()) {
4297 const FunctionDecl *WithProto, *WithoutProto;
4298 if (New->hasWrittenPrototype()) {
4299 WithProto = New;
4300 WithoutProto = Old;
4301 } else {
4302 WithProto = Old;
4303 WithoutProto = New;
4304 }
4305
4306 if (WithProto->getNumParams() != 0) {
4307 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4308 // The one without the prototype will be changing behavior in C23, so
4309 // warn about that one so long as it's a user-visible declaration.
4310 bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4311 if (WithoutProto == New)
4312 IsWithoutProtoADef = NewDeclIsDefn;
4313 else
4314 IsWithProtoADef = NewDeclIsDefn;
4315 Diag(WithoutProto->getLocation(),
4316 diag::warn_non_prototype_changes_behavior)
4317 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4318 << (WithoutProto == Old) << IsWithProtoADef;
4319
4320 // The reason the one without the prototype will be changing behavior
4321 // is because of the one with the prototype, so note that so long as
4322 // it's a user-visible declaration. There is one exception to this:
4323 // when the new declaration is a definition without a prototype, the
4324 // old declaration with a prototype is not the cause of the issue,
4325 // and that does not need to be noted because the one with a
4326 // prototype will not change behavior in C23.
4327 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4328 !IsWithoutProtoADef)
4329 Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
4330 }
4331 }
4332 }
4333
4334 if (Context.typesAreCompatible(OldQType, NewQType)) {
4335 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4336 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4337 const FunctionProtoType *OldProto = nullptr;
4338 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
4339 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
4340 // The old declaration provided a function prototype, but the
4341 // new declaration does not. Merge in the prototype.
4342 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4343 NewQType = Context.getFunctionType(NewFuncType->getReturnType(),
4344 OldProto->getParamTypes(),
4345 OldProto->getExtProtoInfo());
4346 New->setType(NewQType);
4347 New->setHasInheritedPrototype();
4348
4349 // Synthesize parameters with the same types.
4351 for (const auto &ParamType : OldProto->param_types()) {
4353 Context, New, SourceLocation(), SourceLocation(), nullptr,
4354 ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4355 Param->setScopeInfo(0, Params.size());
4356 Param->setImplicit();
4357 Params.push_back(Param);
4358 }
4359
4360 New->setParams(Params);
4361 }
4362
4363 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4364 }
4365 }
4366
4367 // Check if the function types are compatible when pointer size address
4368 // spaces are ignored.
4369 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4370 return false;
4371
4372 // GNU C permits a K&R definition to follow a prototype declaration
4373 // if the declared types of the parameters in the K&R definition
4374 // match the types in the prototype declaration, even when the
4375 // promoted types of the parameters from the K&R definition differ
4376 // from the types in the prototype. GCC then keeps the types from
4377 // the prototype.
4378 //
4379 // If a variadic prototype is followed by a non-variadic K&R definition,
4380 // the K&R definition becomes variadic. This is sort of an edge case, but
4381 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4382 // C99 6.9.1p8.
4383 if (!getLangOpts().CPlusPlus &&
4384 Old->hasPrototype() && !New->hasPrototype() &&
4385 New->getType()->getAs<FunctionProtoType>() &&
4386 Old->getNumParams() == New->getNumParams()) {
4389 const FunctionProtoType *OldProto
4390 = Old->getType()->getAs<FunctionProtoType>();
4391 const FunctionProtoType *NewProto
4392 = New->getType()->getAs<FunctionProtoType>();
4393
4394 // Determine whether this is the GNU C extension.
4395 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4396 NewProto->getReturnType());
4397 bool LooseCompatible = !MergedReturn.isNull();
4398 for (unsigned Idx = 0, End = Old->getNumParams();
4399 LooseCompatible && Idx != End; ++Idx) {
4400 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4401 ParmVarDecl *NewParm = New->getParamDecl(Idx);
4402 if (Context.typesAreCompatible(OldParm->getType(),
4403 NewProto->getParamType(Idx))) {
4404 ArgTypes.push_back(NewParm->getType());
4405 } else if (Context.typesAreCompatible(OldParm->getType(),
4406 NewParm->getType(),
4407 /*CompareUnqualified=*/true)) {
4408 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4409 NewProto->getParamType(Idx) };
4410 Warnings.push_back(Warn);
4411 ArgTypes.push_back(NewParm->getType());
4412 } else
4413 LooseCompatible = false;
4414 }
4415
4416 if (LooseCompatible) {
4417 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4418 Diag(Warnings[Warn].NewParm->getLocation(),
4419 diag::ext_param_promoted_not_compatible_with_prototype)
4420 << Warnings[Warn].PromotedType
4421 << Warnings[Warn].OldParm->getType();
4422 if (Warnings[Warn].OldParm->getLocation().isValid())
4423 Diag(Warnings[Warn].OldParm->getLocation(),
4424 diag::note_previous_declaration);
4425 }
4426
4427 if (MergeTypeWithOld)
4428 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4429 OldProto->getExtProtoInfo()));
4430 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4431 }
4432
4433 // Fall through to diagnose conflicting types.
4434 }
4435
4436 // A function that has already been declared has been redeclared or
4437 // defined with a different type; show an appropriate diagnostic.
4438
4439 // If the previous declaration was an implicitly-generated builtin
4440 // declaration, then at the very least we should use a specialized note.
4441 unsigned BuiltinID;
4442 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4443 // If it's actually a library-defined builtin function like 'malloc'
4444 // or 'printf', just warn about the incompatible redeclaration.
4445 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4446 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4447 Diag(OldLocation, diag::note_previous_builtin_declaration)
4448 << Old << Old->getType();
4449 return false;
4450 }
4451
4452 PrevDiag = diag::note_previous_builtin_declaration;
4453 }
4454
4455 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4456 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4457 return true;
4458}
4459
4461 Scope *S, bool MergeTypeWithOld) {
4462 // Merge the attributes
4464
4465 // Merge "pure" flag.
4466 if (Old->isPureVirtual())
4467 New->setIsPureVirtual();
4468
4469 // Merge "used" flag.
4470 if (Old->getMostRecentDecl()->isUsed(false))
4471 New->setIsUsed();
4472
4473 // Merge attributes from the parameters. These can mismatch with K&R
4474 // declarations.
4475 if (New->getNumParams() == Old->getNumParams())
4476 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4477 ParmVarDecl *NewParam = New->getParamDecl(i);
4478 ParmVarDecl *OldParam = Old->getParamDecl(i);
4479 mergeParamDeclAttributes(NewParam, OldParam, *this);
4480 mergeParamDeclTypes(NewParam, OldParam, *this);
4481 }
4482
4483 if (getLangOpts().CPlusPlus)
4484 return MergeCXXFunctionDecl(New, Old, S);
4485
4486 // Merge the function types so the we get the composite types for the return
4487 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4488 // was visible.
4489 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4490 if (!Merged.isNull() && MergeTypeWithOld)
4491 New->setType(Merged);
4492
4493 return false;
4494}
4495
4497 ObjCMethodDecl *oldMethod) {
4498 // Merge the attributes, including deprecated/unavailable
4499 AvailabilityMergeKind MergeKind =
4501 ? (oldMethod->isOptional()
4504 : isa<ObjCImplDecl>(newMethod->getDeclContext())
4507
4508 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4509
4510 // Merge attributes from the parameters.
4512 oe = oldMethod->param_end();
4514 ni = newMethod->param_begin(), ne = newMethod->param_end();
4515 ni != ne && oi != oe; ++ni, ++oi)
4516 mergeParamDeclAttributes(*ni, *oi, *this);
4517
4518 ObjC().CheckObjCMethodOverride(newMethod, oldMethod);
4519}
4520
4522 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4523
4524 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
4525 ? diag::err_redefinition_different_type
4526 : diag::err_redeclaration_different_type)
4527 << New->getDeclName() << New->getType() << Old->getType();
4528
4529 diag::kind PrevDiag;
4530 SourceLocation OldLocation;
4531 std::tie(PrevDiag, OldLocation)
4533 S.Diag(OldLocation, PrevDiag) << Old << Old->getType();
4534 New->setInvalidDecl();
4535}
4536
4538 bool MergeTypeWithOld) {
4539 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4540 return;
4541
4542 QualType MergedT;
4543 if (getLangOpts().CPlusPlus) {
4544 if (New->getType()->isUndeducedType()) {
4545 // We don't know what the new type is until the initializer is attached.
4546 return;
4547 } else if (Context.hasSameType(New->getType(), Old->getType())) {
4548 // These could still be something that needs exception specs checked.
4549 return MergeVarDeclExceptionSpecs(New, Old);
4550 }
4551 // C++ [basic.link]p10:
4552 // [...] the types specified by all declarations referring to a given
4553 // object or function shall be identical, except that declarations for an
4554 // array object can specify array types that differ by the presence or
4555 // absence of a major array bound (8.3.4).
4556 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4557 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4558 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4559
4560 // We are merging a variable declaration New into Old. If it has an array
4561 // bound, and that bound differs from Old's bound, we should diagnose the
4562 // mismatch.
4563 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4564 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4565 PrevVD = PrevVD->getPreviousDecl()) {
4566 QualType PrevVDTy = PrevVD->getType();
4567 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4568 continue;
4569
4570 if (!Context.hasSameType(New->getType(), PrevVDTy))
4571 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4572 }
4573 }
4574
4575 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4576 if (Context.hasSameType(OldArray->getElementType(),
4577 NewArray->getElementType()))
4578 MergedT = New->getType();
4579 }
4580 // FIXME: Check visibility. New is hidden but has a complete type. If New
4581 // has no array bound, it should not inherit one from Old, if Old is not
4582 // visible.
4583 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4584 if (Context.hasSameType(OldArray->getElementType(),
4585 NewArray->getElementType()))
4586 MergedT = Old->getType();
4587 }
4588 }
4589 else if (New->getType()->isObjCObjectPointerType() &&
4590 Old->getType()->isObjCObjectPointerType()) {
4591 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4592 Old->getType());
4593 }
4594 } else {
4595 // C 6.2.7p2:
4596 // All declarations that refer to the same object or function shall have
4597 // compatible type.
4598 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4599 }
4600 if (MergedT.isNull()) {
4601 // It's OK if we couldn't merge types if either type is dependent, for a
4602 // block-scope variable. In other cases (static data members of class
4603 // templates, variable templates, ...), we require the types to be
4604 // equivalent.
4605 // FIXME: The C++ standard doesn't say anything about this.
4606 if ((New->getType()->isDependentType() ||
4607 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4608 // If the old type was dependent, we can't merge with it, so the new type
4609 // becomes dependent for now. We'll reproduce the original type when we
4610 // instantiate the TypeSourceInfo for the variable.
4611 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4612 New->setType(Context.DependentTy);
4613 return;
4614 }
4615 return diagnoseVarDeclTypeMismatch(*this, New, Old);
4616 }
4617
4618 // Don't actually update the type on the new declaration if the old
4619 // declaration was an extern declaration in a different scope.
4620 if (MergeTypeWithOld)
4621 New->setType(MergedT);
4622}
4623
4624static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4626 // C11 6.2.7p4:
4627 // For an identifier with internal or external linkage declared
4628 // in a scope in which a prior declaration of that identifier is
4629 // visible, if the prior declaration specifies internal or
4630 // external linkage, the type of the identifier at the later
4631 // declaration becomes the composite type.
4632 //
4633 // If the variable isn't visible, we do not merge with its type.
4634 if (Previous.isShadowed())
4635 return false;
4636
4637 if (S.getLangOpts().CPlusPlus) {
4638 // C++11 [dcl.array]p3:
4639 // If there is a preceding declaration of the entity in the same
4640 // scope in which the bound was specified, an omitted array bound
4641 // is taken to be the same as in that earlier declaration.
4642 return NewVD->isPreviousDeclInSameBlockScope() ||
4643 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4645 } else {
4646 // If the old declaration was function-local, don't merge with its
4647 // type unless we're in the same function.
4648 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4649 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4650 }
4651}
4652
4654 // If the new decl is already invalid, don't do any other checking.
4655 if (New->isInvalidDecl())
4656 return;
4657
4658 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4659 return;
4660
4661 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4662
4663 // Verify the old decl was also a variable or variable template.
4664 VarDecl *Old = nullptr;
4665 VarTemplateDecl *OldTemplate = nullptr;
4666 if (Previous.isSingleResult()) {
4667 if (NewTemplate) {
4668 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4669 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4670
4671 if (auto *Shadow =
4672 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4673 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4674 return New->setInvalidDecl();
4675 } else {
4676 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4677
4678 if (auto *Shadow =
4679 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4680 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4681 return New->setInvalidDecl();
4682 }
4683 }
4684 if (!Old) {
4685 Diag(New->getLocation(), diag::err_redefinition_different_kind)
4686 << New->getDeclName();
4687 notePreviousDefinition(Previous.getRepresentativeDecl(),
4688 New->getLocation());
4689 return New->setInvalidDecl();
4690 }
4691
4692 // If the old declaration was found in an inline namespace and the new
4693 // declaration was qualified, update the DeclContext to match.
4695
4696 // Ensure the template parameters are compatible.
4697 if (NewTemplate &&
4699 OldTemplate->getTemplateParameters(),
4700 /*Complain=*/true, TPL_TemplateMatch))
4701 return New->setInvalidDecl();
4702
4703 // C++ [class.mem]p1:
4704 // A member shall not be declared twice in the member-specification [...]
4705 //
4706 // Here, we need only consider static data members.
4707 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4708 Diag(New->getLocation(), diag::err_duplicate_member)
4709 << New->getIdentifier();
4710 Diag(Old->getLocation(), diag::note_previous_declaration);
4711 New->setInvalidDecl();
4712 }
4713
4715 // Warn if an already-defined variable is made a weak_import in a subsequent
4716 // declaration
4717 if (New->hasAttr<WeakImportAttr>())
4718 for (auto *D = Old; D; D = D->getPreviousDecl()) {
4719 if (D->isThisDeclarationADefinition() != VarDecl::DeclarationOnly) {
4720 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4721 Diag(D->getLocation(), diag::note_previous_definition);
4722 // Remove weak_import attribute on new declaration.
4723 New->dropAttr<WeakImportAttr>();
4724 break;
4725 }
4726 }
4727
4728 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4729 if (!Old->hasAttr<InternalLinkageAttr>()) {
4730 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4731 << ILA;
4732 Diag(Old->getLocation(), diag::note_previous_declaration);
4733 New->dropAttr<InternalLinkageAttr>();
4734 }
4735
4736 // Merge the types.
4737 VarDecl *MostRecent = Old->getMostRecentDecl();
4738 if (MostRecent != Old) {
4739 MergeVarDeclTypes(New, MostRecent,
4740 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4741 if (New->isInvalidDecl())
4742 return;
4743 }
4744
4746 if (New->isInvalidDecl())
4747 return;
4748
4749 diag::kind PrevDiag;
4750 SourceLocation OldLocation;
4751 std::tie(PrevDiag, OldLocation) =
4753
4754 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4755 if (New->getStorageClass() == SC_Static &&
4756 !New->isStaticDataMember() &&
4757 Old->hasExternalFormalLinkage()) {
4758 if (getLangOpts().MicrosoftExt) {
4759 Diag(New->getLocation(), diag::ext_static_non_static)
4760 << New->getDeclName();
4761 Diag(OldLocation, PrevDiag);
4762 } else {
4763 Diag(New->getLocation(), diag::err_static_non_static)
4764 << New->getDeclName();
4765 Diag(OldLocation, PrevDiag);
4766 return New->setInvalidDecl();
4767 }
4768 }
4769 // C99 6.2.2p4:
4770 // For an identifier declared with the storage-class specifier
4771 // extern in a scope in which a prior declaration of that
4772 // identifier is visible,23) if the prior declaration specifies
4773 // internal or external linkage, the linkage of the identifier at
4774 // the later declaration is the same as the linkage specified at
4775 // the prior declaration. If no prior declaration is visible, or
4776 // if the prior declaration specifies no linkage, then the
4777 // identifier has external linkage.
4778 if (New->hasExternalStorage() && Old->hasLinkage())
4779 /* Okay */;
4780 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4781 !New->isStaticDataMember() &&
4783 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4784 Diag(OldLocation, PrevDiag);
4785 return New->setInvalidDecl();
4786 }
4787
4788 // Check if extern is followed by non-extern and vice-versa.
4789 if (New->hasExternalStorage() &&
4790 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4791 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4792 Diag(OldLocation, PrevDiag);
4793 return New->setInvalidDecl();
4794 }
4795 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4796 !New->hasExternalStorage()) {
4797 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4798 Diag(OldLocation, PrevDiag);
4799 return New->setInvalidDecl();
4800 }
4801
4803 return;
4804
4805 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4806
4807 // FIXME: The test for external storage here seems wrong? We still
4808 // need to check for mismatches.
4809 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4810 // Don't complain about out-of-line definitions of static members.
4811 !(Old->getLexicalDeclContext()->isRecord() &&
4812 !New->getLexicalDeclContext()->isRecord())) {
4813 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4814 Diag(OldLocation, PrevDiag);
4815 return New->setInvalidDecl();
4816 }
4817
4818 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4819 if (VarDecl *Def = Old->getDefinition()) {
4820 // C++1z [dcl.fcn.spec]p4:
4821 // If the definition of a variable appears in a translation unit before
4822 // its first declaration as inline, the program is ill-formed.
4823 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4824 Diag(Def->getLocation(), diag::note_previous_definition);
4825 }
4826 }
4827
4828 // If this redeclaration makes the variable inline, we may need to add it to
4829 // UndefinedButUsed.
4830 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4831 !Old->getDefinition() && !New->isThisDeclarationADefinition() &&
4832 !Old->isInAnotherModuleUnit())
4833 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4834 SourceLocation()));
4835
4836 if (New->getTLSKind() != Old->getTLSKind()) {
4837 if (!Old->getTLSKind()) {
4838 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4839 Diag(OldLocation, PrevDiag);
4840 } else if (!New->getTLSKind()) {
4841 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4842 Diag(OldLocation, PrevDiag);
4843 } else {
4844 // Do not allow redeclaration to change the variable between requiring
4845 // static and dynamic initialization.
4846 // FIXME: GCC allows this, but uses the TLS keyword on the first
4847 // declaration to determine the kind. Do we need to be compatible here?
4848 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4849 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4850 Diag(OldLocation, PrevDiag);
4851 }
4852 }
4853
4854 // C++ doesn't have tentative definitions, so go right ahead and check here.
4855 if (getLangOpts().CPlusPlus) {
4856 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4857 Old->getCanonicalDecl()->isConstexpr()) {
4858 // This definition won't be a definition any more once it's been merged.
4859 Diag(New->getLocation(),
4860 diag::warn_deprecated_redundant_constexpr_static_def);
4861 } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4862 VarDecl *Def = Old->getDefinition();
4863 if (Def && checkVarDeclRedefinition(Def, New))
4864 return;
4865 }
4866 } else {
4867 // C++ may not have a tentative definition rule, but it has a different
4868 // rule about what constitutes a definition in the first place. See
4869 // [basic.def]p2 for details, but the basic idea is: if the old declaration
4870 // contains the extern specifier and doesn't have an initializer, it's fine
4871 // in C++.
4872 if (Old->getStorageClass() != SC_Extern || Old->hasInit()) {
4873 Diag(New->getLocation(), diag::warn_cxx_compat_tentative_definition)
4874 << New;
4875 Diag(Old->getLocation(), diag::note_previous_declaration);
4876 }
4877 }
4878
4880 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4881 Diag(OldLocation, PrevDiag);
4882 New->setInvalidDecl();
4883 return;
4884 }
4885
4886 // Merge "used" flag.
4887 if (Old->getMostRecentDecl()->isUsed(false))
4888 New->setIsUsed();
4889
4890 // Keep a chain of previous declarations.
4891 New->setPreviousDecl(Old);
4892 if (NewTemplate)
4893 NewTemplate->setPreviousDecl(OldTemplate);
4894
4895 // Inherit access appropriately.
4896 New->setAccess(Old->getAccess());
4897 if (NewTemplate)
4898 NewTemplate->setAccess(New->getAccess());
4899
4900 if (Old->isInline())
4901 New->setImplicitlyInline();
4902}
4903
4906 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4907 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4908 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4909 auto FOld = SrcMgr.getFileEntryRefForID(FOldDecLoc.first);
4910 auto &HSI = PP.getHeaderSearchInfo();
4911 StringRef HdrFilename =
4912 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4913
4914 auto noteFromModuleOrInclude = [&](Module *Mod,
4915 SourceLocation IncLoc) -> bool {
4916 // Redefinition errors with modules are common with non modular mapped
4917 // headers, example: a non-modular header H in module A that also gets
4918 // included directly in a TU. Pointing twice to the same header/definition
4919 // is confusing, try to get better diagnostics when modules is on.
4920 if (IncLoc.isValid()) {
4921 if (Mod) {
4922 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4923 << HdrFilename.str() << Mod->getFullModuleName();
4924 if (!Mod->DefinitionLoc.isInvalid())
4925 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4926 << Mod->getFullModuleName();
4927 } else {
4928 Diag(IncLoc, diag::note_redefinition_include_same_file)
4929 << HdrFilename.str();
4930 }
4931 return true;
4932 }
4933
4934 return false;
4935 };
4936
4937 // Is it the same file and same offset? Provide more information on why
4938 // this leads to a redefinition error.
4939 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4940 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4941 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4942 bool EmittedDiag =
4943 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4944 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4945
4946 // If the header has no guards, emit a note suggesting one.
4947 if (FOld && !HSI.isFileMultipleIncludeGuarded(*FOld))
4948 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4949
4950 if (EmittedDiag)
4951 return;
4952 }
4953
4954 // Redefinition coming from different files or couldn't do better above.
4955 if (Old->getLocation().isValid())
4956 Diag(Old->getLocation(), diag::note_previous_definition);
4957}
4958
4960 if (!hasVisibleDefinition(Old) &&
4961 (New->getFormalLinkage() == Linkage::Internal || New->isInline() ||
4963 New->getDescribedVarTemplate() || New->getNumTemplateParameterLists() ||
4964 New->getDeclContext()->isDependentContext() ||
4965 New->hasAttr<SelectAnyAttr>())) {
4966 // The previous definition is hidden, and multiple definitions are
4967 // permitted (in separate TUs). Demote this to a declaration.
4968 New->demoteThisDefinitionToDeclaration();
4969
4970 // Make the canonical definition visible.
4971 if (auto *OldTD = Old->getDescribedVarTemplate())
4974 return false;
4975 } else {
4976 Diag(New->getLocation(), diag::err_redefinition) << New;
4977 notePreviousDefinition(Old, New->getLocation());
4978 New->setInvalidDecl();
4979 return true;
4980 }
4981}
4982
4984 DeclSpec &DS,
4985 const ParsedAttributesView &DeclAttrs,
4986 RecordDecl *&AnonRecord) {
4988 S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);
4989}
4990
4991// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4992// disambiguate entities defined in different scopes.
4993// While the VS2015 ABI fixes potential miscompiles, it is also breaks
4994// compatibility.
4995// We will pick our mangling number depending on which version of MSVC is being
4996// targeted.
4997static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
5001}
5002
5003void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
5004 if (!Context.getLangOpts().CPlusPlus)
5005 return;
5006
5007 if (isa<CXXRecordDecl>(Tag->getParent())) {
5008 // If this tag is the direct child of a class, number it if
5009 // it is anonymous.
5010 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
5011 return;
5013 Context.getManglingNumberContext(Tag->getParent());
5014 Context.setManglingNumber(
5015 Tag, MCtx.getManglingNumber(
5016 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
5017 return;
5018 }
5019
5020 // If this tag isn't a direct child of a class, number it if it is local.
5022 Decl *ManglingContextDecl;
5023 std::tie(MCtx, ManglingContextDecl) =
5024 getCurrentMangleNumberContext(Tag->getDeclContext());
5025 if (MCtx) {
5026 Context.setManglingNumber(
5027 Tag, MCtx->getManglingNumber(
5028 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
5029 }
5030}
5031
5032namespace {
5033struct NonCLikeKind {
5034 enum {
5035 None,
5036 BaseClass,
5037 DefaultMemberInit,
5038 Lambda,
5039 Friend,
5040 OtherMember,
5041 Invalid,
5042 } Kind = None;
5043 SourceRange Range;
5044
5045 explicit operator bool() { return Kind != None; }
5046};
5047}
5048
5049/// Determine whether a class is C-like, according to the rules of C++
5050/// [dcl.typedef] for anonymous classes with typedef names for linkage.
5051static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
5052 if (RD->isInvalidDecl())
5053 return {NonCLikeKind::Invalid, {}};
5054
5055 // C++ [dcl.typedef]p9: [P1766R1]
5056 // An unnamed class with a typedef name for linkage purposes shall not
5057 //
5058 // -- have any base classes
5059 if (RD->getNumBases())
5060 return {NonCLikeKind::BaseClass,
5062 RD->bases_end()[-1].getEndLoc())};
5063 bool Invalid = false;
5064 for (Decl *D : RD->decls()) {
5065 // Don't complain about things we already diagnosed.
5066 if (D->isInvalidDecl()) {
5067 Invalid = true;
5068 continue;
5069 }
5070
5071 // -- have any [...] default member initializers
5072 if (auto *FD = dyn_cast<FieldDecl>(D)) {
5073 if (FD->hasInClassInitializer()) {
5074 auto *Init = FD->getInClassInitializer();
5075 return {NonCLikeKind::DefaultMemberInit,
5076 Init ? Init->getSourceRange() : D->getSourceRange()};
5077 }
5078 continue;
5079 }
5080
5081 // FIXME: We don't allow friend declarations. This violates the wording of
5082 // P1766, but not the intent.
5083 if (isa<FriendDecl>(D))
5084 return {NonCLikeKind::Friend, D->getSourceRange()};
5085
5086 // -- declare any members other than non-static data members, member
5087 // enumerations, or member classes,
5089 isa<EnumDecl>(D))
5090 continue;
5091 auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
5092 if (!MemberRD) {
5093 if (D->isImplicit())
5094 continue;
5095 return {NonCLikeKind::OtherMember, D->getSourceRange()};
5096 }
5097
5098 // -- contain a lambda-expression,
5099 if (MemberRD->isLambda())
5100 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
5101
5102 // and all member classes shall also satisfy these requirements
5103 // (recursively).
5104 if (MemberRD->isThisDeclarationADefinition()) {
5105 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
5106 return Kind;
5107 }
5108 }
5109
5110 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
5111}
5112
5114 TypedefNameDecl *NewTD) {
5115 if (TagFromDeclSpec->isInvalidDecl())
5116 return;
5117
5118 // Do nothing if the tag already has a name for linkage purposes.
5119 if (TagFromDeclSpec->hasNameForLinkage())
5120 return;
5121
5122 // A well-formed anonymous tag must always be a TagUseKind::Definition.
5123 assert(TagFromDeclSpec->isThisDeclarationADefinition());
5124
5125 // The type must match the tag exactly; no qualifiers allowed.
5126 if (!Context.hasSameType(NewTD->getUnderlyingType(),
5127 Context.getCanonicalTagType(TagFromDeclSpec))) {
5128 if (getLangOpts().CPlusPlus)
5129 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
5130 return;
5131 }
5132
5133 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
5134 // An unnamed class with a typedef name for linkage purposes shall [be
5135 // C-like].
5136 //
5137 // FIXME: Also diagnose if we've already computed the linkage. That ideally
5138 // shouldn't happen, but there are constructs that the language rule doesn't
5139 // disallow for which we can't reasonably avoid computing linkage early.
5140 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
5141 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
5142 : NonCLikeKind();
5143 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
5144 if (NonCLike || ChangesLinkage) {
5145 if (NonCLike.Kind == NonCLikeKind::Invalid)
5146 return;
5147
5148 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
5149 if (ChangesLinkage) {
5150 // If the linkage changes, we can't accept this as an extension.
5151 if (NonCLike.Kind == NonCLikeKind::None)
5152 DiagID = diag::err_typedef_changes_linkage;
5153 else
5154 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
5155 }
5156
5157 SourceLocation FixitLoc =
5158 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
5159 llvm::SmallString<40> TextToInsert;
5160 TextToInsert += ' ';
5161 TextToInsert += NewTD->getIdentifier()->getName();
5162
5163 Diag(FixitLoc, DiagID)
5164 << isa<TypeAliasDecl>(NewTD)
5165 << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
5166 if (NonCLike.Kind != NonCLikeKind::None) {
5167 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
5168 << NonCLike.Kind - 1 << NonCLike.Range;
5169 }
5170 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
5171 << NewTD << isa<TypeAliasDecl>(NewTD);
5172
5173 if (ChangesLinkage)
5174 return;
5175 }
5176
5177 // Otherwise, set this as the anon-decl typedef for the tag.
5178 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
5179
5180 // Now that we have a name for the tag, process API notes again.
5181 ProcessAPINotes(TagFromDeclSpec);
5182}
5183
5184static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {
5186 switch (T) {
5188 return 0;
5190 return 1;
5192 return 2;
5194 return 3;
5195 case DeclSpec::TST_enum:
5196 if (const auto *ED = dyn_cast<EnumDecl>(DS.getRepAsDecl())) {
5197 if (ED->isScopedUsingClassTag())
5198 return 5;
5199 if (ED->isScoped())
5200 return 6;
5201 }
5202 return 4;
5203 default:
5204 llvm_unreachable("unexpected type specifier");
5205 }
5206}
5207
5209 DeclSpec &DS,
5210 const ParsedAttributesView &DeclAttrs,
5211 MultiTemplateParamsArg TemplateParams,
5212 bool IsExplicitInstantiation,
5213 RecordDecl *&AnonRecord,
5214 SourceLocation EllipsisLoc) {
5215 Decl *TagD = nullptr;
5216 TagDecl *Tag = nullptr;
5222 TagD = DS.getRepAsDecl();
5223
5224 if (!TagD) // We probably had an error
5225 return nullptr;
5226
5227 // Note that the above type specs guarantee that the
5228 // type rep is a Decl, whereas in many of the others
5229 // it's a Type.
5230 if (isa<TagDecl>(TagD))
5231 Tag = cast<TagDecl>(TagD);
5232 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
5233 Tag = CTD->getTemplatedDecl();
5234 }
5235
5236 if (Tag) {
5237 handleTagNumbering(Tag, S);
5238 Tag->setFreeStanding();
5239 if (Tag->isInvalidDecl())
5240 return Tag;
5241 }
5242
5243 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5244 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5245 // or incomplete types shall not be restrict-qualified."
5246 if (TypeQuals & DeclSpec::TQ_restrict)
5248 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5249 << DS.getSourceRange();
5250 }
5251
5252 if (DS.isInlineSpecified())
5253 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
5254 << getLangOpts().CPlusPlus17;
5255
5256 if (DS.hasConstexprSpecifier()) {
5257 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5258 // and definitions of functions and variables.
5259 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5260 // the declaration of a function or function template
5261 if (Tag)
5262 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
5264 << static_cast<int>(DS.getConstexprSpecifier());
5265 else if (getLangOpts().C23)
5266 Diag(DS.getConstexprSpecLoc(), diag::err_c23_constexpr_not_variable);
5267 else
5268 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
5269 << static_cast<int>(DS.getConstexprSpecifier());
5270 // Don't emit warnings after this error.
5271 return TagD;
5272 }
5273
5275
5276 if (DS.isFriendSpecified()) {
5277 // If we're dealing with a decl but not a TagDecl, assume that
5278 // whatever routines created it handled the friendship aspect.
5279 if (TagD && !Tag)
5280 return nullptr;
5281 return ActOnFriendTypeDecl(S, DS, TemplateParams, EllipsisLoc);
5282 }
5283
5284 assert(EllipsisLoc.isInvalid() &&
5285 "Friend ellipsis but not friend-specified?");
5286
5287 // Track whether this decl-specifier declares anything.
5288 bool DeclaresAnything = true;
5289
5290 // Handle anonymous struct definitions.
5291 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
5292 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5294 if (getLangOpts().CPlusPlus ||
5295 Record->getDeclContext()->isRecord()) {
5296 // If CurContext is a DeclContext that can contain statements,
5297 // RecursiveASTVisitor won't visit the decls that
5298 // BuildAnonymousStructOrUnion() will put into CurContext.
5299 // Also store them here so that they can be part of the
5300 // DeclStmt that gets created in this case.
5301 // FIXME: Also return the IndirectFieldDecls created by
5302 // BuildAnonymousStructOr union, for the same reason?
5303 if (CurContext->isFunctionOrMethod())
5304 AnonRecord = Record;
5305 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5306 Context.getPrintingPolicy());
5307 }
5308
5309 DeclaresAnything = false;
5310 }
5311 }
5312
5313 // C11 6.7.2.1p2:
5314 // A struct-declaration that does not declare an anonymous structure or
5315 // anonymous union shall contain a struct-declarator-list.
5316 //
5317 // This rule also existed in C89 and C99; the grammar for struct-declaration
5318 // did not permit a struct-declaration without a struct-declarator-list.
5319 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5321 // Check for Microsoft C extension: anonymous struct/union member.
5322 // Handle 2 kinds of anonymous struct/union:
5323 // struct STRUCT;
5324 // union UNION;
5325 // and
5326 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5327 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5328 if ((Tag && Tag->getDeclName()) ||
5330 RecordDecl *Record = Tag ? dyn_cast<RecordDecl>(Tag)
5331 : DS.getRepAsType().get()->getAsRecordDecl();
5332 if (Record && getLangOpts().MicrosoftExt) {
5333 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5334 << Record->isUnion() << DS.getSourceRange();
5336 }
5337
5338 DeclaresAnything = false;
5339 }
5340 }
5341
5342 // Skip all the checks below if we have a type error.
5344 (TagD && TagD->isInvalidDecl()))
5345 return TagD;
5346
5347 if (getLangOpts().CPlusPlus &&
5349 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5350 if (Enum->enumerators().empty() && !Enum->getIdentifier() &&
5351 !Enum->isInvalidDecl())
5352 DeclaresAnything = false;
5353
5354 if (!DS.isMissingDeclaratorOk()) {
5355 // Customize diagnostic for a typedef missing a name.
5357 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5358 << DS.getSourceRange();
5359 else
5360 DeclaresAnything = false;
5361 }
5362
5363 if (DS.isModulePrivateSpecified() &&
5364 Tag && Tag->getDeclContext()->isFunctionOrMethod())
5365 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5366 << Tag->getTagKind()
5368
5370
5371 // C 6.7/2:
5372 // A declaration [...] shall declare at least a declarator [...], a tag,
5373 // or the members of an enumeration.
5374 // C++ [dcl.dcl]p3:
5375 // [If there are no declarators], and except for the declaration of an
5376 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5377 // names into the program, or shall redeclare a name introduced by a
5378 // previous declaration.
5379 if (!DeclaresAnything) {
5380 // In C, we allow this as a (popular) extension / bug. Don't bother
5381 // producing further diagnostics for redundant qualifiers after this.
5382 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5383 ? diag::err_no_declarators
5384 : diag::ext_no_declarators)
5385 << DS.getSourceRange();
5386 return TagD;
5387 }
5388
5389 // C++ [dcl.stc]p1:
5390 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5391 // init-declarator-list of the declaration shall not be empty.
5392 // C++ [dcl.fct.spec]p1:
5393 // If a cv-qualifier appears in a decl-specifier-seq, the
5394 // init-declarator-list of the declaration shall not be empty.
5395 //
5396 // Spurious qualifiers here appear to be valid in C.
5397 unsigned DiagID = diag::warn_standalone_specifier;
5398 if (getLangOpts().CPlusPlus)
5399 DiagID = diag::ext_standalone_specifier;
5400
5401 // Note that a linkage-specification sets a storage class, but
5402 // 'extern "C" struct foo;' is actually valid and not theoretically
5403 // useless.
5404 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5405 if (SCS == DeclSpec::SCS_mutable)
5406 // Since mutable is not a viable storage class specifier in C, there is
5407 // no reason to treat it as an extension. Instead, diagnose as an error.
5408 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5409 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5410 Diag(DS.getStorageClassSpecLoc(), DiagID)
5412 }
5413
5417 if (DS.getTypeQualifiers()) {
5419 Diag(DS.getConstSpecLoc(), DiagID) << "const";
5421 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5422 // Restrict is covered above.
5424 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5426 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5427 }
5428
5429 // Warn about ignored type attributes, for example:
5430 // __attribute__((aligned)) struct A;
5431 // Attributes should be placed after tag to apply to type declaration.
5432 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5433 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5434 if (TypeSpecType == DeclSpec::TST_class ||
5435 TypeSpecType == DeclSpec::TST_struct ||
5436 TypeSpecType == DeclSpec::TST_interface ||
5437 TypeSpecType == DeclSpec::TST_union ||
5438 TypeSpecType == DeclSpec::TST_enum) {
5439
5440 auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) {
5441 unsigned DiagnosticId = diag::warn_declspec_attribute_ignored;
5442 if (AL.isAlignas() && !getLangOpts().CPlusPlus)
5443 DiagnosticId = diag::warn_attribute_ignored;
5444 else if (AL.isRegularKeywordAttribute())
5445 DiagnosticId = diag::err_declspec_keyword_has_no_effect;
5446 else
5447 DiagnosticId = diag::warn_declspec_attribute_ignored;
5448 Diag(AL.getLoc(), DiagnosticId)
5449 << AL << GetDiagnosticTypeSpecifierID(DS);
5450 };
5451
5452 llvm::for_each(DS.getAttributes(), EmitAttributeDiagnostic);
5453 llvm::for_each(DeclAttrs, EmitAttributeDiagnostic);
5454 }
5455 }
5456
5457 return TagD;
5458}
5459
5460/// We are trying to inject an anonymous member into the given scope;
5461/// check if there's an existing declaration that can't be overloaded.
5462///
5463/// \return true if this is a forbidden redeclaration
5464static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S,
5465 DeclContext *Owner,
5466 DeclarationName Name,
5467 SourceLocation NameLoc, bool IsUnion,
5468 StorageClass SC) {
5469 LookupResult R(SemaRef, Name, NameLoc,
5473 if (!SemaRef.LookupName(R, S)) return false;
5474
5475 // Pick a representative declaration.
5477 assert(PrevDecl && "Expected a non-null Decl");
5478
5479 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5480 return false;
5481
5482 if (SC == StorageClass::SC_None &&
5483 PrevDecl->isPlaceholderVar(SemaRef.getLangOpts()) &&
5484 (Owner->isFunctionOrMethod() || Owner->isRecord())) {
5485 if (!Owner->isRecord())
5486 SemaRef.DiagPlaceholderVariableDefinition(NameLoc);
5487 return false;
5488 }
5489
5490 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5491 << IsUnion << Name;
5492 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5493
5494 return true;
5495}
5496
5498 if (auto *RD = dyn_cast_if_present<RecordDecl>(D))
5500}
5501
5503 if (!getLangOpts().CPlusPlus)
5504 return;
5505
5506 // This function can be parsed before we have validated the
5507 // structure as an anonymous struct
5508 if (Record->isAnonymousStructOrUnion())
5509 return;
5510
5511 const NamedDecl *First = 0;
5512 for (const Decl *D : Record->decls()) {
5513 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
5514 if (!ND || !ND->isPlaceholderVar(getLangOpts()))
5515 continue;
5516 if (!First)
5517 First = ND;
5518 else
5520 }
5521}
5522
5523/// InjectAnonymousStructOrUnionMembers - Inject the members of the
5524/// anonymous struct or union AnonRecord into the owning context Owner
5525/// and scope S. This routine will be invoked just after we realize
5526/// that an unnamed union or struct is actually an anonymous union or
5527/// struct, e.g.,
5528///
5529/// @code
5530/// union {
5531/// int i;
5532/// float f;
5533/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5534/// // f into the surrounding scope.x
5535/// @endcode
5536///
5537/// This routine is recursive, injecting the names of nested anonymous
5538/// structs/unions into the owning context and scope as well.
5539static bool
5541 RecordDecl *AnonRecord, AccessSpecifier AS,
5542 StorageClass SC,
5543 SmallVectorImpl<NamedDecl *> &Chaining) {
5544 bool Invalid = false;
5545
5546 // Look every FieldDecl and IndirectFieldDecl with a name.
5547 for (auto *D : AnonRecord->decls()) {
5548 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5549 cast<NamedDecl>(D)->getDeclName()) {
5550 ValueDecl *VD = cast<ValueDecl>(D);
5551 // C++ [class.union]p2:
5552 // The names of the members of an anonymous union shall be
5553 // distinct from the names of any other entity in the
5554 // scope in which the anonymous union is declared.
5555
5556 bool FieldInvalid = CheckAnonMemberRedeclaration(
5557 SemaRef, S, Owner, VD->getDeclName(), VD->getLocation(),
5558 AnonRecord->isUnion(), SC);
5559 if (FieldInvalid)
5560 Invalid = true;
5561
5562 // Inject the IndirectFieldDecl even if invalid, because later
5563 // diagnostics may depend on it being present, see findDefaultInitializer.
5564
5565 // C++ [class.union]p2:
5566 // For the purpose of name lookup, after the anonymous union
5567 // definition, the members of the anonymous union are
5568 // considered to have been defined in the scope in which the
5569 // anonymous union is declared.
5570 unsigned OldChainingSize = Chaining.size();
5571 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5572 Chaining.append(IF->chain_begin(), IF->chain_end());
5573 else
5574 Chaining.push_back(VD);
5575
5576 assert(Chaining.size() >= 2);
5577 NamedDecl **NamedChain =
5578 new (SemaRef.Context) NamedDecl *[Chaining.size()];
5579 for (unsigned i = 0; i < Chaining.size(); i++)
5580 NamedChain[i] = Chaining[i];
5581
5583 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5584 VD->getType(), {NamedChain, Chaining.size()});
5585
5586 for (const auto *Attr : VD->attrs())
5587 IndirectField->addAttr(Attr->clone(SemaRef.Context));
5588
5589 IndirectField->setAccess(AS);
5590 IndirectField->setImplicit();
5591 IndirectField->setInvalidDecl(FieldInvalid);
5592 SemaRef.PushOnScopeChains(IndirectField, S);
5593
5594 // That includes picking up the appropriate access specifier.
5595 if (AS != AS_none)
5596 IndirectField->setAccess(AS);
5597
5598 Chaining.resize(OldChainingSize);
5599 }
5600 }
5601
5602 return Invalid;
5603}
5604
5605/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5606/// a VarDecl::StorageClass. Any error reporting is up to the caller:
5607/// illegal input values are mapped to SC_None.
5608static StorageClass
5610 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5611 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5612 "Parser allowed 'typedef' as storage class VarDecl.");
5613 switch (StorageClassSpec) {
5616 if (DS.isExternInLinkageSpec())
5617 return SC_None;
5618 return SC_Extern;
5619 case DeclSpec::SCS_static: return SC_Static;
5620 case DeclSpec::SCS_auto: return SC_Auto;
5623 // Illegal SCSs map to None: error reporting is up to the caller.
5624 case DeclSpec::SCS_mutable: // Fall through.
5625 case DeclSpec::SCS_typedef: return SC_None;
5626 }
5627 llvm_unreachable("unknown storage class specifier");
5628}
5629
5631 assert(Record->hasInClassInitializer());
5632
5633 for (const auto *I : Record->decls()) {
5634 const auto *FD = dyn_cast<FieldDecl>(I);
5635 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5636 FD = IFD->getAnonField();
5637 if (FD && FD->hasInClassInitializer())
5638 return FD->getLocation();
5639 }
5640
5641 llvm_unreachable("couldn't find in-class initializer");
5642}
5643
5645 SourceLocation DefaultInitLoc) {
5646 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5647 return;
5648
5649 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5650 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5651}
5652
5654 CXXRecordDecl *AnonUnion) {
5655 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5656 return;
5657
5659}
5660
5662 AccessSpecifier AS,
5664 const PrintingPolicy &Policy) {
5665 DeclContext *Owner = Record->getDeclContext();
5666
5667 // Diagnose whether this anonymous struct/union is an extension.
5668 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5669 Diag(Record->getLocation(), diag::ext_anonymous_union);
5670 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5671 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5672 else if (!Record->isUnion() && !getLangOpts().C11)
5673 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5674
5675 // C and C++ require different kinds of checks for anonymous
5676 // structs/unions.
5677 bool Invalid = false;
5678 if (getLangOpts().CPlusPlus) {
5679 const char *PrevSpec = nullptr;
5680 if (Record->isUnion()) {
5681 // C++ [class.union]p6:
5682 // C++17 [class.union.anon]p2:
5683 // Anonymous unions declared in a named namespace or in the
5684 // global namespace shall be declared static.
5685 unsigned DiagID;
5686 DeclContext *OwnerScope = Owner->getRedeclContext();
5688 (OwnerScope->isTranslationUnit() ||
5689 (OwnerScope->isNamespace() &&
5690 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5691 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5692 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5693
5694 // Recover by adding 'static'.
5696 PrevSpec, DiagID, Policy);
5697 }
5698 // C++ [class.union]p6:
5699 // A storage class is not allowed in a declaration of an
5700 // anonymous union in a class scope.
5702 isa<RecordDecl>(Owner)) {
5704 diag::err_anonymous_union_with_storage_spec)
5706
5707 // Recover by removing the storage specifier.
5710 PrevSpec, DiagID, Context.getPrintingPolicy());
5711 }
5712 }
5713
5714 // Ignore const/volatile/restrict qualifiers.
5715 if (DS.getTypeQualifiers()) {
5717 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5718 << Record->isUnion() << "const"
5722 diag::ext_anonymous_struct_union_qualified)
5723 << Record->isUnion() << "volatile"
5727 diag::ext_anonymous_struct_union_qualified)
5728 << Record->isUnion() << "restrict"
5732 diag::ext_anonymous_struct_union_qualified)
5733 << Record->isUnion() << "_Atomic"
5737 diag::ext_anonymous_struct_union_qualified)
5738 << Record->isUnion() << "__unaligned"
5740
5742 }
5743
5744 // C++ [class.union]p2:
5745 // The member-specification of an anonymous union shall only
5746 // define non-static data members. [Note: nested types and
5747 // functions cannot be declared within an anonymous union. ]
5748 for (auto *Mem : Record->decls()) {
5749 // Ignore invalid declarations; we already diagnosed them.
5750 if (Mem->isInvalidDecl())
5751 continue;
5752
5753 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5754 // C++ [class.union]p3:
5755 // An anonymous union shall not have private or protected
5756 // members (clause 11).
5757 assert(FD->getAccess() != AS_none);
5758 if (FD->getAccess() != AS_public) {
5759 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5760 << Record->isUnion() << (FD->getAccess() == AS_protected);
5761 Invalid = true;
5762 }
5763
5764 // C++ [class.union]p1
5765 // An object of a class with a non-trivial constructor, a non-trivial
5766 // copy constructor, a non-trivial destructor, or a non-trivial copy
5767 // assignment operator cannot be a member of a union, nor can an
5768 // array of such objects.
5769 if (CheckNontrivialField(FD))
5770 Invalid = true;
5771 } else if (Mem->isImplicit()) {
5772 // Any implicit members are fine.
5773 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5774 // This is a type that showed up in an
5775 // elaborated-type-specifier inside the anonymous struct or
5776 // union, but which actually declares a type outside of the
5777 // anonymous struct or union. It's okay.
5778 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5779 if (!MemRecord->isAnonymousStructOrUnion() &&
5780 MemRecord->getDeclName()) {
5781 // Visual C++ allows type definition in anonymous struct or union.
5782 if (getLangOpts().MicrosoftExt)
5783 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5784 << Record->isUnion();
5785 else {
5786 // This is a nested type declaration.
5787 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5788 << Record->isUnion();
5789 Invalid = true;
5790 }
5791 } else {
5792 // This is an anonymous type definition within another anonymous type.
5793 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5794 // not part of standard C++.
5795 Diag(MemRecord->getLocation(),
5796 diag::ext_anonymous_record_with_anonymous_type)
5797 << Record->isUnion();
5798 }
5799 } else if (isa<AccessSpecDecl>(Mem)) {
5800 // Any access specifier is fine.
5801 } else if (isa<StaticAssertDecl>(Mem)) {
5802 // In C++1z, static_assert declarations are also fine.
5803 } else {
5804 // We have something that isn't a non-static data
5805 // member. Complain about it.
5806 unsigned DK = diag::err_anonymous_record_bad_member;
5807 if (isa<TypeDecl>(Mem))
5808 DK = diag::err_anonymous_record_with_type;
5809 else if (isa<FunctionDecl>(Mem))
5810 DK = diag::err_anonymous_record_with_function;
5811 else if (isa<VarDecl>(Mem))
5812 DK = diag::err_anonymous_record_with_static;
5813
5814 // Visual C++ allows type definition in anonymous struct or union.
5815 if (getLangOpts().MicrosoftExt &&
5816 DK == diag::err_anonymous_record_with_type)
5817 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5818 << Record->isUnion();
5819 else {
5820 Diag(Mem->getLocation(), DK) << Record->isUnion();
5821 Invalid = true;
5822 }
5823 }
5824 }
5825
5826 // C++11 [class.union]p8 (DR1460):
5827 // At most one variant member of a union may have a
5828 // brace-or-equal-initializer.
5829 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5830 Owner->isRecord())
5833 }
5834
5835 if (!Record->isUnion() && !Owner->isRecord()) {
5836 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5837 << getLangOpts().CPlusPlus;
5838 Invalid = true;
5839 }
5840
5841 // C++ [dcl.dcl]p3:
5842 // [If there are no declarators], and except for the declaration of an
5843 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5844 // names into the program
5845 // C++ [class.mem]p2:
5846 // each such member-declaration shall either declare at least one member
5847 // name of the class or declare at least one unnamed bit-field
5848 //
5849 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5850 if (getLangOpts().CPlusPlus && Record->field_empty())
5851 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5852
5853 // Mock up a declarator.
5857 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5858
5859 // Create a declaration for this anonymous struct/union.
5860 NamedDecl *Anon = nullptr;
5861 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5862 Anon = FieldDecl::Create(
5863 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5864 /*IdentifierInfo=*/nullptr, Context.getCanonicalTagType(Record), TInfo,
5865 /*BitWidth=*/nullptr, /*Mutable=*/false,
5866 /*InitStyle=*/ICIS_NoInit);
5867 Anon->setAccess(AS);
5868 ProcessDeclAttributes(S, Anon, Dc);
5869
5870 if (getLangOpts().CPlusPlus)
5871 FieldCollector->Add(cast<FieldDecl>(Anon));
5872 } else {
5873 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5874 if (SCSpec == DeclSpec::SCS_mutable) {
5875 // mutable can only appear on non-static class members, so it's always
5876 // an error here
5877 Diag(Record->getLocation(), diag::err_mutable_nonmember);
5878 Invalid = true;
5879 SC = SC_None;
5880 }
5881
5882 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5883 Record->getLocation(), /*IdentifierInfo=*/nullptr,
5884 Context.getCanonicalTagType(Record), TInfo, SC);
5885 if (Invalid)
5886 Anon->setInvalidDecl();
5887
5888 ProcessDeclAttributes(S, Anon, Dc);
5889
5890 // Default-initialize the implicit variable. This initialization will be
5891 // trivial in almost all cases, except if a union member has an in-class
5892 // initializer:
5893 // union { int n = 0; };
5895 }
5896 Anon->setImplicit();
5897
5898 // Mark this as an anonymous struct/union type.
5899 Record->setAnonymousStructOrUnion(true);
5900
5901 // Add the anonymous struct/union object to the current
5902 // context. We'll be referencing this object when we refer to one of
5903 // its members.
5904 Owner->addDecl(Anon);
5905
5906 // Inject the members of the anonymous struct/union into the owning
5907 // context and into the identifier resolver chain for name lookup
5908 // purposes.
5910 Chain.push_back(Anon);
5911
5912 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, SC,
5913 Chain))
5914 Invalid = true;
5915
5916 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5917 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5919 Decl *ManglingContextDecl;
5920 std::tie(MCtx, ManglingContextDecl) =
5921 getCurrentMangleNumberContext(NewVD->getDeclContext());
5922 if (MCtx) {
5923 Context.setManglingNumber(
5924 NewVD, MCtx->getManglingNumber(
5925 NewVD, getMSManglingNumber(getLangOpts(), S)));
5926 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5927 }
5928 }
5929 }
5930
5931 if (Invalid)
5932 Anon->setInvalidDecl();
5933
5934 return Anon;
5935}
5936
5938 RecordDecl *Record) {
5939 assert(Record && "expected a record!");
5940
5941 // Mock up a declarator.
5944 assert(TInfo && "couldn't build declarator info for anonymous struct");
5945
5946 auto *ParentDecl = cast<RecordDecl>(CurContext);
5947 CanQualType RecTy = Context.getCanonicalTagType(Record);
5948
5949 // Create a declaration for this anonymous struct.
5950 NamedDecl *Anon =
5951 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5952 /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5953 /*BitWidth=*/nullptr, /*Mutable=*/false,
5954 /*InitStyle=*/ICIS_NoInit);
5955 Anon->setImplicit();
5956
5957 // Add the anonymous struct object to the current context.
5958 CurContext->addDecl(Anon);
5959
5960 // Inject the members of the anonymous struct into the current
5961 // context and into the identifier resolver chain for name lookup
5962 // purposes.
5964 Chain.push_back(Anon);
5965
5966 RecordDecl *RecordDef = Record->getDefinition();
5967 if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5968 diag::err_field_incomplete_or_sizeless) ||
5970 *this, S, CurContext, RecordDef, AS_none,
5972 Anon->setInvalidDecl();
5973 ParentDecl->setInvalidDecl();
5974 }
5975
5976 return Anon;
5977}
5978
5982
5985 DeclarationNameInfo NameInfo;
5986 NameInfo.setLoc(Name.StartLocation);
5987
5988 switch (Name.getKind()) {
5989
5992 NameInfo.setName(Name.Identifier);
5993 return NameInfo;
5994
5996 // C++ [temp.deduct.guide]p3:
5997 // The simple-template-id shall name a class template specialization.
5998 // The template-name shall be the same identifier as the template-name
5999 // of the simple-template-id.
6000 // These together intend to imply that the template-name shall name a
6001 // class template.
6002 // FIXME: template<typename T> struct X {};
6003 // template<typename T> using Y = X<T>;
6004 // Y(int) -> Y<int>;
6005 // satisfies these rules but does not name a class template.
6006 TemplateName TN = Name.TemplateName.get().get();
6007 auto *Template = TN.getAsTemplateDecl();
6009 Diag(Name.StartLocation,
6010 diag::err_deduction_guide_name_not_class_template)
6011 << (int)getTemplateNameKindForDiagnostics(TN) << TN;
6012 if (Template)
6014 return DeclarationNameInfo();
6015 }
6016
6017 NameInfo.setName(
6018 Context.DeclarationNames.getCXXDeductionGuideName(Template));
6019 return NameInfo;
6020 }
6021
6023 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
6027 return NameInfo;
6028
6030 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
6031 Name.Identifier));
6033 return NameInfo;
6034
6036 TypeSourceInfo *TInfo;
6038 if (Ty.isNull())
6039 return DeclarationNameInfo();
6040 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
6041 Context.getCanonicalType(Ty)));
6042 NameInfo.setNamedTypeInfo(TInfo);
6043 return NameInfo;
6044 }
6045
6047 TypeSourceInfo *TInfo;
6048 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
6049 if (Ty.isNull())
6050 return DeclarationNameInfo();
6051 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
6052 Context.getCanonicalType(Ty)));
6053 NameInfo.setNamedTypeInfo(TInfo);
6054 return NameInfo;
6055 }
6056
6058 // In well-formed code, we can only have a constructor
6059 // template-id that refers to the current context, so go there
6060 // to find the actual type being constructed.
6061 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
6062 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
6063 return DeclarationNameInfo();
6064
6065 // Determine the type of the class being constructed.
6066 CanQualType CurClassType = Context.getCanonicalTagType(CurClass);
6067
6068 // FIXME: Check two things: that the template-id names the same type as
6069 // CurClassType, and that the template-id does not occur when the name
6070 // was qualified.
6071
6072 NameInfo.setName(
6073 Context.DeclarationNames.getCXXConstructorName(CurClassType));
6074 // FIXME: should we retrieve TypeSourceInfo?
6075 NameInfo.setNamedTypeInfo(nullptr);
6076 return NameInfo;
6077 }
6078
6080 TypeSourceInfo *TInfo;
6081 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
6082 if (Ty.isNull())
6083 return DeclarationNameInfo();
6084 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
6085 Context.getCanonicalType(Ty)));
6086 NameInfo.setNamedTypeInfo(TInfo);
6087 return NameInfo;
6088 }
6089
6091 TemplateName TName = Name.TemplateId->Template.get();
6092 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
6093 return Context.getNameForTemplate(TName, TNameLoc);
6094 }
6095
6096 } // switch (Name.getKind())
6097
6098 llvm_unreachable("Unknown name kind");
6099}
6100
6102 do {
6103 if (Ty->isPointerOrReferenceType())
6104 Ty = Ty->getPointeeType();
6105 else if (Ty->isArrayType())
6107 else
6108 return Ty.withoutLocalFastQualifiers();
6109 } while (true);
6110}
6111
6112/// hasSimilarParameters - Determine whether the C++ functions Declaration
6113/// and Definition have "nearly" matching parameters. This heuristic is
6114/// used to improve diagnostics in the case where an out-of-line function
6115/// definition doesn't match any declaration within the class or namespace.
6116/// Also sets Params to the list of indices to the parameters that differ
6117/// between the declaration and the definition. If hasSimilarParameters
6118/// returns true and Params is empty, then all of the parameters match.
6122 SmallVectorImpl<unsigned> &Params) {
6123 Params.clear();
6124 if (Declaration->param_size() != Definition->param_size())
6125 return false;
6126 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
6127 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
6128 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
6129
6130 // The parameter types are identical
6131 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
6132 continue;
6133
6134 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
6135 QualType DefParamBaseTy = getCoreType(DefParamTy);
6136 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
6137 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
6138
6139 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
6140 (DeclTyName && DeclTyName == DefTyName))
6141 Params.push_back(Idx);
6142 else // The two parameters aren't even close
6143 return false;
6144 }
6145
6146 return true;
6147}
6148
6149/// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
6150/// declarator needs to be rebuilt in the current instantiation.
6151/// Any bits of declarator which appear before the name are valid for
6152/// consideration here. That's specifically the type in the decl spec
6153/// and the base type in any member-pointer chunks.
6155 DeclarationName Name) {
6156 // The types we specifically need to rebuild are:
6157 // - typenames, typeofs, and decltypes
6158 // - types which will become injected class names
6159 // Of course, we also need to rebuild any type referencing such a
6160 // type. It's safest to just say "dependent", but we call out a
6161 // few cases here.
6162
6163 DeclSpec &DS = D.getMutableDeclSpec();
6164 switch (DS.getTypeSpecType()) {
6168#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
6169#include "clang/Basic/TransformTypeTraits.def"
6170 case DeclSpec::TST_atomic: {
6171 // Grab the type from the parser.
6172 TypeSourceInfo *TSI = nullptr;
6173 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
6174 if (T.isNull() || !T->isInstantiationDependentType()) break;
6175
6176 // Make sure there's a type source info. This isn't really much
6177 // of a waste; most dependent types should have type source info
6178 // attached already.
6179 if (!TSI)
6181
6182 // Rebuild the type in the current instantiation.
6184 if (!TSI) return true;
6185
6186 // Store the new type back in the decl spec.
6187 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
6188 DS.UpdateTypeRep(LocType);
6189 break;
6190 }
6191
6195 Expr *E = DS.getRepAsExpr();
6197 if (Result.isInvalid()) return true;
6198 DS.UpdateExprRep(Result.get());
6199 break;
6200 }
6201
6202 default:
6203 // Nothing to do for these decl specs.
6204 break;
6205 }
6206
6207 // It doesn't matter what order we do this in.
6208 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
6209 DeclaratorChunk &Chunk = D.getTypeObject(I);
6210
6211 // The only type information in the declarator which can come
6212 // before the declaration name is the base type of a member
6213 // pointer.
6215 continue;
6216
6217 // Rebuild the scope specifier in-place.
6218 CXXScopeSpec &SS = Chunk.Mem.Scope();
6220 return true;
6221 }
6222
6223 return false;
6224}
6225
6226/// Returns true if the declaration is declared in a system header or from a
6227/// system macro.
6228static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
6229 return SM.isInSystemHeader(D->getLocation()) ||
6230 SM.isInSystemMacro(D->getLocation());
6231}
6232
6234 // Avoid warning twice on the same identifier, and don't warn on redeclaration
6235 // of system decl.
6236 if (D->getPreviousDecl() || D->isImplicit())
6237 return;
6240 !isFromSystemHeader(Context.getSourceManager(), D)) {
6241 Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
6242 << D << static_cast<int>(Status);
6243 }
6244}
6245
6248
6249 // Check if we are in an `omp begin/end declare variant` scope. Handle this
6250 // declaration only if the `bind_to_declaration` extension is set.
6252 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
6253 if (OpenMP().getOMPTraitInfoForSurroundingScope()->isExtensionActive(
6254 llvm::omp::TraitProperty::
6255 implementation_extension_bind_to_declaration))
6257 S, D, MultiTemplateParamsArg(), Bases);
6258
6260
6261 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
6262 Dcl && Dcl->getDeclContext()->isFileContext())
6264
6265 if (!Bases.empty())
6267 Bases);
6268
6269 return Dcl;
6270}
6271
6273 DeclarationNameInfo NameInfo) {
6274 DeclarationName Name = NameInfo.getName();
6275
6276 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
6277 while (Record && Record->isAnonymousStructOrUnion())
6278 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
6279 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6280 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
6281 return true;
6282 }
6283
6284 return false;
6285}
6286
6288 DeclarationName Name,
6289 SourceLocation Loc,
6290 TemplateIdAnnotation *TemplateId,
6291 bool IsMemberSpecialization) {
6292 assert(SS.isValid() && "diagnoseQualifiedDeclaration called for declaration "
6293 "without nested-name-specifier");
6294 DeclContext *Cur = CurContext;
6295 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
6296 Cur = Cur->getParent();
6297
6298 // If the user provided a superfluous scope specifier that refers back to the
6299 // class in which the entity is already declared, diagnose and ignore it.
6300 //
6301 // class X {
6302 // void X::f();
6303 // };
6304 //
6305 // Note, it was once ill-formed to give redundant qualification in all
6306 // contexts, but that rule was removed by DR482.
6307 if (Cur->Equals(DC)) {
6308 if (Cur->isRecord()) {
6309 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6310 : diag::err_member_extra_qualification)
6311 << Name << FixItHint::CreateRemoval(SS.getRange());
6312 SS.clear();
6313 } else {
6314 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
6315 }
6316 return false;
6317 }
6318
6319 // Check whether the qualifying scope encloses the scope of the original
6320 // declaration. For a template-id, we perform the checks in
6321 // CheckTemplateSpecializationScope.
6322 if (!Cur->Encloses(DC) && !(TemplateId || IsMemberSpecialization)) {
6323 if (Cur->isRecord())
6324 Diag(Loc, diag::err_member_qualification)
6325 << Name << SS.getRange();
6326 else if (isa<TranslationUnitDecl>(DC))
6327 Diag(Loc, diag::err_invalid_declarator_global_scope)
6328 << Name << SS.getRange();
6329 else if (isa<FunctionDecl>(Cur))
6330 Diag(Loc, diag::err_invalid_declarator_in_function)
6331 << Name << SS.getRange();
6332 else if (isa<BlockDecl>(Cur))
6333 Diag(Loc, diag::err_invalid_declarator_in_block)
6334 << Name << SS.getRange();
6335 else if (isa<ExportDecl>(Cur)) {
6336 if (!isa<NamespaceDecl>(DC))
6337 Diag(Loc, diag::err_export_non_namespace_scope_name)
6338 << Name << SS.getRange();
6339 else
6340 // The cases that DC is not NamespaceDecl should be handled in
6341 // CheckRedeclarationExported.
6342 return false;
6343 } else
6344 Diag(Loc, diag::err_invalid_declarator_scope)
6345 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
6346
6347 return true;
6348 }
6349
6350 if (Cur->isRecord()) {
6351 // Cannot qualify members within a class.
6352 Diag(Loc, diag::err_member_qualification)
6353 << Name << SS.getRange();
6354 SS.clear();
6355
6356 // C++ constructors and destructors with incorrect scopes can break
6357 // our AST invariants by having the wrong underlying types. If
6358 // that's the case, then drop this declaration entirely.
6361 !Context.hasSameType(
6362 Name.getCXXNameType(),
6363 Context.getCanonicalTagType(cast<CXXRecordDecl>(Cur))))
6364 return true;
6365
6366 return false;
6367 }
6368
6369 // C++23 [temp.names]p5:
6370 // The keyword template shall not appear immediately after a declarative
6371 // nested-name-specifier.
6372 //
6373 // First check the template-id (if any), and then check each component of the
6374 // nested-name-specifier in reverse order.
6375 //
6376 // FIXME: nested-name-specifiers in friend declarations are declarative,
6377 // but we don't call diagnoseQualifiedDeclaration for them. We should.
6378 if (TemplateId && TemplateId->TemplateKWLoc.isValid())
6379 Diag(Loc, diag::ext_template_after_declarative_nns)
6381
6383 for (TypeLoc TL = SpecLoc.getAsTypeLoc(), NextTL; TL;
6384 TL = std::exchange(NextTL, TypeLoc())) {
6385 SourceLocation TemplateKeywordLoc;
6386 switch (TL.getTypeLocClass()) {
6387 case TypeLoc::TemplateSpecialization: {
6388 auto TST = TL.castAs<TemplateSpecializationTypeLoc>();
6389 TemplateKeywordLoc = TST.getTemplateKeywordLoc();
6390 if (auto *T = TST.getTypePtr(); T->isDependentType() && T->isTypeAlias())
6391 Diag(Loc, diag::ext_alias_template_in_declarative_nns)
6392 << TST.getLocalSourceRange();
6393 break;
6394 }
6395 case TypeLoc::Decltype:
6396 case TypeLoc::PackIndexing: {
6397 const Type *T = TL.getTypePtr();
6398 // C++23 [expr.prim.id.qual]p2:
6399 // [...] A declarative nested-name-specifier shall not have a
6400 // computed-type-specifier.
6401 //
6402 // CWG2858 changed this from 'decltype-specifier' to
6403 // 'computed-type-specifier'.
6404 Diag(Loc, diag::err_computed_type_in_declarative_nns)
6405 << T->isDecltypeType() << TL.getSourceRange();
6406 break;
6407 }
6408 case TypeLoc::DependentName:
6409 NextTL =
6410 TL.castAs<DependentNameTypeLoc>().getQualifierLoc().getAsTypeLoc();
6411 break;
6412 default:
6413 break;
6414 }
6415 if (TemplateKeywordLoc.isValid())
6416 Diag(Loc, diag::ext_template_after_declarative_nns)
6417 << FixItHint::CreateRemoval(TemplateKeywordLoc);
6418 }
6419
6420 return false;
6421}
6422
6424 MultiTemplateParamsArg TemplateParamLists) {
6425 // TODO: consider using NameInfo for diagnostic.
6427 DeclarationName Name = NameInfo.getName();
6428
6429 // All of these full declarators require an identifier. If it doesn't have
6430 // one, the ParsedFreeStandingDeclSpec action should be used.
6431 if (D.isDecompositionDeclarator()) {
6432 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6433 } else if (!Name) {
6434 if (!D.isInvalidType()) // Reject this if we think it is valid.
6435 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6437 return nullptr;
6439 return nullptr;
6440
6441 DeclContext *DC = CurContext;
6442 if (D.getCXXScopeSpec().isInvalid())
6443 D.setInvalidType();
6444 else if (D.getCXXScopeSpec().isSet()) {
6447 return nullptr;
6448
6449 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6450 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
6451 if (!DC || isa<EnumDecl>(DC)) {
6452 // If we could not compute the declaration context, it's because the
6453 // declaration context is dependent but does not refer to a class,
6454 // class template, or class template partial specialization. Complain
6455 // and return early, to avoid the coming semantic disaster.
6457 diag::err_template_qualified_declarator_no_match)
6459 << D.getCXXScopeSpec().getRange();
6460 return nullptr;
6461 }
6462 bool IsDependentContext = DC->isDependentContext();
6463
6464 if (!IsDependentContext &&
6466 return nullptr;
6467
6468 // If a class is incomplete, do not parse entities inside it.
6471 diag::err_member_def_undefined_record)
6472 << Name << DC << D.getCXXScopeSpec().getRange();
6473 return nullptr;
6474 }
6475 if (!D.getDeclSpec().isFriendSpecified()) {
6476 TemplateIdAnnotation *TemplateId =
6478 ? D.getName().TemplateId
6479 : nullptr;
6481 D.getIdentifierLoc(), TemplateId,
6482 /*IsMemberSpecialization=*/false)) {
6483 if (DC->isRecord())
6484 return nullptr;
6485
6486 D.setInvalidType();
6487 }
6488 }
6489
6490 // Check whether we need to rebuild the type of the given
6491 // declaration in the current instantiation.
6492 if (EnteringContext && IsDependentContext &&
6493 TemplateParamLists.size() != 0) {
6494 ContextRAII SavedContext(*this, DC);
6495 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
6496 D.setInvalidType();
6497 }
6498 }
6499
6501 QualType R = TInfo->getType();
6502
6505 D.setInvalidType();
6506
6507 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6509
6510 // See if this is a redefinition of a variable in the same scope.
6511 if (!D.getCXXScopeSpec().isSet()) {
6512 bool IsLinkageLookup = false;
6513 bool CreateBuiltins = false;
6514
6515 // If the declaration we're planning to build will be a function
6516 // or object with linkage, then look for another declaration with
6517 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6518 //
6519 // If the declaration we're planning to build will be declared with
6520 // external linkage in the translation unit, create any builtin with
6521 // the same name.
6523 /* Do nothing*/;
6524 else if (CurContext->isFunctionOrMethod() &&
6526 R->isFunctionType())) {
6527 IsLinkageLookup = true;
6528 CreateBuiltins =
6529 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6530 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6532 CreateBuiltins = true;
6533
6534 if (IsLinkageLookup) {
6536 Previous.setRedeclarationKind(
6538 }
6539
6540 LookupName(Previous, S, CreateBuiltins);
6541 } else { // Something like "int foo::x;"
6543
6544 // C++ [dcl.meaning]p1:
6545 // When the declarator-id is qualified, the declaration shall refer to a
6546 // previously declared member of the class or namespace to which the
6547 // qualifier refers (or, in the case of a namespace, of an element of the
6548 // inline namespace set of that namespace (7.3.1)) or to a specialization
6549 // thereof; [...]
6550 //
6551 // Note that we already checked the context above, and that we do not have
6552 // enough information to make sure that Previous contains the declaration
6553 // we want to match. For example, given:
6554 //
6555 // class X {
6556 // void f();
6557 // void f(float);
6558 // };
6559 //
6560 // void X::f(int) { } // ill-formed
6561 //
6562 // In this case, Previous will point to the overload set
6563 // containing the two f's declared in X, but neither of them
6564 // matches.
6565
6567 }
6568
6569 if (auto *TPD = Previous.getAsSingle<NamedDecl>();
6570 TPD && TPD->isTemplateParameter()) {
6571 // Older versions of clang allowed the names of function/variable templates
6572 // to shadow the names of their template parameters. For the compatibility
6573 // purposes we detect such cases and issue a default-to-error warning that
6574 // can be disabled with -Wno-strict-primary-template-shadow.
6575 if (!D.isInvalidType()) {
6576 bool AllowForCompatibility = false;
6577 if (Scope *DeclParent = S->getDeclParent();
6578 Scope *TemplateParamParent = S->getTemplateParamParent()) {
6579 AllowForCompatibility = DeclParent->Contains(*TemplateParamParent) &&
6580 TemplateParamParent->isDeclScope(TPD);
6581 }
6583 AllowForCompatibility);
6584 }
6585
6586 // Just pretend that we didn't see the previous declaration.
6587 Previous.clear();
6588 }
6589
6590 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6591 // Forget that the previous declaration is the injected-class-name.
6592 Previous.clear();
6593
6594 // In C++, the previous declaration we find might be a tag type
6595 // (class or enum). In this case, the new declaration will hide the
6596 // tag type. Note that this applies to functions, function templates, and
6597 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6598 if (Previous.isSingleTagDecl() &&
6600 (TemplateParamLists.size() == 0 || R->isFunctionType()))
6601 Previous.clear();
6602
6603 // Check that there are no default arguments other than in the parameters
6604 // of a function declaration (C++ only).
6605 if (getLangOpts().CPlusPlus)
6607
6608 /// Get the innermost enclosing declaration scope.
6609 S = S->getDeclParent();
6610
6611 NamedDecl *New;
6612
6613 bool AddToScope = true;
6615 if (TemplateParamLists.size()) {
6616 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6617 return nullptr;
6618 }
6619
6620 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6621 } else if (R->isFunctionType()) {
6622 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6623 TemplateParamLists,
6624 AddToScope);
6625 } else {
6626 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6627 AddToScope);
6628 }
6629
6630 if (!New)
6631 return nullptr;
6632
6634
6635 // If this has an identifier and is not a function template specialization,
6636 // add it to the scope stack.
6637 if (New->getDeclName() && AddToScope)
6639
6640 if (OpenMP().isInOpenMPDeclareTargetContext())
6642
6643 return New;
6644}
6645
6646/// Helper method to turn variable array types into constant array
6647/// types in certain situations which would otherwise be errors (for
6648/// GCC compatibility).
6650 ASTContext &Context,
6651 bool &SizeIsNegative,
6652 llvm::APSInt &Oversized) {
6653 // This method tries to turn a variable array into a constant
6654 // array even when the size isn't an ICE. This is necessary
6655 // for compatibility with code that depends on gcc's buggy
6656 // constant expression folding, like struct {char x[(int)(char*)2];}
6657 SizeIsNegative = false;
6658 Oversized = 0;
6659
6660 if (T->isDependentType())
6661 return QualType();
6662
6664 const Type *Ty = Qs.strip(T);
6665
6666 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6667 QualType Pointee = PTy->getPointeeType();
6668 QualType FixedType =
6669 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6670 Oversized);
6671 if (FixedType.isNull()) return FixedType;
6672 FixedType = Context.getPointerType(FixedType);
6673 return Qs.apply(Context, FixedType);
6674 }
6675 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6676 QualType Inner = PTy->getInnerType();
6677 QualType FixedType =
6678 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6679 Oversized);
6680 if (FixedType.isNull()) return FixedType;
6681 FixedType = Context.getParenType(FixedType);
6682 return Qs.apply(Context, FixedType);
6683 }
6684
6685 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6686 if (!VLATy)
6687 return QualType();
6688
6689 QualType ElemTy = VLATy->getElementType();
6690 if (ElemTy->isVariablyModifiedType()) {
6691 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6692 SizeIsNegative, Oversized);
6693 if (ElemTy.isNull())
6694 return QualType();
6695 }
6696
6697 Expr::EvalResult Result;
6698 if (!VLATy->getSizeExpr() ||
6699 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6700 return QualType();
6701
6702 llvm::APSInt Res = Result.Val.getInt();
6703
6704 // Check whether the array size is negative.
6705 if (Res.isSigned() && Res.isNegative()) {
6706 SizeIsNegative = true;
6707 return QualType();
6708 }
6709
6710 // Check whether the array is too large to be addressed.
6711 unsigned ActiveSizeBits =
6712 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6713 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6714 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6715 : Res.getActiveBits();
6716 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6717 Oversized = Res;
6718 return QualType();
6719 }
6720
6721 QualType FoldedArrayType = Context.getConstantArrayType(
6722 ElemTy, Res, VLATy->getSizeExpr(), ArraySizeModifier::Normal, 0);
6723 return Qs.apply(Context, FoldedArrayType);
6724}
6725
6726static void
6728 SrcTL = SrcTL.getUnqualifiedLoc();
6729 DstTL = DstTL.getUnqualifiedLoc();
6730 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6731 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6732 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6733 DstPTL.getPointeeLoc());
6734 DstPTL.setStarLoc(SrcPTL.getStarLoc());
6735 return;
6736 }
6737 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6738 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6739 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6740 DstPTL.getInnerLoc());
6741 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6742 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6743 return;
6744 }
6745 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6746 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6747 TypeLoc SrcElemTL = SrcATL.getElementLoc();
6748 TypeLoc DstElemTL = DstATL.getElementLoc();
6749 if (VariableArrayTypeLoc SrcElemATL =
6750 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6751 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6752 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6753 } else {
6754 DstElemTL.initializeFullCopy(SrcElemTL);
6755 }
6756 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6757 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6758 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6759}
6760
6761/// Helper method to turn variable array types into constant array
6762/// types in certain situations which would otherwise be errors (for
6763/// GCC compatibility).
6764static TypeSourceInfo*
6766 ASTContext &Context,
6767 bool &SizeIsNegative,
6768 llvm::APSInt &Oversized) {
6769 QualType FixedTy
6770 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6771 SizeIsNegative, Oversized);
6772 if (FixedTy.isNull())
6773 return nullptr;
6774 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6776 FixedTInfo->getTypeLoc());
6777 return FixedTInfo;
6778}
6779
6782 unsigned FailedFoldDiagID) {
6783 bool SizeIsNegative;
6784 llvm::APSInt Oversized;
6786 TInfo, Context, SizeIsNegative, Oversized);
6787 if (FixedTInfo) {
6788 Diag(Loc, diag::ext_vla_folded_to_constant);
6789 TInfo = FixedTInfo;
6790 T = FixedTInfo->getType();
6791 return true;
6792 }
6793
6794 if (SizeIsNegative)
6795 Diag(Loc, diag::err_typecheck_negative_array_size);
6796 else if (Oversized.getBoolValue())
6797 Diag(Loc, diag::err_array_too_large) << toString(
6798 Oversized, 10, Oversized.isSigned(), /*formatAsCLiteral=*/false,
6799 /*UpperCase=*/false, /*InsertSeparators=*/true);
6800 else if (FailedFoldDiagID)
6801 Diag(Loc, FailedFoldDiagID);
6802 return false;
6803}
6804
6805void
6807 if (!getLangOpts().CPlusPlus &&
6809 // Don't need to track declarations in the TU in C.
6810 return;
6811
6812 // Note that we have a locally-scoped external with this name.
6813 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6814}
6815
6817 // FIXME: We can have multiple results via __attribute__((overloadable)).
6818 auto Result = Context.getExternCContextDecl()->lookup(Name);
6819 return Result.empty() ? nullptr : *Result.begin();
6820}
6821
6823 // FIXME: We should probably indicate the identifier in question to avoid
6824 // confusion for constructs like "virtual int a(), b;"
6825 if (DS.isVirtualSpecified())
6827 diag::err_virtual_non_function);
6828
6829 if (DS.hasExplicitSpecifier())
6831 diag::err_explicit_non_function);
6832
6833 if (DS.isNoreturnSpecified())
6835 diag::err_noreturn_non_function);
6836}
6837
6838NamedDecl*
6841 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6842 if (D.getCXXScopeSpec().isSet()) {
6843 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6844 << D.getCXXScopeSpec().getRange();
6845 D.setInvalidType();
6846 // Pretend we didn't see the scope specifier.
6847 DC = CurContext;
6848 Previous.clear();
6849 }
6850
6852
6855 (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus)
6856 ? diag::warn_ms_inline_non_function
6857 : diag::err_inline_non_function)
6858 << getLangOpts().CPlusPlus17;
6860 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6861 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6862
6866 diag::err_deduction_guide_invalid_specifier)
6867 << "typedef";
6868 else
6869 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6870 << D.getName().getSourceRange();
6871 return nullptr;
6872 }
6873
6874 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6875 if (!NewTD) return nullptr;
6876
6877 // Handle attributes prior to checking for duplicates in MergeVarDecl
6878 ProcessDeclAttributes(S, NewTD, D);
6879
6881
6882 bool Redeclaration = D.isRedeclaration();
6885 return ND;
6886}
6887
6888void
6890 // C99 6.7.7p2: If a typedef name specifies a variably modified type
6891 // then it shall have block scope.
6892 // Note that variably modified types must be fixed before merging the decl so
6893 // that redeclarations will match.
6894 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6895 QualType T = TInfo->getType();
6896 if (T->isVariablyModifiedType()) {
6898
6899 if (S->getFnParent() == nullptr) {
6900 bool SizeIsNegative;
6901 llvm::APSInt Oversized;
6902 TypeSourceInfo *FixedTInfo =
6904 SizeIsNegative,
6905 Oversized);
6906 if (FixedTInfo) {
6907 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6908 NewTD->setTypeSourceInfo(FixedTInfo);
6909 } else {
6910 if (SizeIsNegative)
6911 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6912 else if (T->isVariableArrayType())
6913 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6914 else if (Oversized.getBoolValue())
6915 Diag(NewTD->getLocation(), diag::err_array_too_large)
6916 << toString(Oversized, 10);
6917 else
6918 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6919 NewTD->setInvalidDecl();
6920 }
6921 }
6922 }
6923}
6924
6925NamedDecl*
6928
6929 // Find the shadowed declaration before filtering for scope.
6930 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6931
6932 // Merge the decl with the existing one if appropriate. If the decl is
6933 // in an outer scope, it isn't the same thing.
6934 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6935 /*AllowInlineNamespace*/false);
6937 if (!Previous.empty()) {
6938 Redeclaration = true;
6939 MergeTypedefNameDecl(S, NewTD, Previous);
6940 } else {
6942 }
6943
6944 if (ShadowedDecl && !Redeclaration)
6945 CheckShadow(NewTD, ShadowedDecl, Previous);
6946
6947 // If this is the C FILE type, notify the AST context.
6948 if (IdentifierInfo *II = NewTD->getIdentifier())
6949 if (!NewTD->isInvalidDecl() &&
6951 switch (II->getNotableIdentifierID()) {
6952 case tok::NotableIdentifierKind::FILE:
6953 Context.setFILEDecl(NewTD);
6954 break;
6955 case tok::NotableIdentifierKind::jmp_buf:
6956 Context.setjmp_bufDecl(NewTD);
6957 break;
6958 case tok::NotableIdentifierKind::sigjmp_buf:
6959 Context.setsigjmp_bufDecl(NewTD);
6960 break;
6961 case tok::NotableIdentifierKind::ucontext_t:
6962 Context.setucontext_tDecl(NewTD);
6963 break;
6964 case tok::NotableIdentifierKind::float_t:
6965 case tok::NotableIdentifierKind::double_t:
6966 NewTD->addAttr(AvailableOnlyInDefaultEvalMethodAttr::Create(Context));
6967 break;
6968 default:
6969 break;
6970 }
6971 }
6972
6973 return NewTD;
6974}
6975
6976/// Determines whether the given declaration is an out-of-scope
6977/// previous declaration.
6978///
6979/// This routine should be invoked when name lookup has found a
6980/// previous declaration (PrevDecl) that is not in the scope where a
6981/// new declaration by the same name is being introduced. If the new
6982/// declaration occurs in a local scope, previous declarations with
6983/// linkage may still be considered previous declarations (C99
6984/// 6.2.2p4-5, C++ [basic.link]p6).
6985///
6986/// \param PrevDecl the previous declaration found by name
6987/// lookup
6988///
6989/// \param DC the context in which the new declaration is being
6990/// declared.
6991///
6992/// \returns true if PrevDecl is an out-of-scope previous declaration
6993/// for a new delcaration with the same name.
6994static bool
6996 ASTContext &Context) {
6997 if (!PrevDecl)
6998 return false;
6999
7000 if (!PrevDecl->hasLinkage())
7001 return false;
7002
7003 if (Context.getLangOpts().CPlusPlus) {
7004 // C++ [basic.link]p6:
7005 // If there is a visible declaration of an entity with linkage
7006 // having the same name and type, ignoring entities declared
7007 // outside the innermost enclosing namespace scope, the block
7008 // scope declaration declares that same entity and receives the
7009 // linkage of the previous declaration.
7010 DeclContext *OuterContext = DC->getRedeclContext();
7011 if (!OuterContext->isFunctionOrMethod())
7012 // This rule only applies to block-scope declarations.
7013 return false;
7014
7015 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
7016 if (PrevOuterContext->isRecord())
7017 // We found a member function: ignore it.
7018 return false;
7019
7020 // Find the innermost enclosing namespace for the new and
7021 // previous declarations.
7022 OuterContext = OuterContext->getEnclosingNamespaceContext();
7023 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
7024
7025 // The previous declaration is in a different namespace, so it
7026 // isn't the same function.
7027 if (!OuterContext->Equals(PrevOuterContext))
7028 return false;
7029 }
7030
7031 return true;
7032}
7033
7035 CXXScopeSpec &SS = D.getCXXScopeSpec();
7036 if (!SS.isSet()) return;
7038}
7039
7041 if (Decl->getType().hasAddressSpace())
7042 return;
7043 if (Decl->getType()->isDependentType())
7044 return;
7045 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
7046 QualType Type = Var->getType();
7047 if (Type->isSamplerT() || Type->isVoidType())
7048 return;
7050 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
7051 // __opencl_c_program_scope_global_variables feature, the address space
7052 // for a variable at program scope or a static or extern variable inside
7053 // a function are inferred to be __global.
7054 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
7055 Var->hasGlobalStorage())
7056 ImplAS = LangAS::opencl_global;
7057 // If the original type from a decayed type is an array type and that array
7058 // type has no address space yet, deduce it now.
7059 if (auto DT = dyn_cast<DecayedType>(Type)) {
7060 auto OrigTy = DT->getOriginalType();
7061 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
7062 // Add the address space to the original array type and then propagate
7063 // that to the element type through `getAsArrayType`.
7064 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
7065 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
7066 // Re-generate the decayed type.
7067 Type = Context.getDecayedType(OrigTy);
7068 }
7069 }
7070 Type = Context.getAddrSpaceQualType(Type, ImplAS);
7071 // Apply any qualifiers (including address space) from the array type to
7072 // the element type. This implements C99 6.7.3p8: "If the specification of
7073 // an array type includes any type qualifiers, the element type is so
7074 // qualified, not the array type."
7075 if (Type->isArrayType())
7076 Type = QualType(Context.getAsArrayType(Type), 0);
7077 Decl->setType(Type);
7078 }
7079}
7080
7081static void checkWeakAttr(Sema &S, NamedDecl &ND) {
7082 // 'weak' only applies to declarations with external linkage.
7083 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
7084 if (!ND.isExternallyVisible()) {
7085 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
7086 ND.dropAttr<WeakAttr>();
7087 }
7088 }
7089}
7090
7091static void checkWeakRefAttr(Sema &S, NamedDecl &ND) {
7092 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
7093 if (ND.isExternallyVisible()) {
7094 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
7095 ND.dropAttrs<WeakRefAttr, AliasAttr>();
7096 }
7097 }
7098}
7099
7100static void checkAliasAttr(Sema &S, NamedDecl &ND) {
7101 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
7102 if (VD->hasInit()) {
7103 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
7104 assert(VD->isThisDeclarationADefinition() &&
7105 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
7106 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
7107 VD->dropAttr<AliasAttr>();
7108 }
7109 }
7110 }
7111}
7112
7113static void checkSelectAnyAttr(Sema &S, NamedDecl &ND) {
7114 // 'selectany' only applies to externally visible variable declarations.
7115 // It does not apply to functions.
7116 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
7117 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
7118 S.Diag(Attr->getLocation(),
7119 diag::err_attribute_selectany_non_extern_data);
7120 ND.dropAttr<SelectAnyAttr>();
7121 }
7122 }
7123}
7124
7126 if (HybridPatchableAttr *Attr = ND.getAttr<HybridPatchableAttr>()) {
7127 if (!ND.isExternallyVisible())
7128 S.Diag(Attr->getLocation(),
7129 diag::warn_attribute_hybrid_patchable_non_extern);
7130 }
7131}
7132
7134 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
7135 auto *VD = dyn_cast<VarDecl>(&ND);
7136 bool IsAnonymousNS = false;
7137 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
7138 if (VD) {
7139 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
7140 while (NS && !IsAnonymousNS) {
7141 IsAnonymousNS = NS->isAnonymousNamespace();
7142 NS = dyn_cast<NamespaceDecl>(NS->getParent());
7143 }
7144 }
7145 // dll attributes require external linkage. Static locals may have external
7146 // linkage but still cannot be explicitly imported or exported.
7147 // In Microsoft mode, a variable defined in anonymous namespace must have
7148 // external linkage in order to be exported.
7149 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
7150 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
7151 (!AnonNSInMicrosoftMode &&
7152 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
7153 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
7154 << &ND << Attr;
7155 ND.setInvalidDecl();
7156 }
7157 }
7158}
7159
7161 // Check the attributes on the function type and function params, if any.
7162 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
7163 FD = FD->getMostRecentDecl();
7164 // Don't declare this variable in the second operand of the for-statement;
7165 // GCC miscompiles that by ending its lifetime before evaluating the
7166 // third operand. See gcc.gnu.org/PR86769.
7168 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
7169 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7170 TL = ATL.getModifiedLoc()) {
7171 // The [[lifetimebound]] attribute can be applied to the implicit object
7172 // parameter of a non-static member function (other than a ctor or dtor)
7173 // by applying it to the function type.
7174 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
7175 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
7176 int NoImplicitObjectError = -1;
7177 if (!MD)
7178 NoImplicitObjectError = 0;
7179 else if (MD->isStatic())
7180 NoImplicitObjectError = 1;
7181 else if (MD->isExplicitObjectMemberFunction())
7182 NoImplicitObjectError = 2;
7183 if (NoImplicitObjectError != -1) {
7184 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
7185 << NoImplicitObjectError << A->getRange();
7186 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
7187 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
7188 << isa<CXXDestructorDecl>(MD) << A->getRange();
7189 } else if (MD->getReturnType()->isVoidType()) {
7190 S.Diag(
7191 MD->getLocation(),
7192 diag::
7193 err_lifetimebound_implicit_object_parameter_void_return_type);
7194 }
7195 }
7196 }
7197
7198 for (unsigned int I = 0; I < FD->getNumParams(); ++I) {
7199 const ParmVarDecl *P = FD->getParamDecl(I);
7200
7201 // The [[lifetimebound]] attribute can be applied to a function parameter
7202 // only if the function returns a value.
7203 if (auto *A = P->getAttr<LifetimeBoundAttr>()) {
7204 if (!isa<CXXConstructorDecl>(FD) && FD->getReturnType()->isVoidType()) {
7205 S.Diag(A->getLocation(),
7206 diag::err_lifetimebound_parameter_void_return_type);
7207 }
7208 }
7209 }
7210 }
7211}
7212
7214 // Ensure that an auto decl is deduced otherwise the checks below might cache
7215 // the wrong linkage.
7216 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
7217
7218 checkWeakAttr(S, ND);
7219 checkWeakRefAttr(S, ND);
7220 checkAliasAttr(S, ND);
7221 checkSelectAnyAttr(S, ND);
7223 checkInheritableAttr(S, ND);
7225}
7226
7228 NamedDecl *NewDecl,
7229 bool IsSpecialization,
7230 bool IsDefinition) {
7231 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
7232 return;
7233
7234 bool IsTemplate = false;
7235 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
7236 OldDecl = OldTD->getTemplatedDecl();
7237 IsTemplate = true;
7238 if (!IsSpecialization)
7239 IsDefinition = false;
7240 }
7241 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
7242 NewDecl = NewTD->getTemplatedDecl();
7243 IsTemplate = true;
7244 }
7245
7246 if (!OldDecl || !NewDecl)
7247 return;
7248
7249 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
7250 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
7251 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
7252 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
7253
7254 // dllimport and dllexport are inheritable attributes so we have to exclude
7255 // inherited attribute instances.
7256 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
7257 (NewExportAttr && !NewExportAttr->isInherited());
7258
7259 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
7260 // the only exception being explicit specializations.
7261 // Implicitly generated declarations are also excluded for now because there
7262 // is no other way to switch these to use dllimport or dllexport.
7263 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
7264
7265 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
7266 // Allow with a warning for free functions and global variables.
7267 bool JustWarn = false;
7268 if (!OldDecl->isCXXClassMember()) {
7269 auto *VD = dyn_cast<VarDecl>(OldDecl);
7270 if (VD && !VD->getDescribedVarTemplate())
7271 JustWarn = true;
7272 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
7273 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
7274 JustWarn = true;
7275 }
7276
7277 // We cannot change a declaration that's been used because IR has already
7278 // been emitted. Dllimported functions will still work though (modulo
7279 // address equality) as they can use the thunk.
7280 if (OldDecl->isUsed())
7281 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
7282 JustWarn = false;
7283
7284 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7285 : diag::err_attribute_dll_redeclaration;
7286 S.Diag(NewDecl->getLocation(), DiagID)
7287 << NewDecl
7288 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7289 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7290 if (!JustWarn) {
7291 NewDecl->setInvalidDecl();
7292 return;
7293 }
7294 }
7295
7296 // A redeclaration is not allowed to drop a dllimport attribute, the only
7297 // exceptions being inline function definitions (except for function
7298 // templates), local extern declarations, qualified friend declarations or
7299 // special MSVC extension: in the last case, the declaration is treated as if
7300 // it were marked dllexport.
7301 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7302 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7303 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
7304 // Ignore static data because out-of-line definitions are diagnosed
7305 // separately.
7306 IsStaticDataMember = VD->isStaticDataMember();
7307 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7309 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
7310 IsInline = FD->isInlined();
7311 IsQualifiedFriend = FD->getQualifier() &&
7312 FD->getFriendObjectKind() == Decl::FOK_Declared;
7313 }
7314
7315 if (OldImportAttr && !HasNewAttr &&
7316 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7317 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7318 if (IsMicrosoftABI && IsDefinition) {
7319 if (IsSpecialization) {
7320 S.Diag(
7321 NewDecl->getLocation(),
7322 diag::err_attribute_dllimport_function_specialization_definition);
7323 S.Diag(OldImportAttr->getLocation(), diag::note_attribute);
7324 NewDecl->dropAttr<DLLImportAttr>();
7325 } else {
7326 S.Diag(NewDecl->getLocation(),
7327 diag::warn_redeclaration_without_import_attribute)
7328 << NewDecl;
7329 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7330 NewDecl->dropAttr<DLLImportAttr>();
7331 NewDecl->addAttr(DLLExportAttr::CreateImplicit(
7332 S.Context, NewImportAttr->getRange()));
7333 }
7334 } else if (IsMicrosoftABI && IsSpecialization) {
7335 assert(!IsDefinition);
7336 // MSVC allows this. Keep the inherited attribute.
7337 } else {
7338 S.Diag(NewDecl->getLocation(),
7339 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7340 << NewDecl << OldImportAttr;
7341 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7342 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
7343 OldDecl->dropAttr<DLLImportAttr>();
7344 NewDecl->dropAttr<DLLImportAttr>();
7345 }
7346 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7347 // In MinGW, seeing a function declared inline drops the dllimport
7348 // attribute.
7349 OldDecl->dropAttr<DLLImportAttr>();
7350 NewDecl->dropAttr<DLLImportAttr>();
7351 S.Diag(NewDecl->getLocation(),
7352 diag::warn_dllimport_dropped_from_inline_function)
7353 << NewDecl << OldImportAttr;
7354 }
7355
7356 // A specialization of a class template member function is processed here
7357 // since it's a redeclaration. If the parent class is dllexport, the
7358 // specialization inherits that attribute. This doesn't happen automatically
7359 // since the parent class isn't instantiated until later.
7360 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
7361 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7362 !NewImportAttr && !NewExportAttr) {
7363 if (const DLLExportAttr *ParentExportAttr =
7364 MD->getParent()->getAttr<DLLExportAttr>()) {
7365 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
7366 NewAttr->setInherited(true);
7367 NewDecl->addAttr(NewAttr);
7368 }
7369 }
7370 }
7371}
7372
7373/// Given that we are within the definition of the given function,
7374/// will that definition behave like C99's 'inline', where the
7375/// definition is discarded except for optimization purposes?
7377 // Try to avoid calling GetGVALinkageForFunction.
7378
7379 // All cases of this require the 'inline' keyword.
7380 if (!FD->isInlined()) return false;
7381
7382 // This is only possible in C++ with the gnu_inline attribute.
7383 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7384 return false;
7385
7386 // Okay, go ahead and call the relatively-more-expensive function.
7388}
7389
7390/// Determine whether a variable is extern "C" prior to attaching
7391/// an initializer. We can't just call isExternC() here, because that
7392/// will also compute and cache whether the declaration is externally
7393/// visible, which might change when we attach the initializer.
7394///
7395/// This can only be used if the declaration is known to not be a
7396/// redeclaration of an internal linkage declaration.
7397///
7398/// For instance:
7399///
7400/// auto x = []{};
7401///
7402/// Attaching the initializer here makes this declaration not externally
7403/// visible, because its type has internal linkage.
7404///
7405/// FIXME: This is a hack.
7406template<typename T>
7407static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7408 if (S.getLangOpts().CPlusPlus) {
7409 // In C++, the overloadable attribute negates the effects of extern "C".
7410 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7411 return false;
7412
7413 // So do CUDA's host/device attributes.
7414 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7415 D->template hasAttr<CUDAHostAttr>()))
7416 return false;
7417 }
7418 return D->isExternC();
7419}
7420
7421static bool shouldConsiderLinkage(const VarDecl *VD) {
7422 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7425 return VD->hasExternalStorage();
7426 if (DC->isFileContext())
7427 return true;
7428 if (DC->isRecord())
7429 return false;
7430 if (DC->getDeclKind() == Decl::HLSLBuffer)
7431 return false;
7432
7434 return false;
7435 llvm_unreachable("Unexpected context");
7436}
7437
7438static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7439 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7440 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7442 return true;
7443 if (DC->isRecord())
7444 return false;
7445 llvm_unreachable("Unexpected context");
7446}
7447
7448static bool hasParsedAttr(Scope *S, const Declarator &PD,
7449 ParsedAttr::Kind Kind) {
7450 // Check decl attributes on the DeclSpec.
7451 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
7452 return true;
7453
7454 // Walk the declarator structure, checking decl attributes that were in a type
7455 // position to the decl itself.
7456 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7457 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
7458 return true;
7459 }
7460
7461 // Finally, check attributes on the decl itself.
7462 return PD.getAttributes().hasAttribute(Kind) ||
7464}
7465
7467 if (!DC->isFunctionOrMethod())
7468 return false;
7469
7470 // If this is a local extern function or variable declared within a function
7471 // template, don't add it into the enclosing namespace scope until it is
7472 // instantiated; it might have a dependent type right now.
7473 if (DC->isDependentContext())
7474 return true;
7475
7476 // C++11 [basic.link]p7:
7477 // When a block scope declaration of an entity with linkage is not found to
7478 // refer to some other declaration, then that entity is a member of the
7479 // innermost enclosing namespace.
7480 //
7481 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7482 // semantically-enclosing namespace, not a lexically-enclosing one.
7483 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
7484 DC = DC->getParent();
7485 return true;
7486}
7487
7488/// Returns true if given declaration has external C language linkage.
7489static bool isDeclExternC(const Decl *D) {
7490 if (const auto *FD = dyn_cast<FunctionDecl>(D))
7491 return FD->isExternC();
7492 if (const auto *VD = dyn_cast<VarDecl>(D))
7493 return VD->isExternC();
7494
7495 llvm_unreachable("Unknown type of decl!");
7496}
7497
7498/// Returns true if there hasn't been any invalid type diagnosed.
7499static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7500 DeclContext *DC = NewVD->getDeclContext();
7501 QualType R = NewVD->getType();
7502
7503 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7504 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7505 // argument.
7506 if (R->isImageType() || R->isPipeType()) {
7507 Se.Diag(NewVD->getLocation(),
7508 diag::err_opencl_type_can_only_be_used_as_function_parameter)
7509 << R;
7510 NewVD->setInvalidDecl();
7511 return false;
7512 }
7513
7514 // OpenCL v1.2 s6.9.r:
7515 // The event type cannot be used to declare a program scope variable.
7516 // OpenCL v2.0 s6.9.q:
7517 // The clk_event_t and reserve_id_t types cannot be declared in program
7518 // scope.
7519 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7520 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7521 Se.Diag(NewVD->getLocation(),
7522 diag::err_invalid_type_for_program_scope_var)
7523 << R;
7524 NewVD->setInvalidDecl();
7525 return false;
7526 }
7527 }
7528
7529 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7530 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7531 Se.getLangOpts())) {
7532 QualType NR = R.getCanonicalType();
7533 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7534 NR->isReferenceType()) {
7537 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7538 << NR->isReferenceType();
7539 NewVD->setInvalidDecl();
7540 return false;
7541 }
7542 NR = NR->getPointeeType();
7543 }
7544 }
7545
7546 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7547 Se.getLangOpts())) {
7548 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7549 // half array type (unless the cl_khr_fp16 extension is enabled).
7550 if (Se.Context.getBaseElementType(R)->isHalfType()) {
7551 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7552 NewVD->setInvalidDecl();
7553 return false;
7554 }
7555 }
7556
7557 // OpenCL v1.2 s6.9.r:
7558 // The event type cannot be used with the __local, __constant and __global
7559 // address space qualifiers.
7560 if (R->isEventT()) {
7562 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7563 NewVD->setInvalidDecl();
7564 return false;
7565 }
7566 }
7567
7568 if (R->isSamplerT()) {
7569 // OpenCL v1.2 s6.9.b p4:
7570 // The sampler type cannot be used with the __local and __global address
7571 // space qualifiers.
7574 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7575 NewVD->setInvalidDecl();
7576 }
7577
7578 // OpenCL v1.2 s6.12.14.1:
7579 // A global sampler must be declared with either the constant address
7580 // space qualifier or with the const qualifier.
7581 if (DC->isTranslationUnit() &&
7583 R.isConstQualified())) {
7584 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7585 NewVD->setInvalidDecl();
7586 }
7587 if (NewVD->isInvalidDecl())
7588 return false;
7589 }
7590
7591 return true;
7592}
7593
7594template <typename AttrTy>
7595static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7596 const TypedefNameDecl *TND = TT->getDecl();
7597 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7598 AttrTy *Clone = Attribute->clone(S.Context);
7599 Clone->setInherited(true);
7600 D->addAttr(Clone);
7601 }
7602}
7603
7604// This function emits warning and a corresponding note based on the
7605// ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7606// declarations of an annotated type must be const qualified.
7608 QualType VarType = VD->getType().getCanonicalType();
7609
7610 // Ignore local declarations (for now) and those with const qualification.
7611 // TODO: Local variables should not be allowed if their type declaration has
7612 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7613 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7614 return;
7615
7616 if (VarType->isArrayType()) {
7617 // Retrieve element type for array declarations.
7618 VarType = S.getASTContext().getBaseElementType(VarType);
7619 }
7620
7621 const RecordDecl *RD = VarType->getAsRecordDecl();
7622
7623 // Check if the record declaration is present and if it has any attributes.
7624 if (RD == nullptr)
7625 return;
7626
7627 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7628 S.Diag(VD->getLocation(), diag::warn_var_decl_not_read_only) << RD;
7629 S.Diag(ConstDecl->getLocation(), diag::note_enforce_read_only_placement);
7630 return;
7631 }
7632}
7633
7634// Checks if VD is declared at global scope or with C language linkage.
7635static bool isMainVar(DeclarationName Name, VarDecl *VD) {
7636 return Name.getAsIdentifierInfo() &&
7637 Name.getAsIdentifierInfo()->isStr("main") &&
7638 !VD->getDescribedVarTemplate() &&
7639 (VD->getDeclContext()->getRedeclContext()->isTranslationUnit() ||
7640 VD->isExternC());
7641}
7642
7644 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7645 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7646 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7647 QualType R = TInfo->getType();
7649
7651 bool IsPlaceholderVariable = false;
7652
7653 if (D.isDecompositionDeclarator()) {
7654 // Take the name of the first declarator as our name for diagnostic
7655 // purposes.
7656 auto &Decomp = D.getDecompositionDeclarator();
7657 if (!Decomp.bindings().empty()) {
7658 II = Decomp.bindings()[0].Name;
7659 Name = II;
7660 }
7661 } else if (!II) {
7662 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7663 return nullptr;
7664 }
7665
7666
7669 if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) &&
7670 SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) {
7671
7672 IsPlaceholderVariable = true;
7673
7674 if (!Previous.empty()) {
7675 NamedDecl *PrevDecl = *Previous.begin();
7676 bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals(
7677 DC->getRedeclContext());
7678 if (SameDC && isDeclInScope(PrevDecl, CurContext, S, false)) {
7679 IsPlaceholderVariable = !isa<ParmVarDecl>(PrevDecl);
7680 if (IsPlaceholderVariable)
7682 }
7683 }
7684 }
7685
7686 // dllimport globals without explicit storage class are treated as extern. We
7687 // have to change the storage class this early to get the right DeclContext.
7688 if (SC == SC_None && !DC->isRecord() &&
7689 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7690 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7691 SC = SC_Extern;
7692
7693 DeclContext *OriginalDC = DC;
7694 bool IsLocalExternDecl = SC == SC_Extern &&
7696
7697 if (SCSpec == DeclSpec::SCS_mutable) {
7698 // mutable can only appear on non-static class members, so it's always
7699 // an error here
7700 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7701 D.setInvalidType();
7702 SC = SC_None;
7703 }
7704
7705 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7706 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7708 // In C++11, the 'register' storage class specifier is deprecated.
7709 // Suppress the warning in system macros, it's used in macros in some
7710 // popular C system headers, such as in glibc's htonl() macro.
7712 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7713 : diag::warn_deprecated_register)
7715 }
7716
7718
7719 if (!DC->isRecord() && S->getFnParent() == nullptr) {
7720 // C99 6.9p2: The storage-class specifiers auto and register shall not
7721 // appear in the declaration specifiers in an external declaration.
7722 // Global Register+Asm is a GNU extension we support.
7723 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7724 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7725 D.setInvalidType();
7726 }
7727 }
7728
7729 // If this variable has a VLA type and an initializer, try to
7730 // fold to a constant-sized type. This is otherwise invalid.
7731 if (D.hasInitializer() && R->isVariableArrayType())
7733 /*DiagID=*/0);
7734
7735 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) {
7736 const AutoType *AT = TL.getTypePtr();
7737 CheckConstrainedAuto(AT, TL.getConceptNameLoc());
7738 }
7739
7740 bool IsMemberSpecialization = false;
7741 bool IsVariableTemplateSpecialization = false;
7742 bool IsPartialSpecialization = false;
7743 bool IsVariableTemplate = false;
7744 VarDecl *NewVD = nullptr;
7745 VarTemplateDecl *NewTemplate = nullptr;
7746 TemplateParameterList *TemplateParams = nullptr;
7747 if (!getLangOpts().CPlusPlus) {
7749 II, R, TInfo, SC);
7750
7751 if (R->getContainedDeducedType())
7752 ParsingInitForAutoVars.insert(NewVD);
7753
7754 if (D.isInvalidType())
7755 NewVD->setInvalidDecl();
7756
7758 NewVD->hasLocalStorage())
7759 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7761 } else {
7762 bool Invalid = false;
7763 // Match up the template parameter lists with the scope specifier, then
7764 // determine whether we have a template or a template specialization.
7767 D.getCXXScopeSpec(),
7769 ? D.getName().TemplateId
7770 : nullptr,
7771 TemplateParamLists,
7772 /*never a friend*/ false, IsMemberSpecialization, Invalid);
7773
7774 if (TemplateParams) {
7775 if (DC->isDependentContext()) {
7776 ContextRAII SavedContext(*this, DC);
7778 Invalid = true;
7779 }
7780
7781 if (!TemplateParams->size() &&
7783 // There is an extraneous 'template<>' for this variable. Complain
7784 // about it, but allow the declaration of the variable.
7785 Diag(TemplateParams->getTemplateLoc(),
7786 diag::err_template_variable_noparams)
7787 << II
7788 << SourceRange(TemplateParams->getTemplateLoc(),
7789 TemplateParams->getRAngleLoc());
7790 TemplateParams = nullptr;
7791 } else {
7792 // Check that we can declare a template here.
7793 if (CheckTemplateDeclScope(S, TemplateParams))
7794 return nullptr;
7795
7797 // This is an explicit specialization or a partial specialization.
7798 IsVariableTemplateSpecialization = true;
7799 IsPartialSpecialization = TemplateParams->size() > 0;
7800 } else { // if (TemplateParams->size() > 0)
7801 // This is a template declaration.
7802 IsVariableTemplate = true;
7803
7804 // Only C++1y supports variable templates (N3651).
7805 DiagCompat(D.getIdentifierLoc(), diag_compat::variable_template);
7806 }
7807 }
7808 } else {
7809 // Check that we can declare a member specialization here.
7810 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7811 CheckTemplateDeclScope(S, TemplateParamLists.back()))
7812 return nullptr;
7813 assert((Invalid ||
7815 "should have a 'template<>' for this decl");
7816 }
7817
7818 bool IsExplicitSpecialization =
7819 IsVariableTemplateSpecialization && !IsPartialSpecialization;
7820
7821 // C++ [temp.expl.spec]p2:
7822 // The declaration in an explicit-specialization shall not be an
7823 // export-declaration. An explicit specialization shall not use a
7824 // storage-class-specifier other than thread_local.
7825 //
7826 // We use the storage-class-specifier from DeclSpec because we may have
7827 // added implicit 'extern' for declarations with __declspec(dllimport)!
7828 if (SCSpec != DeclSpec::SCS_unspecified &&
7829 (IsExplicitSpecialization || IsMemberSpecialization)) {
7831 diag::ext_explicit_specialization_storage_class)
7833 }
7834
7835 if (CurContext->isRecord()) {
7836 if (SC == SC_Static) {
7837 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7838 // Walk up the enclosing DeclContexts to check for any that are
7839 // incompatible with static data members.
7840 const DeclContext *FunctionOrMethod = nullptr;
7841 const CXXRecordDecl *AnonStruct = nullptr;
7842 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7843 if (Ctxt->isFunctionOrMethod()) {
7844 FunctionOrMethod = Ctxt;
7845 break;
7846 }
7847 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7848 if (ParentDecl && !ParentDecl->getDeclName()) {
7849 AnonStruct = ParentDecl;
7850 break;
7851 }
7852 }
7853 if (FunctionOrMethod) {
7854 // C++ [class.static.data]p5: A local class shall not have static
7855 // data members.
7857 diag::err_static_data_member_not_allowed_in_local_class)
7858 << Name << RD->getDeclName() << RD->getTagKind();
7859 } else if (AnonStruct) {
7860 // C++ [class.static.data]p4: Unnamed classes and classes contained
7861 // directly or indirectly within unnamed classes shall not contain
7862 // static data members.
7864 diag::err_static_data_member_not_allowed_in_anon_struct)
7865 << Name << AnonStruct->getTagKind();
7866 Invalid = true;
7867 } else if (RD->isUnion()) {
7868 // C++98 [class.union]p1: If a union contains a static data member,
7869 // the program is ill-formed. C++11 drops this restriction.
7871 diag_compat::static_data_member_in_union)
7872 << Name;
7873 }
7874 }
7875 } else if (IsVariableTemplate || IsPartialSpecialization) {
7876 // There is no such thing as a member field template.
7877 Diag(D.getIdentifierLoc(), diag::err_template_member)
7878 << II << TemplateParams->getSourceRange();
7879 // Recover by pretending this is a static data member template.
7880 SC = SC_Static;
7881 }
7882 } else if (DC->isRecord()) {
7883 // This is an out-of-line definition of a static data member.
7884 switch (SC) {
7885 case SC_None:
7886 break;
7887 case SC_Static:
7889 diag::err_static_out_of_line)
7892 break;
7893 case SC_Auto:
7894 case SC_Register:
7895 case SC_Extern:
7896 // [dcl.stc] p2: The auto or register specifiers shall be applied only
7897 // to names of variables declared in a block or to function parameters.
7898 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7899 // of class members
7900
7902 diag::err_storage_class_for_static_member)
7905 break;
7906 case SC_PrivateExtern:
7907 llvm_unreachable("C storage class in c++!");
7908 }
7909 }
7910
7911 if (IsVariableTemplateSpecialization) {
7912 SourceLocation TemplateKWLoc =
7913 TemplateParamLists.size() > 0
7914 ? TemplateParamLists[0]->getTemplateLoc()
7915 : SourceLocation();
7917 S, D, TInfo, Previous, TemplateKWLoc, TemplateParams, SC,
7919 if (Res.isInvalid())
7920 return nullptr;
7921 NewVD = cast<VarDecl>(Res.get());
7922 AddToScope = false;
7923 } else if (D.isDecompositionDeclarator()) {
7925 D.getIdentifierLoc(), R, TInfo, SC,
7926 Bindings);
7927 } else
7928 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7929 D.getIdentifierLoc(), II, R, TInfo, SC);
7930
7931 // If this is supposed to be a variable template, create it as such.
7932 if (IsVariableTemplate) {
7933 NewTemplate =
7935 TemplateParams, NewVD);
7936 NewVD->setDescribedVarTemplate(NewTemplate);
7937 }
7938
7939 // If this decl has an auto type in need of deduction, make a note of the
7940 // Decl so we can diagnose uses of it in its own initializer.
7941 if (R->getContainedDeducedType())
7942 ParsingInitForAutoVars.insert(NewVD);
7943
7944 if (D.isInvalidType() || Invalid) {
7945 NewVD->setInvalidDecl();
7946 if (NewTemplate)
7947 NewTemplate->setInvalidDecl();
7948 }
7949
7950 SetNestedNameSpecifier(*this, NewVD, D);
7951
7952 // If we have any template parameter lists that don't directly belong to
7953 // the variable (matching the scope specifier), store them.
7954 // An explicit variable template specialization does not own any template
7955 // parameter lists.
7956 unsigned VDTemplateParamLists =
7957 (TemplateParams && !IsExplicitSpecialization) ? 1 : 0;
7958 if (TemplateParamLists.size() > VDTemplateParamLists)
7960 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7961 }
7962
7963 if (D.getDeclSpec().isInlineSpecified()) {
7964 if (!getLangOpts().CPlusPlus) {
7965 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7966 << 0;
7967 } else if (CurContext->isFunctionOrMethod()) {
7968 // 'inline' is not allowed on block scope variable declaration.
7970 diag::err_inline_declaration_block_scope) << Name
7972 } else {
7974 getLangOpts().CPlusPlus17 ? diag::compat_cxx17_inline_variable
7975 : diag::compat_pre_cxx17_inline_variable);
7976 NewVD->setInlineSpecified();
7977 }
7978 }
7979
7980 // Set the lexical context. If the declarator has a C++ scope specifier, the
7981 // lexical context will be different from the semantic context.
7983 if (NewTemplate)
7984 NewTemplate->setLexicalDeclContext(CurContext);
7985
7986 if (IsLocalExternDecl) {
7988 for (auto *B : Bindings)
7989 B->setLocalExternDecl();
7990 else
7991 NewVD->setLocalExternDecl();
7992 }
7993
7994 bool EmitTLSUnsupportedError = false;
7996 // C++11 [dcl.stc]p4:
7997 // When thread_local is applied to a variable of block scope the
7998 // storage-class-specifier static is implied if it does not appear
7999 // explicitly.
8000 // Core issue: 'static' is not implied if the variable is declared
8001 // 'extern'.
8002 if (NewVD->hasLocalStorage() &&
8003 (SCSpec != DeclSpec::SCS_unspecified ||
8005 !DC->isFunctionOrMethod()))
8007 diag::err_thread_non_global)
8009 else if (!Context.getTargetInfo().isTLSSupported()) {
8010 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8011 // Postpone error emission until we've collected attributes required to
8012 // figure out whether it's a host or device variable and whether the
8013 // error should be ignored.
8014 EmitTLSUnsupportedError = true;
8015 // We still need to mark the variable as TLS so it shows up in AST with
8016 // proper storage class for other tools to use even if we're not going
8017 // to emit any code for it.
8018 NewVD->setTSCSpec(TSCS);
8019 } else
8021 diag::err_thread_unsupported);
8022 } else
8023 NewVD->setTSCSpec(TSCS);
8024 }
8025
8026 switch (D.getDeclSpec().getConstexprSpecifier()) {
8028 break;
8029
8032 diag::err_constexpr_wrong_decl_kind)
8033 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
8034 [[fallthrough]];
8035
8037 NewVD->setConstexpr(true);
8038 // C++1z [dcl.spec.constexpr]p1:
8039 // A static data member declared with the constexpr specifier is
8040 // implicitly an inline variable.
8041 if (NewVD->isStaticDataMember() &&
8043 Context.getTargetInfo().getCXXABI().isMicrosoft()))
8044 NewVD->setImplicitlyInline();
8045 break;
8046
8048 if (!NewVD->hasGlobalStorage())
8050 diag::err_constinit_local_variable);
8051 else
8052 NewVD->addAttr(
8053 ConstInitAttr::Create(Context, D.getDeclSpec().getConstexprSpecLoc(),
8054 ConstInitAttr::Keyword_constinit));
8055 break;
8056 }
8057
8058 // C99 6.7.4p3
8059 // An inline definition of a function with external linkage shall
8060 // not contain a definition of a modifiable object with static or
8061 // thread storage duration...
8062 // We only apply this when the function is required to be defined
8063 // elsewhere, i.e. when the function is not 'extern inline'. Note
8064 // that a local variable with thread storage duration still has to
8065 // be marked 'static'. Also note that it's possible to get these
8066 // semantics in C++ using __attribute__((gnu_inline)).
8067 if (SC == SC_Static && S->getFnParent() != nullptr &&
8068 !NewVD->getType().isConstQualified()) {
8070 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
8072 diag::warn_static_local_in_extern_inline);
8074 }
8075 }
8076
8078 if (IsVariableTemplateSpecialization)
8079 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
8080 << (IsPartialSpecialization ? 1 : 0)
8083 else if (IsMemberSpecialization)
8084 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
8085 << 2
8087 else if (NewVD->hasLocalStorage())
8088 Diag(NewVD->getLocation(), diag::err_module_private_local)
8089 << 0 << NewVD
8093 else {
8094 NewVD->setModulePrivate();
8095 if (NewTemplate)
8096 NewTemplate->setModulePrivate();
8097 for (auto *B : Bindings)
8098 B->setModulePrivate();
8099 }
8100 }
8101
8102 if (getLangOpts().OpenCL) {
8104
8106 if (TSC != TSCS_unspecified) {
8108 diag::err_opencl_unknown_type_specifier)
8110 << DeclSpec::getSpecifierName(TSC) << 1;
8111 NewVD->setInvalidDecl();
8112 }
8113 }
8114
8115 // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
8116 // address space if the table has local storage (semantic checks elsewhere
8117 // will produce an error anyway).
8118 if (const auto *ATy = dyn_cast<ArrayType>(NewVD->getType())) {
8119 if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&
8120 !NewVD->hasLocalStorage()) {
8121 QualType Type = Context.getAddrSpaceQualType(
8122 NewVD->getType(), Context.getLangASForBuiltinAddressSpace(1));
8123 NewVD->setType(Type);
8124 }
8125 }
8126
8127 // Handle attributes prior to checking for duplicates in MergeVarDecl
8128 ProcessDeclAttributes(S, NewVD, D);
8129
8130 if (getLangOpts().HLSL)
8132
8133 if (getLangOpts().OpenACC)
8135
8136 // FIXME: This is probably the wrong location to be doing this and we should
8137 // probably be doing this for more attributes (especially for function
8138 // pointer attributes such as format, warn_unused_result, etc.). Ideally
8139 // the code to copy attributes would be generated by TableGen.
8140 if (R->isFunctionPointerType())
8141 if (const auto *TT = R->getAs<TypedefType>())
8143
8144 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8145 if (EmitTLSUnsupportedError &&
8147 (getLangOpts().OpenMPIsTargetDevice &&
8148 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
8150 diag::err_thread_unsupported);
8151
8152 if (EmitTLSUnsupportedError &&
8153 (LangOpts.SYCLIsDevice ||
8154 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)))
8155 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
8156 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
8157 // storage [duration]."
8158 if (SC == SC_None && S->getFnParent() != nullptr &&
8159 (NewVD->hasAttr<CUDASharedAttr>() ||
8160 NewVD->hasAttr<CUDAConstantAttr>())) {
8161 NewVD->setStorageClass(SC_Static);
8162 }
8163 }
8164
8165 // Ensure that dllimport globals without explicit storage class are treated as
8166 // extern. The storage class is set above using parsed attributes. Now we can
8167 // check the VarDecl itself.
8168 assert(!NewVD->hasAttr<DLLImportAttr>() ||
8169 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
8170 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
8171
8172 // In auto-retain/release, infer strong retension for variables of
8173 // retainable type.
8174 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewVD))
8175 NewVD->setInvalidDecl();
8176
8177 // Handle GNU asm-label extension (encoded as an attribute).
8178 if (Expr *E = D.getAsmLabel()) {
8179 // The parser guarantees this is a string.
8181 StringRef Label = SE->getString();
8182 if (S->getFnParent() != nullptr) {
8183 switch (SC) {
8184 case SC_None:
8185 case SC_Auto:
8186 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
8187 break;
8188 case SC_Register:
8189 // Local Named register
8190 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
8192 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
8193 break;
8194 case SC_Static:
8195 case SC_Extern:
8196 case SC_PrivateExtern:
8197 break;
8198 }
8199 } else if (SC == SC_Register) {
8200 // Global Named register
8201 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
8202 const auto &TI = Context.getTargetInfo();
8203 bool HasSizeMismatch;
8204
8205 if (!TI.isValidGCCRegisterName(Label))
8206 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
8207 else if (!TI.validateGlobalRegisterVariable(Label,
8208 Context.getTypeSize(R),
8209 HasSizeMismatch))
8210 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
8211 else if (HasSizeMismatch)
8212 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
8213 }
8214
8215 if (!R->isIntegralType(Context) && !R->isPointerType()) {
8216 Diag(TInfo->getTypeLoc().getBeginLoc(),
8217 diag::err_asm_unsupported_register_type)
8218 << TInfo->getTypeLoc().getSourceRange();
8219 NewVD->setInvalidDecl(true);
8220 }
8221 }
8222
8223 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, SE->getStrTokenLoc(0)));
8224 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8225 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8227 if (I != ExtnameUndeclaredIdentifiers.end()) {
8228 if (isDeclExternC(NewVD)) {
8229 NewVD->addAttr(I->second);
8231 } else
8232 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
8233 << /*Variable*/1 << NewVD;
8234 }
8235 }
8236
8237 // Find the shadowed declaration before filtering for scope.
8238 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
8240 : nullptr;
8241
8242 // Don't consider existing declarations that are in a different
8243 // scope and are out-of-semantic-context declarations (if the new
8244 // declaration has linkage).
8247 IsMemberSpecialization ||
8248 IsVariableTemplateSpecialization);
8249
8250 // Check whether the previous declaration is in the same block scope. This
8251 // affects whether we merge types with it, per C++11 [dcl.array]p3.
8252 if (getLangOpts().CPlusPlus &&
8253 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
8255 Previous.isSingleResult() && !Previous.isShadowed() &&
8256 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
8257
8258 if (!getLangOpts().CPlusPlus) {
8260 } else {
8261 // If this is an explicit specialization of a static data member, check it.
8262 if (IsMemberSpecialization && !IsVariableTemplate &&
8263 !IsVariableTemplateSpecialization && !NewVD->isInvalidDecl() &&
8265 NewVD->setInvalidDecl();
8266
8267 // Merge the decl with the existing one if appropriate.
8268 if (!Previous.empty()) {
8269 if (Previous.isSingleResult() &&
8270 isa<FieldDecl>(Previous.getFoundDecl()) &&
8271 D.getCXXScopeSpec().isSet()) {
8272 // The user tried to define a non-static data member
8273 // out-of-line (C++ [dcl.meaning]p1).
8274 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
8275 << D.getCXXScopeSpec().getRange();
8276 Previous.clear();
8277 NewVD->setInvalidDecl();
8278 }
8279 } else if (D.getCXXScopeSpec().isSet() &&
8280 !IsVariableTemplateSpecialization) {
8281 // No previous declaration in the qualifying scope.
8282 Diag(D.getIdentifierLoc(), diag::err_no_member)
8283 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
8284 << D.getCXXScopeSpec().getRange();
8285 NewVD->setInvalidDecl();
8286 }
8287
8288 if (!IsPlaceholderVariable)
8290
8291 // CheckVariableDeclaration will set NewVD as invalid if something is in
8292 // error like WebAssembly tables being declared as arrays with a non-zero
8293 // size, but then parsing continues and emits further errors on that line.
8294 // To avoid that we check here if it happened and return nullptr.
8295 if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())
8296 return nullptr;
8297
8298 if (NewTemplate) {
8299 VarTemplateDecl *PrevVarTemplate =
8300 NewVD->getPreviousDecl()
8302 : nullptr;
8303
8304 // Check the template parameter list of this declaration, possibly
8305 // merging in the template parameter list from the previous variable
8306 // template declaration.
8308 TemplateParams,
8309 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8310 : nullptr,
8311 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8312 DC->isDependentContext())
8314 : TPC_Other))
8315 NewVD->setInvalidDecl();
8316
8317 // If we are providing an explicit specialization of a static variable
8318 // template, make a note of that.
8319 if (PrevVarTemplate &&
8320 PrevVarTemplate->getInstantiatedFromMemberTemplate())
8321 PrevVarTemplate->setMemberSpecialization();
8322 }
8323 }
8324
8325 // Diagnose shadowed variables iff this isn't a redeclaration.
8326 if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration())
8327 CheckShadow(NewVD, ShadowedDecl, Previous);
8328
8329 ProcessPragmaWeak(S, NewVD);
8330
8331 // If this is the first declaration of an extern C variable, update
8332 // the map of such variables.
8333 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8334 isIncompleteDeclExternC(*this, NewVD))
8336
8337 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8339 Decl *ManglingContextDecl;
8340 std::tie(MCtx, ManglingContextDecl) =
8342 if (MCtx) {
8343 Context.setManglingNumber(
8344 NewVD, MCtx->getManglingNumber(
8345 NewVD, getMSManglingNumber(getLangOpts(), S)));
8346 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
8347 }
8348 }
8349
8350 // Special handling of variable named 'main'.
8351 if (!getLangOpts().Freestanding && isMainVar(Name, NewVD)) {
8352 // C++ [basic.start.main]p3:
8353 // A program that declares
8354 // - a variable main at global scope, or
8355 // - an entity named main with C language linkage (in any namespace)
8356 // is ill-formed
8357 if (getLangOpts().CPlusPlus)
8358 Diag(D.getBeginLoc(), diag::err_main_global_variable)
8359 << NewVD->isExternC();
8360
8361 // In C, and external-linkage variable named main results in undefined
8362 // behavior.
8363 else if (NewVD->hasExternalFormalLinkage())
8364 Diag(D.getBeginLoc(), diag::warn_main_redefined);
8365 }
8366
8367 if (D.isRedeclaration() && !Previous.empty()) {
8368 NamedDecl *Prev = Previous.getRepresentativeDecl();
8369 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
8371 }
8372
8373 if (NewTemplate) {
8374 if (NewVD->isInvalidDecl())
8375 NewTemplate->setInvalidDecl();
8376 ActOnDocumentableDecl(NewTemplate);
8377 return NewTemplate;
8378 }
8379
8380 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8382
8384
8385 return NewVD;
8386}
8387
8388/// Enum describing the %select options in diag::warn_decl_shadow.
8398
8399/// Determine what kind of declaration we're shadowing.
8401 const DeclContext *OldDC) {
8402 if (isa<TypeAliasDecl>(ShadowedDecl))
8403 return SDK_Using;
8404 else if (isa<TypedefDecl>(ShadowedDecl))
8405 return SDK_Typedef;
8406 else if (isa<BindingDecl>(ShadowedDecl))
8407 return SDK_StructuredBinding;
8408 else if (isa<RecordDecl>(OldDC))
8409 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8410
8411 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8412}
8413
8414/// Return the location of the capture if the given lambda captures the given
8415/// variable \p VD, or an invalid source location otherwise.
8417 const ValueDecl *VD) {
8418 for (const Capture &Capture : LSI->Captures) {
8420 return Capture.getLocation();
8421 }
8422 return SourceLocation();
8423}
8424
8426 const LookupResult &R) {
8427 // Only diagnose if we're shadowing an unambiguous field or variable.
8429 return false;
8430
8431 // Return false if warning is ignored.
8432 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
8433}
8434
8436 const LookupResult &R) {
8438 return nullptr;
8439
8440 // Don't diagnose declarations at file scope.
8441 if (D->hasGlobalStorage() && !D->isStaticLocal())
8442 return nullptr;
8443
8444 NamedDecl *ShadowedDecl = R.getFoundDecl();
8445 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8446 : nullptr;
8447}
8448
8450 const LookupResult &R) {
8451 // Don't warn if typedef declaration is part of a class
8452 if (D->getDeclContext()->isRecord())
8453 return nullptr;
8454
8456 return nullptr;
8457
8458 NamedDecl *ShadowedDecl = R.getFoundDecl();
8459 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
8460}
8461
8463 const LookupResult &R) {
8465 return nullptr;
8466
8467 NamedDecl *ShadowedDecl = R.getFoundDecl();
8468 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8469 : nullptr;
8470}
8471
8473 const LookupResult &R) {
8474 DeclContext *NewDC = D->getDeclContext();
8475
8476 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
8477 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) {
8478 // Fields are not shadowed by variables in C++ static methods.
8479 if (MD->isStatic())
8480 return;
8481
8482 if (!MD->getParent()->isLambda() && MD->isExplicitObjectMemberFunction())
8483 return;
8484 }
8485 // Fields shadowed by constructor parameters are a special case. Usually
8486 // the constructor initializes the field with the parameter.
8487 if (isa<CXXConstructorDecl>(NewDC))
8488 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
8489 // Remember that this was shadowed so we can either warn about its
8490 // modification or its existence depending on warning settings.
8491 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
8492 return;
8493 }
8494 }
8495
8496 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
8497 if (shadowedVar->isExternC()) {
8498 // For shadowing external vars, make sure that we point to the global
8499 // declaration, not a locally scoped extern declaration.
8500 for (auto *I : shadowedVar->redecls())
8501 if (I->isFileVarDecl()) {
8502 ShadowedDecl = I;
8503 break;
8504 }
8505 }
8506
8507 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8508
8509 unsigned WarningDiag = diag::warn_decl_shadow;
8510 SourceLocation CaptureLoc;
8511 if (isa<VarDecl>(D) && NewDC && isa<CXXMethodDecl>(NewDC)) {
8512 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
8513 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
8514 // Handle both VarDecl and BindingDecl in lambda contexts
8515 if (isa<VarDecl, BindingDecl>(ShadowedDecl)) {
8516 const auto *VD = cast<ValueDecl>(ShadowedDecl);
8517 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
8518 if (RD->getLambdaCaptureDefault() == LCD_None) {
8519 // Try to avoid warnings for lambdas with an explicit capture
8520 // list. Warn only when the lambda captures the shadowed decl
8521 // explicitly.
8522 CaptureLoc = getCaptureLocation(LSI, VD);
8523 if (CaptureLoc.isInvalid())
8524 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8525 } else {
8526 // Remember that this was shadowed so we can avoid the warning if
8527 // the shadowed decl isn't captured and the warning settings allow
8528 // it.
8530 ->ShadowingDecls.push_back({D, VD});
8531 return;
8532 }
8533 }
8534 if (isa<FieldDecl>(ShadowedDecl)) {
8535 // If lambda can capture this, then emit default shadowing warning,
8536 // Otherwise it is not really a shadowing case since field is not
8537 // available in lambda's body.
8538 // At this point we don't know that lambda can capture this, so
8539 // remember that this was shadowed and delay until we know.
8541 ->ShadowingDecls.push_back({D, ShadowedDecl});
8542 return;
8543 }
8544 }
8545 // Apply scoping logic to both VarDecl and BindingDecl with local storage
8546 if (isa<VarDecl, BindingDecl>(ShadowedDecl)) {
8547 bool HasLocalStorage = false;
8548 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl))
8549 HasLocalStorage = VD->hasLocalStorage();
8550 else if (const auto *BD = dyn_cast<BindingDecl>(ShadowedDecl))
8551 HasLocalStorage =
8552 cast<VarDecl>(BD->getDecomposedDecl())->hasLocalStorage();
8553
8554 if (HasLocalStorage) {
8555 // A variable can't shadow a local variable or binding in an enclosing
8556 // scope, if they are separated by a non-capturing declaration
8557 // context.
8558 for (DeclContext *ParentDC = NewDC;
8559 ParentDC && !ParentDC->Equals(OldDC);
8560 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
8561 // Only block literals, captured statements, and lambda expressions
8562 // can capture; other scopes don't.
8563 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
8564 !isLambdaCallOperator(ParentDC))
8565 return;
8566 }
8567 }
8568 }
8569 }
8570 }
8571
8572 // Never warn about shadowing a placeholder variable.
8573 if (ShadowedDecl->isPlaceholderVar(getLangOpts()))
8574 return;
8575
8576 // Only warn about certain kinds of shadowing for class members.
8577 if (NewDC) {
8578 // In particular, don't warn about shadowing non-class members.
8579 if (NewDC->isRecord() && !OldDC->isRecord())
8580 return;
8581
8582 // Skip shadowing check if we're in a class scope, dealing with an enum
8583 // constant in a different context.
8584 DeclContext *ReDC = NewDC->getRedeclContext();
8585 if (ReDC->isRecord() && isa<EnumConstantDecl>(D) && !OldDC->Equals(ReDC))
8586 return;
8587
8588 // TODO: should we warn about static data members shadowing
8589 // static data members from base classes?
8590
8591 // TODO: don't diagnose for inaccessible shadowed members.
8592 // This is hard to do perfectly because we might friend the
8593 // shadowing context, but that's just a false negative.
8594 }
8595
8596 DeclarationName Name = R.getLookupName();
8597
8598 // Emit warning and note.
8599 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8600 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8601 if (!CaptureLoc.isInvalid())
8602 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8603 << Name << /*explicitly*/ 1;
8604 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8605}
8606
8608 for (const auto &Shadow : LSI->ShadowingDecls) {
8609 const NamedDecl *ShadowedDecl = Shadow.ShadowedDecl;
8610 // Try to avoid the warning when the shadowed decl isn't captured.
8611 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8612 if (isa<VarDecl, BindingDecl>(ShadowedDecl)) {
8613 const auto *VD = cast<ValueDecl>(ShadowedDecl);
8614 SourceLocation CaptureLoc = getCaptureLocation(LSI, VD);
8615 Diag(Shadow.VD->getLocation(),
8616 CaptureLoc.isInvalid() ? diag::warn_decl_shadow_uncaptured_local
8617 : diag::warn_decl_shadow)
8618 << Shadow.VD->getDeclName()
8619 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8620 if (CaptureLoc.isValid())
8621 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8622 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8623 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8624 } else if (isa<FieldDecl>(ShadowedDecl)) {
8625 Diag(Shadow.VD->getLocation(),
8626 LSI->isCXXThisCaptured() ? diag::warn_decl_shadow
8627 : diag::warn_decl_shadow_uncaptured_local)
8628 << Shadow.VD->getDeclName()
8629 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8630 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8631 }
8632 }
8633}
8634
8636 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8637 return;
8638
8639 LookupResult R(*this, D->getDeclName(), D->getLocation(),
8642 LookupName(R, S);
8643 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8644 CheckShadow(D, ShadowedDecl, R);
8645}
8646
8647/// Check if 'E', which is an expression that is about to be modified, refers
8648/// to a constructor parameter that shadows a field.
8650 // Quickly ignore expressions that can't be shadowing ctor parameters.
8651 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8652 return;
8653 E = E->IgnoreParenImpCasts();
8654 auto *DRE = dyn_cast<DeclRefExpr>(E);
8655 if (!DRE)
8656 return;
8657 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8658 auto I = ShadowingDecls.find(D);
8659 if (I == ShadowingDecls.end())
8660 return;
8661 const NamedDecl *ShadowedDecl = I->second;
8662 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8663 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8664 Diag(D->getLocation(), diag::note_var_declared_here) << D;
8665 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8666
8667 // Avoid issuing multiple warnings about the same decl.
8668 ShadowingDecls.erase(I);
8669}
8670
8671/// Check for conflict between this global or extern "C" declaration and
8672/// previous global or extern "C" declarations. This is only used in C++.
8673template<typename T>
8675 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8676 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8677 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8678
8679 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8680 // The common case: this global doesn't conflict with any extern "C"
8681 // declaration.
8682 return false;
8683 }
8684
8685 if (Prev) {
8686 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8687 // Both the old and new declarations have C language linkage. This is a
8688 // redeclaration.
8689 Previous.clear();
8690 Previous.addDecl(Prev);
8691 return true;
8692 }
8693
8694 // This is a global, non-extern "C" declaration, and there is a previous
8695 // non-global extern "C" declaration. Diagnose if this is a variable
8696 // declaration.
8697 if (!isa<VarDecl>(ND))
8698 return false;
8699 } else {
8700 // The declaration is extern "C". Check for any declaration in the
8701 // translation unit which might conflict.
8702 if (IsGlobal) {
8703 // We have already performed the lookup into the translation unit.
8704 IsGlobal = false;
8705 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8706 I != E; ++I) {
8707 if (isa<VarDecl>(*I)) {
8708 Prev = *I;
8709 break;
8710 }
8711 }
8712 } else {
8714 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8715 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8716 I != E; ++I) {
8717 if (isa<VarDecl>(*I)) {
8718 Prev = *I;
8719 break;
8720 }
8721 // FIXME: If we have any other entity with this name in global scope,
8722 // the declaration is ill-formed, but that is a defect: it breaks the
8723 // 'stat' hack, for instance. Only variables can have mangled name
8724 // clashes with extern "C" declarations, so only they deserve a
8725 // diagnostic.
8726 }
8727 }
8728
8729 if (!Prev)
8730 return false;
8731 }
8732
8733 // Use the first declaration's location to ensure we point at something which
8734 // is lexically inside an extern "C" linkage-spec.
8735 assert(Prev && "should have found a previous declaration to diagnose");
8736 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8737 Prev = FD->getFirstDecl();
8738 else
8739 Prev = cast<VarDecl>(Prev)->getFirstDecl();
8740
8741 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8742 << IsGlobal << ND;
8743 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8744 << IsGlobal;
8745 return false;
8746}
8747
8748/// Apply special rules for handling extern "C" declarations. Returns \c true
8749/// if we have found that this is a redeclaration of some prior entity.
8750///
8751/// Per C++ [dcl.link]p6:
8752/// Two declarations [for a function or variable] with C language linkage
8753/// with the same name that appear in different scopes refer to the same
8754/// [entity]. An entity with C language linkage shall not be declared with
8755/// the same name as an entity in global scope.
8756template<typename T>
8759 if (!S.getLangOpts().CPlusPlus) {
8760 // In C, when declaring a global variable, look for a corresponding 'extern'
8761 // variable declared in function scope. We don't need this in C++, because
8762 // we find local extern decls in the surrounding file-scope DeclContext.
8763 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8764 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8765 Previous.clear();
8766 Previous.addDecl(Prev);
8767 return true;
8768 }
8769 }
8770 return false;
8771 }
8772
8773 // A declaration in the translation unit can conflict with an extern "C"
8774 // declaration.
8775 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8776 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8777
8778 // An extern "C" declaration can conflict with a declaration in the
8779 // translation unit or can be a redeclaration of an extern "C" declaration
8780 // in another scope.
8781 if (isIncompleteDeclExternC(S,ND))
8782 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8783
8784 // Neither global nor extern "C": nothing to do.
8785 return false;
8786}
8787
8788static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc,
8789 QualType T) {
8790 QualType CanonT = SemaRef.Context.getCanonicalType(T);
8791 // C23 6.7.1p5: An object declared with storage-class specifier constexpr or
8792 // any of its members, even recursively, shall not have an atomic type, or a
8793 // variably modified type, or a type that is volatile or restrict qualified.
8794 if (CanonT->isVariablyModifiedType()) {
8795 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8796 return true;
8797 }
8798
8799 // Arrays are qualified by their element type, so get the base type (this
8800 // works on non-arrays as well).
8801 CanonT = SemaRef.Context.getBaseElementType(CanonT);
8802
8803 if (CanonT->isAtomicType() || CanonT.isVolatileQualified() ||
8804 CanonT.isRestrictQualified()) {
8805 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8806 return true;
8807 }
8808
8809 if (CanonT->isRecordType()) {
8810 const RecordDecl *RD = CanonT->getAsRecordDecl();
8811 if (!RD->isInvalidDecl() &&
8812 llvm::any_of(RD->fields(), [&SemaRef, VarLoc](const FieldDecl *F) {
8813 return CheckC23ConstexprVarType(SemaRef, VarLoc, F->getType());
8814 }))
8815 return true;
8816 }
8817
8818 return false;
8819}
8820
8822 // If the decl is already known invalid, don't check it.
8823 if (NewVD->isInvalidDecl())
8824 return;
8825
8826 QualType T = NewVD->getType();
8827
8828 // Defer checking an 'auto' type until its initializer is attached.
8829 if (T->isUndeducedType())
8830 return;
8831
8832 if (NewVD->hasAttrs())
8834
8835 if (T->isObjCObjectType()) {
8836 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8837 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8838 T = Context.getObjCObjectPointerType(T);
8839 NewVD->setType(T);
8840 }
8841
8842 // Emit an error if an address space was applied to decl with local storage.
8843 // This includes arrays of objects with address space qualifiers, but not
8844 // automatic variables that point to other address spaces.
8845 // ISO/IEC TR 18037 S5.1.2
8846 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8847 T.getAddressSpace() != LangAS::Default) {
8848 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8849 NewVD->setInvalidDecl();
8850 return;
8851 }
8852
8853 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8854 // scope.
8855 if (getLangOpts().OpenCLVersion == 120 &&
8856 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8857 getLangOpts()) &&
8858 NewVD->isStaticLocal()) {
8859 Diag(NewVD->getLocation(), diag::err_static_function_scope);
8860 NewVD->setInvalidDecl();
8861 return;
8862 }
8863
8864 if (getLangOpts().OpenCL) {
8865 if (!diagnoseOpenCLTypes(*this, NewVD))
8866 return;
8867
8868 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8869 if (NewVD->hasAttr<BlocksAttr>()) {
8870 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8871 return;
8872 }
8873
8874 if (T->isBlockPointerType()) {
8875 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8876 // can't use 'extern' storage class.
8877 if (!T.isConstQualified()) {
8878 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8879 << 0 /*const*/;
8880 NewVD->setInvalidDecl();
8881 return;
8882 }
8883 if (NewVD->hasExternalStorage()) {
8884 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8885 NewVD->setInvalidDecl();
8886 return;
8887 }
8888 }
8889
8890 // FIXME: Adding local AS in C++ for OpenCL might make sense.
8891 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8892 NewVD->hasExternalStorage()) {
8893 if (!T->isSamplerT() && !T->isDependentType() &&
8894 !(T.getAddressSpace() == LangAS::opencl_constant ||
8895 (T.getAddressSpace() == LangAS::opencl_global &&
8896 getOpenCLOptions().areProgramScopeVariablesSupported(
8897 getLangOpts())))) {
8898 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8899 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8900 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8901 << Scope << "global or constant";
8902 else
8903 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8904 << Scope << "constant";
8905 NewVD->setInvalidDecl();
8906 return;
8907 }
8908 } else {
8909 if (T.getAddressSpace() == LangAS::opencl_global) {
8910 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8911 << 1 /*is any function*/ << "global";
8912 NewVD->setInvalidDecl();
8913 return;
8914 }
8915 if (T.getAddressSpace() == LangAS::opencl_constant ||
8916 T.getAddressSpace() == LangAS::opencl_local) {
8918 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8919 // in functions.
8920 if (FD && !FD->hasAttr<DeviceKernelAttr>()) {
8921 if (T.getAddressSpace() == LangAS::opencl_constant)
8922 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8923 << 0 /*non-kernel only*/ << "constant";
8924 else
8925 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8926 << 0 /*non-kernel only*/ << "local";
8927 NewVD->setInvalidDecl();
8928 return;
8929 }
8930 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8931 // in the outermost scope of a kernel function.
8932 if (FD && FD->hasAttr<DeviceKernelAttr>()) {
8933 if (!getCurScope()->isFunctionScope()) {
8934 if (T.getAddressSpace() == LangAS::opencl_constant)
8935 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8936 << "constant";
8937 else
8938 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8939 << "local";
8940 NewVD->setInvalidDecl();
8941 return;
8942 }
8943 }
8944 } else if (T.getAddressSpace() != LangAS::opencl_private &&
8945 // If we are parsing a template we didn't deduce an addr
8946 // space yet.
8947 T.getAddressSpace() != LangAS::Default) {
8948 // Do not allow other address spaces on automatic variable.
8949 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8950 NewVD->setInvalidDecl();
8951 return;
8952 }
8953 }
8954 }
8955
8956 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8957 && !NewVD->hasAttr<BlocksAttr>()) {
8958 if (getLangOpts().getGC() != LangOptions::NonGC)
8959 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8960 else {
8961 assert(!getLangOpts().ObjCAutoRefCount);
8962 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8963 }
8964 }
8965
8966 // WebAssembly tables must be static with a zero length and can't be
8967 // declared within functions.
8968 if (T->isWebAssemblyTableType()) {
8969 if (getCurScope()->getParent()) { // Parent is null at top-level
8970 Diag(NewVD->getLocation(), diag::err_wasm_table_in_function);
8971 NewVD->setInvalidDecl();
8972 return;
8973 }
8974 if (NewVD->getStorageClass() != SC_Static) {
8975 Diag(NewVD->getLocation(), diag::err_wasm_table_must_be_static);
8976 NewVD->setInvalidDecl();
8977 return;
8978 }
8979 const auto *ATy = dyn_cast<ConstantArrayType>(T.getTypePtr());
8980 if (!ATy || ATy->getZExtSize() != 0) {
8981 Diag(NewVD->getLocation(),
8982 diag::err_typecheck_wasm_table_must_have_zero_length);
8983 NewVD->setInvalidDecl();
8984 return;
8985 }
8986 }
8987
8988 // zero sized static arrays are not allowed in HIP device functions
8989 if (getLangOpts().HIP && LangOpts.CUDAIsDevice) {
8990 if (FunctionDecl *FD = getCurFunctionDecl();
8991 FD &&
8992 (FD->hasAttr<CUDADeviceAttr>() || FD->hasAttr<CUDAGlobalAttr>())) {
8993 if (const ConstantArrayType *ArrayT =
8994 getASTContext().getAsConstantArrayType(T);
8995 ArrayT && ArrayT->isZeroSize()) {
8996 Diag(NewVD->getLocation(), diag::err_typecheck_zero_array_size) << 2;
8997 }
8998 }
8999 }
9000
9001 bool isVM = T->isVariablyModifiedType();
9002 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
9003 NewVD->hasAttr<BlocksAttr>())
9005
9006 if ((isVM && NewVD->hasLinkage()) ||
9007 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
9008 bool SizeIsNegative;
9009 llvm::APSInt Oversized;
9011 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
9012 QualType FixedT;
9013 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
9014 FixedT = FixedTInfo->getType();
9015 else if (FixedTInfo) {
9016 // Type and type-as-written are canonically different. We need to fix up
9017 // both types separately.
9018 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
9019 Oversized);
9020 }
9021 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
9022 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
9023 // FIXME: This won't give the correct result for
9024 // int a[10][n];
9025 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
9026
9027 if (NewVD->isFileVarDecl())
9028 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
9029 << SizeRange;
9030 else if (NewVD->isStaticLocal())
9031 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
9032 << SizeRange;
9033 else
9034 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
9035 << SizeRange;
9036 NewVD->setInvalidDecl();
9037 return;
9038 }
9039
9040 if (!FixedTInfo) {
9041 if (NewVD->isFileVarDecl())
9042 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
9043 else
9044 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
9045 NewVD->setInvalidDecl();
9046 return;
9047 }
9048
9049 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
9050 NewVD->setType(FixedT);
9051 NewVD->setTypeSourceInfo(FixedTInfo);
9052 }
9053
9054 if (T->isVoidType()) {
9055 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
9056 // of objects and functions.
9058 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
9059 << T;
9060 NewVD->setInvalidDecl();
9061 return;
9062 }
9063 }
9064
9065 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
9066 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
9067 NewVD->setInvalidDecl();
9068 return;
9069 }
9070
9071 if (!NewVD->hasLocalStorage() && T->isSizelessType() &&
9072 !T.isWebAssemblyReferenceType() && !T->isHLSLSpecificType()) {
9073 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
9074 NewVD->setInvalidDecl();
9075 return;
9076 }
9077
9078 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
9079 Diag(NewVD->getLocation(), diag::err_block_on_vm);
9080 NewVD->setInvalidDecl();
9081 return;
9082 }
9083
9084 if (getLangOpts().C23 && NewVD->isConstexpr() &&
9085 CheckC23ConstexprVarType(*this, NewVD->getLocation(), T)) {
9086 NewVD->setInvalidDecl();
9087 return;
9088 }
9089
9090 if (getLangOpts().CPlusPlus && NewVD->isConstexpr() &&
9091 !T->isDependentType() &&
9093 diag::err_constexpr_var_non_literal)) {
9094 NewVD->setInvalidDecl();
9095 return;
9096 }
9097
9098 // PPC MMA non-pointer types are not allowed as non-local variable types.
9099 if (Context.getTargetInfo().getTriple().isPPC64() &&
9100 !NewVD->isLocalVarDecl() &&
9101 PPC().CheckPPCMMAType(T, NewVD->getLocation())) {
9102 NewVD->setInvalidDecl();
9103 return;
9104 }
9105
9106 // Check that SVE types are only used in functions with SVE available.
9107 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
9109 llvm::StringMap<bool> CallerFeatureMap;
9110 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
9111
9112 if (!Builtin::evaluateRequiredTargetFeatures("sve", CallerFeatureMap)) {
9113 if (!Builtin::evaluateRequiredTargetFeatures("sme", CallerFeatureMap)) {
9114 Diag(NewVD->getLocation(), diag::err_sve_vector_in_non_sve_target) << T;
9115 NewVD->setInvalidDecl();
9116 return;
9117 } else if (!IsArmStreamingFunction(FD,
9118 /*IncludeLocallyStreaming=*/true)) {
9119 Diag(NewVD->getLocation(),
9120 diag::err_sve_vector_in_non_streaming_function)
9121 << T;
9122 NewVD->setInvalidDecl();
9123 return;
9124 }
9125 }
9126 }
9127
9128 if (T->isRVVSizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
9130 llvm::StringMap<bool> CallerFeatureMap;
9131 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
9133 CallerFeatureMap);
9134 }
9135}
9136
9139
9140 // If the decl is already known invalid, don't check it.
9141 if (NewVD->isInvalidDecl())
9142 return false;
9143
9144 // If we did not find anything by this name, look for a non-visible
9145 // extern "C" declaration with the same name.
9146 if (Previous.empty() &&
9148 Previous.setShadowed();
9149
9150 if (!Previous.empty()) {
9151 MergeVarDecl(NewVD, Previous);
9152 return true;
9153 }
9154 return false;
9155}
9156
9159
9160 // Look for methods in base classes that this method might override.
9161 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
9162 /*DetectVirtual=*/false);
9163 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9164 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
9165 DeclarationName Name = MD->getDeclName();
9166
9168 // We really want to find the base class destructor here.
9169 Name = Context.DeclarationNames.getCXXDestructorName(
9170 Context.getCanonicalTagType(BaseRecord));
9171 }
9172
9173 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
9174 CXXMethodDecl *BaseMD =
9175 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
9176 if (!BaseMD || !BaseMD->isVirtual() ||
9177 IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
9178 /*ConsiderCudaAttrs=*/true))
9179 continue;
9180 if (!CheckExplicitObjectOverride(MD, BaseMD))
9181 continue;
9182 if (Overridden.insert(BaseMD).second) {
9183 MD->addOverriddenMethod(BaseMD);
9188 }
9189
9190 // A method can only override one function from each base class. We
9191 // don't track indirectly overridden methods from bases of bases.
9192 return true;
9193 }
9194
9195 return false;
9196 };
9197
9198 DC->lookupInBases(VisitBase, Paths);
9199 return !Overridden.empty();
9200}
9201
9202namespace {
9203 // Struct for holding all of the extra arguments needed by
9204 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
9205 struct ActOnFDArgs {
9206 Scope *S;
9207 Declarator &D;
9208 MultiTemplateParamsArg TemplateParamLists;
9209 bool AddToScope;
9210 };
9211} // end anonymous namespace
9212
9213namespace {
9214
9215// Callback to only accept typo corrections that have a non-zero edit distance.
9216// Also only accept corrections that have the same parent decl.
9217class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
9218 public:
9219 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
9220 CXXRecordDecl *Parent)
9221 : Context(Context), OriginalFD(TypoFD),
9222 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
9223
9224 bool ValidateCandidate(const TypoCorrection &candidate) override {
9225 if (candidate.getEditDistance() == 0)
9226 return false;
9227
9228 SmallVector<unsigned, 1> MismatchedParams;
9229 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
9230 CDeclEnd = candidate.end();
9231 CDecl != CDeclEnd; ++CDecl) {
9232 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9233
9234 if (FD && !FD->hasBody() &&
9235 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
9236 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
9237 CXXRecordDecl *Parent = MD->getParent();
9238 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
9239 return true;
9240 } else if (!ExpectedParent) {
9241 return true;
9242 }
9243 }
9244 }
9245
9246 return false;
9247 }
9248
9249 std::unique_ptr<CorrectionCandidateCallback> clone() override {
9250 return std::make_unique<DifferentNameValidatorCCC>(*this);
9251 }
9252
9253 private:
9254 ASTContext &Context;
9255 FunctionDecl *OriginalFD;
9256 CXXRecordDecl *ExpectedParent;
9257};
9258
9259} // end anonymous namespace
9260
9264
9265/// Generate diagnostics for an invalid function redeclaration.
9266///
9267/// This routine handles generating the diagnostic messages for an invalid
9268/// function redeclaration, including finding possible similar declarations
9269/// or performing typo correction if there are no previous declarations with
9270/// the same name.
9271///
9272/// Returns a NamedDecl iff typo correction was performed and substituting in
9273/// the new declaration name does not cause new errors.
9275 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
9276 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
9277 DeclarationName Name = NewFD->getDeclName();
9278 DeclContext *NewDC = NewFD->getDeclContext();
9279 SmallVector<unsigned, 1> MismatchedParams;
9281 TypoCorrection Correction;
9282 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
9283 unsigned DiagMsg =
9284 IsLocalFriend ? diag::err_no_matching_local_friend :
9285 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
9286 diag::err_member_decl_does_not_match;
9287 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
9288 IsLocalFriend ? Sema::LookupLocalFriendName
9291
9292 NewFD->setInvalidDecl();
9293 if (IsLocalFriend)
9294 SemaRef.LookupName(Prev, S);
9295 else
9296 SemaRef.LookupQualifiedName(Prev, NewDC);
9297 assert(!Prev.isAmbiguous() &&
9298 "Cannot have an ambiguity in previous-declaration lookup");
9299 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9300 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
9301 MD ? MD->getParent() : nullptr);
9302 if (!Prev.empty()) {
9303 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
9304 Func != FuncEnd; ++Func) {
9305 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
9306 if (FD &&
9307 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9308 // Add 1 to the index so that 0 can mean the mismatch didn't
9309 // involve a parameter
9310 unsigned ParamNum =
9311 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
9312 NearMatches.push_back(std::make_pair(FD, ParamNum));
9313 }
9314 }
9315 // If the qualified name lookup yielded nothing, try typo correction
9316 } else if ((Correction = SemaRef.CorrectTypo(
9317 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
9318 &ExtraArgs.D.getCXXScopeSpec(), CCC,
9320 IsLocalFriend ? nullptr : NewDC))) {
9321 // Set up everything for the call to ActOnFunctionDeclarator
9322 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
9323 ExtraArgs.D.getIdentifierLoc());
9324 Previous.clear();
9325 Previous.setLookupName(Correction.getCorrection());
9326 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
9327 CDeclEnd = Correction.end();
9328 CDecl != CDeclEnd; ++CDecl) {
9329 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9330 if (FD && !FD->hasBody() &&
9331 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9332 Previous.addDecl(FD);
9333 }
9334 }
9335 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
9336
9337 NamedDecl *Result;
9338 // Retry building the function declaration with the new previous
9339 // declarations, and with errors suppressed.
9340 {
9341 // Trap errors.
9342 Sema::SFINAETrap Trap(SemaRef);
9343
9344 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
9345 // pieces need to verify the typo-corrected C++ declaration and hopefully
9346 // eliminate the need for the parameter pack ExtraArgs.
9347 Result = SemaRef.ActOnFunctionDeclarator(
9348 ExtraArgs.S, ExtraArgs.D,
9349 Correction.getCorrectionDecl()->getDeclContext(),
9350 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
9351 ExtraArgs.AddToScope);
9352
9353 if (Trap.hasErrorOccurred())
9354 Result = nullptr;
9355 }
9356
9357 if (Result) {
9358 // Determine which correction we picked.
9359 Decl *Canonical = Result->getCanonicalDecl();
9360 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9361 I != E; ++I)
9362 if ((*I)->getCanonicalDecl() == Canonical)
9363 Correction.setCorrectionDecl(*I);
9364
9365 // Let Sema know about the correction.
9367 SemaRef.diagnoseTypo(
9368 Correction,
9369 SemaRef.PDiag(IsLocalFriend
9370 ? diag::err_no_matching_local_friend_suggest
9371 : diag::err_member_decl_does_not_match_suggest)
9372 << Name << NewDC << IsDefinition);
9373 return Result;
9374 }
9375
9376 // Pretend the typo correction never occurred
9377 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
9378 ExtraArgs.D.getIdentifierLoc());
9379 ExtraArgs.D.setRedeclaration(wasRedeclaration);
9380 Previous.clear();
9381 Previous.setLookupName(Name);
9382 }
9383
9384 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
9385 << Name << NewDC << IsDefinition << NewFD->getLocation();
9386
9387 CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD);
9388 if (NewMD && DiagMsg == diag::err_member_decl_does_not_match) {
9389 CXXRecordDecl *RD = NewMD->getParent();
9390 SemaRef.Diag(RD->getLocation(), diag::note_defined_here)
9391 << RD->getName() << RD->getLocation();
9392 }
9393
9394 bool NewFDisConst = NewMD && NewMD->isConst();
9395
9396 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
9397 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
9398 NearMatch != NearMatchEnd; ++NearMatch) {
9399 FunctionDecl *FD = NearMatch->first;
9400 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
9401 bool FDisConst = MD && MD->isConst();
9402 bool IsMember = MD || !IsLocalFriend;
9403
9404 // FIXME: These notes are poorly worded for the local friend case.
9405 if (unsigned Idx = NearMatch->second) {
9406 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
9407 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
9408 if (Loc.isInvalid()) Loc = FD->getLocation();
9409 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
9410 : diag::note_local_decl_close_param_match)
9411 << Idx << FDParam->getType()
9412 << NewFD->getParamDecl(Idx - 1)->getType();
9413 } else if (FDisConst != NewFDisConst) {
9414 auto DB = SemaRef.Diag(FD->getLocation(),
9415 diag::note_member_def_close_const_match)
9416 << NewFDisConst << FD->getSourceRange().getEnd();
9417 if (const auto &FTI = ExtraArgs.D.getFunctionTypeInfo(); !NewFDisConst)
9418 DB << FixItHint::CreateInsertion(FTI.getRParenLoc().getLocWithOffset(1),
9419 " const");
9420 else if (FTI.hasMethodTypeQualifiers() &&
9421 FTI.getConstQualifierLoc().isValid())
9422 DB << FixItHint::CreateRemoval(FTI.getConstQualifierLoc());
9423 } else {
9424 SemaRef.Diag(FD->getLocation(),
9425 IsMember ? diag::note_member_def_close_match
9426 : diag::note_local_decl_close_match);
9427 }
9428 }
9429 return nullptr;
9430}
9431
9433 switch (D.getDeclSpec().getStorageClassSpec()) {
9434 default: llvm_unreachable("Unknown storage class!");
9435 case DeclSpec::SCS_auto:
9439 diag::err_typecheck_sclass_func);
9441 D.setInvalidType();
9442 break;
9443 case DeclSpec::SCS_unspecified: break;
9446 return SC_None;
9447 return SC_Extern;
9448 case DeclSpec::SCS_static: {
9450 // C99 6.7.1p5:
9451 // The declaration of an identifier for a function that has
9452 // block scope shall have no explicit storage-class specifier
9453 // other than extern
9454 // See also (C++ [dcl.stc]p4).
9456 diag::err_static_block_func);
9457 break;
9458 } else
9459 return SC_Static;
9460 }
9462 }
9463
9464 // No explicit storage class has already been returned
9465 return SC_None;
9466}
9467
9469 DeclContext *DC, QualType &R,
9470 TypeSourceInfo *TInfo,
9471 StorageClass SC,
9472 bool &IsVirtualOkay) {
9473 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9474 DeclarationName Name = NameInfo.getName();
9475
9476 FunctionDecl *NewFD = nullptr;
9477 bool isInline = D.getDeclSpec().isInlineSpecified();
9478
9480 if (ConstexprKind == ConstexprSpecKind::Constinit ||
9481 (SemaRef.getLangOpts().C23 &&
9482 ConstexprKind == ConstexprSpecKind::Constexpr)) {
9483
9484 if (SemaRef.getLangOpts().C23)
9485 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9486 diag::err_c23_constexpr_not_variable);
9487 else
9488 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9489 diag::err_constexpr_wrong_decl_kind)
9490 << static_cast<int>(ConstexprKind);
9491 ConstexprKind = ConstexprSpecKind::Unspecified;
9493 }
9494
9495 if (!SemaRef.getLangOpts().CPlusPlus) {
9496 // Determine whether the function was written with a prototype. This is
9497 // true when:
9498 // - there is a prototype in the declarator, or
9499 // - the type R of the function is some kind of typedef or other non-
9500 // attributed reference to a type name (which eventually refers to a
9501 // function type). Note, we can't always look at the adjusted type to
9502 // check this case because attributes may cause a non-function
9503 // declarator to still have a function type. e.g.,
9504 // typedef void func(int a);
9505 // __attribute__((noreturn)) func other_func; // This has a prototype
9506 bool HasPrototype =
9508 (D.getDeclSpec().isTypeRep() &&
9509 SemaRef.GetTypeFromParser(D.getDeclSpec().getRepAsType(), nullptr)
9510 ->isFunctionProtoType()) ||
9512 assert(
9513 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9514 "Strict prototypes are required");
9515
9516 NewFD = FunctionDecl::Create(
9517 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9518 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
9520 /*TrailingRequiresClause=*/{});
9521 if (D.isInvalidType())
9522 NewFD->setInvalidDecl();
9523
9524 return NewFD;
9525 }
9526
9528 AssociatedConstraint TrailingRequiresClause(D.getTrailingRequiresClause());
9529
9530 SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R);
9531
9533 // This is a C++ constructor declaration.
9534 assert(DC->isRecord() &&
9535 "Constructors can only be declared in a member context");
9536
9537 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9539 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9541 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9542 InheritedConstructor(), TrailingRequiresClause);
9543
9544 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9545 // This is a C++ destructor declaration.
9546 if (DC->isRecord()) {
9547 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9550 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
9551 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9552 /*isImplicitlyDeclared=*/false, ConstexprKind,
9553 TrailingRequiresClause);
9554 // User defined destructors start as not selected if the class definition is still
9555 // not done.
9556 if (Record->isBeingDefined())
9557 NewDD->setIneligibleOrNotSelected(true);
9558
9559 // If the destructor needs an implicit exception specification, set it
9560 // now. FIXME: It'd be nice to be able to create the right type to start
9561 // with, but the type needs to reference the destructor declaration.
9562 if (SemaRef.getLangOpts().CPlusPlus11)
9563 SemaRef.AdjustDestructorExceptionSpec(NewDD);
9564
9565 IsVirtualOkay = true;
9566 return NewDD;
9567
9568 } else {
9569 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
9570 D.setInvalidType();
9571
9572 // Create a FunctionDecl to satisfy the function definition parsing
9573 // code path.
9574 return FunctionDecl::Create(
9575 SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
9576 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9577 /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
9578 }
9579
9581 if (!DC->isRecord()) {
9582 SemaRef.Diag(D.getIdentifierLoc(),
9583 diag::err_conv_function_not_member);
9584 return nullptr;
9585 }
9586
9587 SemaRef.CheckConversionDeclarator(D, R, SC);
9588 if (D.isInvalidType())
9589 return nullptr;
9590
9591 IsVirtualOkay = true;
9593 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9594 TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9595 ExplicitSpecifier, ConstexprKind, SourceLocation(),
9596 TrailingRequiresClause);
9597
9599 if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))
9600 return nullptr;
9602 SemaRef.Context, DC, D.getBeginLoc(), ExplicitSpecifier, NameInfo, R,
9603 TInfo, D.getEndLoc(), /*Ctor=*/nullptr,
9604 /*Kind=*/DeductionCandidate::Normal, TrailingRequiresClause);
9605 } else if (DC->isRecord()) {
9606 // If the name of the function is the same as the name of the record,
9607 // then this must be an invalid constructor that has a return type.
9608 // (The parser checks for a return type and makes the declarator a
9609 // constructor if it has no return type).
9610 if (Name.getAsIdentifierInfo() &&
9611 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
9612 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
9615 return nullptr;
9616 }
9617
9618 // This is a C++ method declaration.
9620 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9621 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9622 ConstexprKind, SourceLocation(), TrailingRequiresClause);
9623 IsVirtualOkay = !Ret->isStatic();
9624 return Ret;
9625 } else {
9626 bool isFriend =
9627 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9628 if (!isFriend && SemaRef.CurContext->isRecord())
9629 return nullptr;
9630
9631 // Determine whether the function was written with a
9632 // prototype. This true when:
9633 // - we're in C++ (where every function has a prototype),
9634 return FunctionDecl::Create(
9635 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9636 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9637 true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9638 }
9639}
9640
9649
9651 // Size dependent types are just typedefs to normal integer types
9652 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9653 // integers other than by their names.
9654 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9655
9656 // Remove typedefs one by one until we reach a typedef
9657 // for a size dependent type.
9658 QualType DesugaredTy = Ty;
9659 do {
9660 ArrayRef<StringRef> Names(SizeTypeNames);
9661 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
9662 if (Names.end() != Match)
9663 return true;
9664
9665 Ty = DesugaredTy;
9666 DesugaredTy = Ty.getSingleStepDesugaredType(C);
9667 } while (DesugaredTy != Ty);
9668
9669 return false;
9670}
9671
9673 if (PT->isDependentType())
9674 return InvalidKernelParam;
9675
9676 if (PT->isPointerOrReferenceType()) {
9677 QualType PointeeType = PT->getPointeeType();
9678 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9679 PointeeType.getAddressSpace() == LangAS::opencl_private ||
9680 PointeeType.getAddressSpace() == LangAS::Default)
9682
9683 if (PointeeType->isPointerType()) {
9684 // This is a pointer to pointer parameter.
9685 // Recursively check inner type.
9686 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
9687 if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9688 ParamKind == InvalidKernelParam)
9689 return ParamKind;
9690
9691 // OpenCL v3.0 s6.11.a:
9692 // A restriction to pass pointers to pointers only applies to OpenCL C
9693 // v1.2 or below.
9695 return ValidKernelParam;
9696
9697 return PtrPtrKernelParam;
9698 }
9699
9700 // C++ for OpenCL v1.0 s2.4:
9701 // Moreover the types used in parameters of the kernel functions must be:
9702 // Standard layout types for pointer parameters. The same applies to
9703 // reference if an implementation supports them in kernel parameters.
9704 if (S.getLangOpts().OpenCLCPlusPlus &&
9706 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts())) {
9707 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9708 bool IsStandardLayoutType = true;
9709 if (CXXRec) {
9710 // If template type is not ODR-used its definition is only available
9711 // in the template definition not its instantiation.
9712 // FIXME: This logic doesn't work for types that depend on template
9713 // parameter (PR58590).
9714 if (!CXXRec->hasDefinition())
9715 CXXRec = CXXRec->getTemplateInstantiationPattern();
9716 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9717 IsStandardLayoutType = false;
9718 }
9719 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9720 !IsStandardLayoutType)
9721 return InvalidKernelParam;
9722 }
9723
9724 // OpenCL v1.2 s6.9.p:
9725 // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9727 return ValidKernelParam;
9728
9729 return PtrKernelParam;
9730 }
9731
9732 // OpenCL v1.2 s6.9.k:
9733 // Arguments to kernel functions in a program cannot be declared with the
9734 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9735 // uintptr_t or a struct and/or union that contain fields declared to be one
9736 // of these built-in scalar types.
9738 return InvalidKernelParam;
9739
9740 if (PT->isImageType())
9741 return PtrKernelParam;
9742
9743 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9744 return InvalidKernelParam;
9745
9746 // OpenCL extension spec v1.2 s9.5:
9747 // This extension adds support for half scalar and vector types as built-in
9748 // types that can be used for arithmetic operations, conversions etc.
9749 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
9750 PT->isHalfType())
9751 return InvalidKernelParam;
9752
9753 // Look into an array argument to check if it has a forbidden type.
9754 if (PT->isArrayType()) {
9755 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9756 // Call ourself to check an underlying type of an array. Since the
9757 // getPointeeOrArrayElementType returns an innermost type which is not an
9758 // array, this recursive call only happens once.
9759 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
9760 }
9761
9762 // C++ for OpenCL v1.0 s2.4:
9763 // Moreover the types used in parameters of the kernel functions must be:
9764 // Trivial and standard-layout types C++17 [basic.types] (plain old data
9765 // types) for parameters passed by value;
9766 if (S.getLangOpts().OpenCLCPlusPlus &&
9768 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9769 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
9770 return InvalidKernelParam;
9771
9772 if (PT->isRecordType())
9773 return RecordKernelParam;
9774
9775 return ValidKernelParam;
9776}
9777
9779 Sema &S,
9780 Declarator &D,
9781 ParmVarDecl *Param,
9782 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9783 QualType PT = Param->getType();
9784
9785 // Cache the valid types we encounter to avoid rechecking structs that are
9786 // used again
9787 if (ValidTypes.count(PT.getTypePtr()))
9788 return;
9789
9790 switch (getOpenCLKernelParameterType(S, PT)) {
9791 case PtrPtrKernelParam:
9792 // OpenCL v3.0 s6.11.a:
9793 // A kernel function argument cannot be declared as a pointer to a pointer
9794 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9795 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9796 D.setInvalidType();
9797 return;
9798
9800 // OpenCL v1.0 s6.5:
9801 // __kernel function arguments declared to be a pointer of a type can point
9802 // to one of the following address spaces only : __global, __local or
9803 // __constant.
9804 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9805 D.setInvalidType();
9806 return;
9807
9808 // OpenCL v1.2 s6.9.k:
9809 // Arguments to kernel functions in a program cannot be declared with the
9810 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9811 // uintptr_t or a struct and/or union that contain fields declared to be
9812 // one of these built-in scalar types.
9813
9814 case InvalidKernelParam:
9815 // OpenCL v1.2 s6.8 n:
9816 // A kernel function argument cannot be declared
9817 // of event_t type.
9818 // Do not diagnose half type since it is diagnosed as invalid argument
9819 // type for any function elsewhere.
9820 if (!PT->isHalfType()) {
9821 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9822
9823 // Explain what typedefs are involved.
9824 const TypedefType *Typedef = nullptr;
9825 while ((Typedef = PT->getAs<TypedefType>())) {
9826 SourceLocation Loc = Typedef->getDecl()->getLocation();
9827 // SourceLocation may be invalid for a built-in type.
9828 if (Loc.isValid())
9829 S.Diag(Loc, diag::note_entity_declared_at) << PT;
9830 PT = Typedef->desugar();
9831 }
9832 }
9833
9834 D.setInvalidType();
9835 return;
9836
9837 case PtrKernelParam:
9838 case ValidKernelParam:
9839 ValidTypes.insert(PT.getTypePtr());
9840 return;
9841
9842 case RecordKernelParam:
9843 break;
9844 }
9845
9846 // Track nested structs we will inspect
9848
9849 // Track where we are in the nested structs. Items will migrate from
9850 // VisitStack to HistoryStack as we do the DFS for bad field.
9852 HistoryStack.push_back(nullptr);
9853
9854 // At this point we already handled everything except of a RecordType.
9855 assert(PT->isRecordType() && "Unexpected type.");
9856 const auto *PD = PT->castAsRecordDecl();
9857 VisitStack.push_back(PD);
9858 assert(VisitStack.back() && "First decl null?");
9859
9860 do {
9861 const Decl *Next = VisitStack.pop_back_val();
9862 if (!Next) {
9863 assert(!HistoryStack.empty());
9864 // Found a marker, we have gone up a level
9865 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9866 ValidTypes.insert(Hist->getType().getTypePtr());
9867
9868 continue;
9869 }
9870
9871 // Adds everything except the original parameter declaration (which is not a
9872 // field itself) to the history stack.
9873 const RecordDecl *RD;
9874 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9875 HistoryStack.push_back(Field);
9876
9877 QualType FieldTy = Field->getType();
9878 // Other field types (known to be valid or invalid) are handled while we
9879 // walk around RecordDecl::fields().
9880 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9881 "Unexpected type.");
9882 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9883
9884 RD = FieldRecTy->castAsRecordDecl();
9885 } else {
9886 RD = cast<RecordDecl>(Next);
9887 }
9888
9889 // Add a null marker so we know when we've gone back up a level
9890 VisitStack.push_back(nullptr);
9891
9892 for (const auto *FD : RD->fields()) {
9893 QualType QT = FD->getType();
9894
9895 if (ValidTypes.count(QT.getTypePtr()))
9896 continue;
9897
9899 if (ParamType == ValidKernelParam)
9900 continue;
9901
9902 if (ParamType == RecordKernelParam) {
9903 VisitStack.push_back(FD);
9904 continue;
9905 }
9906
9907 // OpenCL v1.2 s6.9.p:
9908 // Arguments to kernel functions that are declared to be a struct or union
9909 // do not allow OpenCL objects to be passed as elements of the struct or
9910 // union. This restriction was lifted in OpenCL v2.0 with the introduction
9911 // of SVM.
9912 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9913 ParamType == InvalidAddrSpacePtrKernelParam) {
9914 S.Diag(Param->getLocation(),
9915 diag::err_record_with_pointers_kernel_param)
9916 << PT->isUnionType()
9917 << PT;
9918 } else {
9919 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9920 }
9921
9922 S.Diag(PD->getLocation(), diag::note_within_field_of_type)
9923 << PD->getDeclName();
9924
9925 // We have an error, now let's go back up through history and show where
9926 // the offending field came from
9928 I = HistoryStack.begin() + 1,
9929 E = HistoryStack.end();
9930 I != E; ++I) {
9931 const FieldDecl *OuterField = *I;
9932 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9933 << OuterField->getType();
9934 }
9935
9936 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9937 << QT->isPointerType()
9938 << QT;
9939 D.setInvalidType();
9940 return;
9941 }
9942 } while (!VisitStack.empty());
9943}
9944
9945/// Find the DeclContext in which a tag is implicitly declared if we see an
9946/// elaborated type specifier in the specified context, and lookup finds
9947/// nothing.
9949 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9950 DC = DC->getParent();
9951 return DC;
9952}
9953
9954/// Find the Scope in which a tag is implicitly declared if we see an
9955/// elaborated type specifier in the specified context, and lookup finds
9956/// nothing.
9957static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9958 while (S->isClassScope() ||
9959 (LangOpts.CPlusPlus &&
9961 ((S->getFlags() & Scope::DeclScope) == 0) ||
9962 (S->getEntity() && S->getEntity()->isTransparentContext()))
9963 S = S->getParent();
9964 return S;
9965}
9966
9967/// Determine whether a declaration matches a known function in namespace std.
9969 unsigned BuiltinID) {
9970 switch (BuiltinID) {
9971 case Builtin::BI__GetExceptionInfo:
9972 // No type checking whatsoever.
9973 return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
9974
9975 case Builtin::BIaddressof:
9976 case Builtin::BI__addressof:
9977 case Builtin::BIforward:
9978 case Builtin::BIforward_like:
9979 case Builtin::BImove:
9980 case Builtin::BImove_if_noexcept:
9981 case Builtin::BIas_const: {
9982 // Ensure that we don't treat the algorithm
9983 // OutputIt std::move(InputIt, InputIt, OutputIt)
9984 // as the builtin std::move.
9985 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9986 return FPT->getNumParams() == 1 && !FPT->isVariadic();
9987 }
9988
9989 default:
9990 return false;
9991 }
9992}
9993
9994NamedDecl*
9997 MultiTemplateParamsArg TemplateParamListsRef,
9998 bool &AddToScope) {
9999 QualType R = TInfo->getType();
10000
10001 assert(R->isFunctionType());
10003 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
10004
10005 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
10006 llvm::append_range(TemplateParamLists, TemplateParamListsRef);
10008 if (!TemplateParamLists.empty() && !TemplateParamLists.back()->empty() &&
10009 Invented->getDepth() == TemplateParamLists.back()->getDepth())
10010 TemplateParamLists.back() = Invented;
10011 else
10012 TemplateParamLists.push_back(Invented);
10013 }
10014
10015 // TODO: consider using NameInfo for diagnostic.
10017 DeclarationName Name = NameInfo.getName();
10019
10022 diag::err_invalid_thread)
10024
10029
10030 bool isFriend = false;
10032 bool isMemberSpecialization = false;
10033 bool isFunctionTemplateSpecialization = false;
10034
10035 bool HasExplicitTemplateArgs = false;
10036 TemplateArgumentListInfo TemplateArgs;
10037
10038 bool isVirtualOkay = false;
10039
10040 DeclContext *OriginalDC = DC;
10041 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
10042
10043 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
10044 isVirtualOkay);
10045 if (!NewFD) return nullptr;
10046
10047 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
10049
10050 // Set the lexical context. If this is a function-scope declaration, or has a
10051 // C++ scope specifier, or is the object of a friend declaration, the lexical
10052 // context will be different from the semantic context.
10054
10055 if (IsLocalExternDecl)
10056 NewFD->setLocalExternDecl();
10057
10058 if (getLangOpts().CPlusPlus) {
10059 // The rules for implicit inlines changed in C++20 for methods and friends
10060 // with an in-class definition (when such a definition is not attached to
10061 // the global module). This does not affect declarations that are already
10062 // inline (whether explicitly or implicitly by being declared constexpr,
10063 // consteval, etc).
10064 // FIXME: We need a better way to separate C++ standard and clang modules.
10065 bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
10066 !NewFD->getOwningModule() ||
10067 NewFD->isFromGlobalModule() ||
10069 bool isInline = D.getDeclSpec().isInlineSpecified();
10070 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10071 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
10072 isFriend = D.getDeclSpec().isFriendSpecified();
10073 if (ImplicitInlineCXX20 && isFriend && D.isFunctionDefinition()) {
10074 // Pre-C++20 [class.friend]p5
10075 // A function can be defined in a friend declaration of a
10076 // class . . . . Such a function is implicitly inline.
10077 // Post C++20 [class.friend]p7
10078 // Such a function is implicitly an inline function if it is attached
10079 // to the global module.
10080 NewFD->setImplicitlyInline();
10081 }
10082
10083 // If this is a method defined in an __interface, and is not a constructor
10084 // or an overloaded operator, then set the pure flag (isVirtual will already
10085 // return true).
10086 if (const CXXRecordDecl *Parent =
10087 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
10088 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
10089 NewFD->setIsPureVirtual(true);
10090
10091 // C++ [class.union]p2
10092 // A union can have member functions, but not virtual functions.
10093 if (isVirtual && Parent->isUnion()) {
10094 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
10095 NewFD->setInvalidDecl();
10096 }
10097 if ((Parent->isClass() || Parent->isStruct()) &&
10098 Parent->hasAttr<SYCLSpecialClassAttr>() &&
10099 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
10100 NewFD->getName() == "__init" && D.isFunctionDefinition()) {
10101 if (auto *Def = Parent->getDefinition())
10102 Def->setInitMethod(true);
10103 }
10104 }
10105
10106 SetNestedNameSpecifier(*this, NewFD, D);
10107 isMemberSpecialization = false;
10108 isFunctionTemplateSpecialization = false;
10109 if (D.isInvalidType())
10110 NewFD->setInvalidDecl();
10111
10112 // Match up the template parameter lists with the scope specifier, then
10113 // determine whether we have a template or a template specialization.
10114 bool Invalid = false;
10115 TemplateIdAnnotation *TemplateId =
10117 ? D.getName().TemplateId
10118 : nullptr;
10119 TemplateParameterList *TemplateParams =
10122 D.getCXXScopeSpec(), TemplateId, TemplateParamLists, isFriend,
10123 isMemberSpecialization, Invalid);
10124 if (TemplateParams) {
10125 // Check that we can declare a template here.
10126 if (CheckTemplateDeclScope(S, TemplateParams))
10127 NewFD->setInvalidDecl();
10128
10129 if (TemplateParams->size() > 0) {
10130 // This is a function template
10131
10132 // A destructor cannot be a template.
10134 Diag(NewFD->getLocation(), diag::err_destructor_template);
10135 NewFD->setInvalidDecl();
10136 // Function template with explicit template arguments.
10137 } else if (TemplateId) {
10138 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
10139 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
10140 NewFD->setInvalidDecl();
10141 }
10142
10143 // If we're adding a template to a dependent context, we may need to
10144 // rebuilding some of the types used within the template parameter list,
10145 // now that we know what the current instantiation is.
10146 if (DC->isDependentContext()) {
10147 ContextRAII SavedContext(*this, DC);
10149 Invalid = true;
10150 }
10151
10153 NewFD->getLocation(),
10154 Name, TemplateParams,
10155 NewFD);
10156 FunctionTemplate->setLexicalDeclContext(CurContext);
10158
10159 // For source fidelity, store the other template param lists.
10160 if (TemplateParamLists.size() > 1) {
10162 ArrayRef<TemplateParameterList *>(TemplateParamLists)
10163 .drop_back(1));
10164 }
10165 } else {
10166 // This is a function template specialization.
10167 isFunctionTemplateSpecialization = true;
10168 // For source fidelity, store all the template param lists.
10169 if (TemplateParamLists.size() > 0)
10170 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
10171
10172 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
10173 if (isFriend) {
10174 // We want to remove the "template<>", found here.
10175 SourceRange RemoveRange = TemplateParams->getSourceRange();
10176
10177 // If we remove the template<> and the name is not a
10178 // template-id, we're actually silently creating a problem:
10179 // the friend declaration will refer to an untemplated decl,
10180 // and clearly the user wants a template specialization. So
10181 // we need to insert '<>' after the name.
10182 SourceLocation InsertLoc;
10184 InsertLoc = D.getName().getSourceRange().getEnd();
10185 InsertLoc = getLocForEndOfToken(InsertLoc);
10186 }
10187
10188 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
10189 << Name << RemoveRange
10190 << FixItHint::CreateRemoval(RemoveRange)
10191 << FixItHint::CreateInsertion(InsertLoc, "<>");
10192 Invalid = true;
10193
10194 // Recover by faking up an empty template argument list.
10195 HasExplicitTemplateArgs = true;
10196 TemplateArgs.setLAngleLoc(InsertLoc);
10197 TemplateArgs.setRAngleLoc(InsertLoc);
10198 }
10199 }
10200 } else {
10201 // Check that we can declare a template here.
10202 if (!TemplateParamLists.empty() && isMemberSpecialization &&
10203 CheckTemplateDeclScope(S, TemplateParamLists.back()))
10204 NewFD->setInvalidDecl();
10205
10206 // All template param lists were matched against the scope specifier:
10207 // this is NOT (an explicit specialization of) a template.
10208 if (TemplateParamLists.size() > 0)
10209 // For source fidelity, store all the template param lists.
10210 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
10211
10212 // "friend void foo<>(int);" is an implicit specialization decl.
10213 if (isFriend && TemplateId)
10214 isFunctionTemplateSpecialization = true;
10215 }
10216
10217 // If this is a function template specialization and the unqualified-id of
10218 // the declarator-id is a template-id, convert the template argument list
10219 // into our AST format and check for unexpanded packs.
10220 if (isFunctionTemplateSpecialization && TemplateId) {
10221 HasExplicitTemplateArgs = true;
10222
10223 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
10224 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
10225 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
10226 TemplateId->NumArgs);
10227 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
10228
10229 // FIXME: Should we check for unexpanded packs if this was an (invalid)
10230 // declaration of a function template partial specialization? Should we
10231 // consider the unexpanded pack context to be a partial specialization?
10232 for (const TemplateArgumentLoc &ArgLoc : TemplateArgs.arguments()) {
10234 ArgLoc, isFriend ? UPPC_FriendDeclaration
10236 NewFD->setInvalidDecl();
10237 }
10238 }
10239
10240 if (Invalid) {
10241 NewFD->setInvalidDecl();
10242 if (FunctionTemplate)
10243 FunctionTemplate->setInvalidDecl();
10244 }
10245
10246 // C++ [dcl.fct.spec]p5:
10247 // The virtual specifier shall only be used in declarations of
10248 // nonstatic class member functions that appear within a
10249 // member-specification of a class declaration; see 10.3.
10250 //
10251 if (isVirtual && !NewFD->isInvalidDecl()) {
10252 if (!isVirtualOkay) {
10254 diag::err_virtual_non_function);
10255 } else if (!CurContext->isRecord()) {
10256 // 'virtual' was specified outside of the class.
10258 diag::err_virtual_out_of_class)
10260 } else if (NewFD->getDescribedFunctionTemplate()) {
10261 // C++ [temp.mem]p3:
10262 // A member function template shall not be virtual.
10264 diag::err_virtual_member_function_template)
10266 } else {
10267 // Okay: Add virtual to the method.
10268 NewFD->setVirtualAsWritten(true);
10269 }
10270
10271 if (getLangOpts().CPlusPlus14 &&
10272 NewFD->getReturnType()->isUndeducedType())
10273 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
10274 }
10275
10276 // C++ [dcl.fct.spec]p3:
10277 // The inline specifier shall not appear on a block scope function
10278 // declaration.
10279 if (isInline && !NewFD->isInvalidDecl()) {
10280 if (CurContext->isFunctionOrMethod()) {
10281 // 'inline' is not allowed on block scope function declaration.
10283 diag::err_inline_declaration_block_scope) << Name
10285 }
10286 }
10287
10288 // C++ [dcl.fct.spec]p6:
10289 // The explicit specifier shall be used only in the declaration of a
10290 // constructor or conversion function within its class definition;
10291 // see 12.3.1 and 12.3.2.
10292 if (hasExplicit && !NewFD->isInvalidDecl() &&
10294 if (!CurContext->isRecord()) {
10295 // 'explicit' was specified outside of the class.
10297 diag::err_explicit_out_of_class)
10299 } else if (!isa<CXXConstructorDecl>(NewFD) &&
10300 !isa<CXXConversionDecl>(NewFD)) {
10301 // 'explicit' was specified on a function that wasn't a constructor
10302 // or conversion function.
10304 diag::err_explicit_non_ctor_or_conv_function)
10306 }
10307 }
10308
10310 if (ConstexprKind != ConstexprSpecKind::Unspecified) {
10311 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
10312 // are implicitly inline.
10313 NewFD->setImplicitlyInline();
10314
10315 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
10316 // be either constructors or to return a literal type. Therefore,
10317 // destructors cannot be declared constexpr.
10318 if (isa<CXXDestructorDecl>(NewFD) &&
10320 ConstexprKind == ConstexprSpecKind::Consteval)) {
10321 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
10322 << static_cast<int>(ConstexprKind);
10326 }
10327 // C++20 [dcl.constexpr]p2: An allocation function, or a
10328 // deallocation function shall not be declared with the consteval
10329 // specifier.
10330 if (ConstexprKind == ConstexprSpecKind::Consteval &&
10333 diag::err_invalid_consteval_decl_kind)
10334 << NewFD;
10336 }
10337 }
10338
10339 // If __module_private__ was specified, mark the function accordingly.
10341 if (isFunctionTemplateSpecialization) {
10342 SourceLocation ModulePrivateLoc
10344 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
10345 << 0
10346 << FixItHint::CreateRemoval(ModulePrivateLoc);
10347 } else {
10348 NewFD->setModulePrivate();
10349 if (FunctionTemplate)
10350 FunctionTemplate->setModulePrivate();
10351 }
10352 }
10353
10354 if (isFriend) {
10355 if (FunctionTemplate) {
10356 FunctionTemplate->setObjectOfFriendDecl();
10357 FunctionTemplate->setAccess(AS_public);
10358 }
10359 NewFD->setObjectOfFriendDecl();
10360 NewFD->setAccess(AS_public);
10361 }
10362
10363 // If a function is defined as defaulted or deleted, mark it as such now.
10364 // We'll do the relevant checks on defaulted / deleted functions later.
10365 switch (D.getFunctionDefinitionKind()) {
10368 break;
10369
10371 NewFD->setDefaulted();
10372 break;
10373
10375 NewFD->setDeletedAsWritten();
10376 break;
10377 }
10378
10379 if (ImplicitInlineCXX20 && isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
10381 // Pre C++20 [class.mfct]p2:
10382 // A member function may be defined (8.4) in its class definition, in
10383 // which case it is an inline member function (7.1.2)
10384 // Post C++20 [class.mfct]p1:
10385 // If a member function is attached to the global module and is defined
10386 // in its class definition, it is inline.
10387 NewFD->setImplicitlyInline();
10388 }
10389
10390 if (!isFriend && SC != SC_None) {
10391 // C++ [temp.expl.spec]p2:
10392 // The declaration in an explicit-specialization shall not be an
10393 // export-declaration. An explicit specialization shall not use a
10394 // storage-class-specifier other than thread_local.
10395 //
10396 // We diagnose friend declarations with storage-class-specifiers
10397 // elsewhere.
10398 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10400 diag::ext_explicit_specialization_storage_class)
10403 }
10404
10405 if (SC == SC_Static && !CurContext->isRecord() && DC->isRecord()) {
10406 assert(isa<CXXMethodDecl>(NewFD) &&
10407 "Out-of-line member function should be a CXXMethodDecl");
10408 // C++ [class.static]p1:
10409 // A data or function member of a class may be declared static
10410 // in a class definition, in which case it is a static member of
10411 // the class.
10412
10413 // Complain about the 'static' specifier if it's on an out-of-line
10414 // member function definition.
10415
10416 // MSVC permits the use of a 'static' storage specifier on an
10417 // out-of-line member function template declaration and class member
10418 // template declaration (MSVC versions before 2015), warn about this.
10420 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
10421 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
10422 (getLangOpts().MSVCCompat &&
10424 ? diag::ext_static_out_of_line
10425 : diag::err_static_out_of_line)
10428 }
10429 }
10430
10431 // C++11 [except.spec]p15:
10432 // A deallocation function with no exception-specification is treated
10433 // as if it were specified with noexcept(true).
10434 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10435 if (Name.isAnyOperatorDelete() && getLangOpts().CPlusPlus11 && FPT &&
10436 !FPT->hasExceptionSpec())
10437 NewFD->setType(Context.getFunctionType(
10438 FPT->getReturnType(), FPT->getParamTypes(),
10440
10441 // C++20 [dcl.inline]/7
10442 // If an inline function or variable that is attached to a named module
10443 // is declared in a definition domain, it shall be defined in that
10444 // domain.
10445 // So, if the current declaration does not have a definition, we must
10446 // check at the end of the TU (or when the PMF starts) to see that we
10447 // have a definition at that point.
10448 if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
10449 NewFD->isInNamedModule()) {
10450 PendingInlineFuncDecls.insert(NewFD);
10451 }
10452 }
10453
10454 // Filter out previous declarations that don't match the scope.
10457 isMemberSpecialization ||
10458 isFunctionTemplateSpecialization);
10459
10460 // Handle GNU asm-label extension (encoded as an attribute).
10461 if (Expr *E = D.getAsmLabel()) {
10462 // The parser guarantees this is a string.
10464 NewFD->addAttr(
10465 AsmLabelAttr::Create(Context, SE->getString(), SE->getStrTokenLoc(0)));
10466 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10467 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
10469 if (I != ExtnameUndeclaredIdentifiers.end()) {
10470 if (isDeclExternC(NewFD)) {
10471 NewFD->addAttr(I->second);
10473 } else
10474 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
10475 << /*Variable*/0 << NewFD;
10476 }
10477 }
10478
10479 // Copy the parameter declarations from the declarator D to the function
10480 // declaration NewFD, if they are available. First scavenge them into Params.
10482 unsigned FTIIdx;
10483 if (D.isFunctionDeclarator(FTIIdx)) {
10485
10486 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10487 // function that takes no arguments, not a function that takes a
10488 // single void argument.
10489 // We let through "const void" here because Sema::GetTypeForDeclarator
10490 // already checks for that case.
10491 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10492 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10493 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
10494 assert(Param->getDeclContext() != NewFD && "Was set before ?");
10495 Param->setDeclContext(NewFD);
10496 Params.push_back(Param);
10497
10498 if (Param->isInvalidDecl())
10499 NewFD->setInvalidDecl();
10500 }
10501 }
10502
10503 if (!getLangOpts().CPlusPlus) {
10504 // In C, find all the tag declarations from the prototype and move them
10505 // into the function DeclContext. Remove them from the surrounding tag
10506 // injection context of the function, which is typically but not always
10507 // the TU.
10508 DeclContext *PrototypeTagContext =
10510 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10511 auto *TD = dyn_cast<TagDecl>(NonParmDecl);
10512
10513 // We don't want to reparent enumerators. Look at their parent enum
10514 // instead.
10515 if (!TD) {
10516 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
10517 TD = cast<EnumDecl>(ECD->getDeclContext());
10518 }
10519 if (!TD)
10520 continue;
10521 DeclContext *TagDC = TD->getLexicalDeclContext();
10522 if (!TagDC->containsDecl(TD))
10523 continue;
10524 TagDC->removeDecl(TD);
10525 TD->setDeclContext(NewFD);
10526 NewFD->addDecl(TD);
10527
10528 // Preserve the lexical DeclContext if it is not the surrounding tag
10529 // injection context of the FD. In this example, the semantic context of
10530 // E will be f and the lexical context will be S, while both the
10531 // semantic and lexical contexts of S will be f:
10532 // void f(struct S { enum E { a } f; } s);
10533 if (TagDC != PrototypeTagContext)
10534 TD->setLexicalDeclContext(TagDC);
10535 }
10536 }
10537 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10538 // When we're declaring a function with a typedef, typeof, etc as in the
10539 // following example, we'll need to synthesize (unnamed)
10540 // parameters for use in the declaration.
10541 //
10542 // @code
10543 // typedef void fn(int);
10544 // fn f;
10545 // @endcode
10546
10547 // Synthesize a parameter for each argument type.
10548 for (const auto &AI : FT->param_types()) {
10549 ParmVarDecl *Param =
10551 Param->setScopeInfo(0, Params.size());
10552 Params.push_back(Param);
10553 }
10554 } else {
10555 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10556 "Should not need args for typedef of non-prototype fn");
10557 }
10558
10559 // Finally, we know we have the right number of parameters, install them.
10560 NewFD->setParams(Params);
10561
10562 // If this declarator is a declaration and not a definition, its parameters
10563 // will not be pushed onto a scope chain. That means we will not issue any
10564 // reserved identifier warnings for the declaration, but we will for the
10565 // definition. Handle those here.
10566 if (!D.isFunctionDefinition()) {
10567 for (const ParmVarDecl *PVD : Params)
10569 }
10570
10572 NewFD->addAttr(
10573 C11NoReturnAttr::Create(Context, D.getDeclSpec().getNoreturnSpecLoc()));
10574
10575 // Functions returning a variably modified type violate C99 6.7.5.2p2
10576 // because all functions have linkage.
10577 if (!NewFD->isInvalidDecl() &&
10579 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
10580 NewFD->setInvalidDecl();
10581 }
10582
10583 // Apply an implicit SectionAttr if '#pragma clang section text' is active
10585 !NewFD->hasAttr<SectionAttr>())
10586 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
10587 Context, PragmaClangTextSection.SectionName,
10588 PragmaClangTextSection.PragmaLocation));
10589
10590 // Apply an implicit SectionAttr if #pragma code_seg is active.
10591 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10592 !NewFD->hasAttr<SectionAttr>()) {
10593 NewFD->addAttr(SectionAttr::CreateImplicit(
10594 Context, CodeSegStack.CurrentValue->getString(),
10595 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate));
10596 if (UnifySection(CodeSegStack.CurrentValue->getString(),
10599 NewFD))
10600 NewFD->dropAttr<SectionAttr>();
10601 }
10602
10603 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10604 // active.
10605 if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() &&
10606 !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10607 NewFD->addAttr(StrictGuardStackCheckAttr::CreateImplicit(
10608 Context, PragmaClangTextSection.PragmaLocation));
10609
10610 // Apply an implicit CodeSegAttr from class declspec or
10611 // apply an implicit SectionAttr from #pragma code_seg if active.
10612 if (!NewFD->hasAttr<CodeSegAttr>()) {
10614 D.isFunctionDefinition())) {
10615 NewFD->addAttr(SAttr);
10616 }
10617 }
10618
10619 // Handle attributes.
10620 ProcessDeclAttributes(S, NewFD, D);
10621 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10622 if (Context.getTargetInfo().getTriple().isAArch64() && NewTVA &&
10623 !NewTVA->isDefaultVersion() &&
10624 !Context.getTargetInfo().hasFeature("fmv")) {
10625 // Don't add to scope fmv functions declarations if fmv disabled
10626 AddToScope = false;
10627 return NewFD;
10628 }
10629
10630 if (getLangOpts().OpenCL || getLangOpts().HLSL) {
10631 // Neither OpenCL nor HLSL allow an address space qualifyer on a return
10632 // type.
10633 //
10634 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10635 // type declaration will generate a compilation error.
10636 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10637 if (AddressSpace != LangAS::Default) {
10638 Diag(NewFD->getLocation(), diag::err_return_value_with_address_space);
10639 NewFD->setInvalidDecl();
10640 }
10641 }
10642
10643 if (!getLangOpts().CPlusPlus) {
10644 // Perform semantic checking on the function declaration.
10645 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10646 CheckMain(NewFD, D.getDeclSpec());
10647
10648 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10649 CheckMSVCRTEntryPoint(NewFD);
10650
10651 if (!NewFD->isInvalidDecl())
10653 isMemberSpecialization,
10655 else if (!Previous.empty())
10656 // Recover gracefully from an invalid redeclaration.
10657 D.setRedeclaration(true);
10658 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10659 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
10660 "previous declaration set still overloaded");
10661
10662 // Diagnose no-prototype function declarations with calling conventions that
10663 // don't support variadic calls. Only do this in C and do it after merging
10664 // possibly prototyped redeclarations.
10665 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10667 CallingConv CC = FT->getExtInfo().getCC();
10668 if (!supportsVariadicCall(CC)) {
10669 // Windows system headers sometimes accidentally use stdcall without
10670 // (void) parameters, so we relax this to a warning.
10671 int DiagID =
10672 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10673 Diag(NewFD->getLocation(), DiagID)
10675 }
10676 }
10677
10681 NewFD->getReturnType(), NewFD->getReturnTypeSourceRange().getBegin(),
10683 } else {
10684 // C++11 [replacement.functions]p3:
10685 // The program's definitions shall not be specified as inline.
10686 //
10687 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10688 //
10689 // Suppress the diagnostic if the function is __attribute__((used)), since
10690 // that forces an external definition to be emitted.
10691 if (D.getDeclSpec().isInlineSpecified() &&
10693 !NewFD->hasAttr<UsedAttr>())
10695 diag::ext_operator_new_delete_declared_inline)
10696 << NewFD->getDeclName();
10697
10698 if (const Expr *TRC = NewFD->getTrailingRequiresClause().ConstraintExpr) {
10699 // C++20 [dcl.decl.general]p4:
10700 // The optional requires-clause in an init-declarator or
10701 // member-declarator shall be present only if the declarator declares a
10702 // templated function.
10703 //
10704 // C++20 [temp.pre]p8:
10705 // An entity is templated if it is
10706 // - a template,
10707 // - an entity defined or created in a templated entity,
10708 // - a member of a templated entity,
10709 // - an enumerator for an enumeration that is a templated entity, or
10710 // - the closure type of a lambda-expression appearing in the
10711 // declaration of a templated entity.
10712 //
10713 // [Note 6: A local class, a local or block variable, or a friend
10714 // function defined in a templated entity is a templated entity.
10715 // — end note]
10716 //
10717 // A templated function is a function template or a function that is
10718 // templated. A templated class is a class template or a class that is
10719 // templated. A templated variable is a variable template or a variable
10720 // that is templated.
10721 if (!FunctionTemplate) {
10722 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10723 // C++ [temp.expl.spec]p8 (proposed resolution for CWG2847):
10724 // An explicit specialization shall not have a trailing
10725 // requires-clause unless it declares a function template.
10726 //
10727 // Since a friend function template specialization cannot be
10728 // definition, and since a non-template friend declaration with a
10729 // trailing requires-clause must be a definition, we diagnose
10730 // friend function template specializations with trailing
10731 // requires-clauses on the same path as explicit specializations
10732 // even though they aren't necessarily prohibited by the same
10733 // language rule.
10734 Diag(TRC->getBeginLoc(), diag::err_non_temp_spec_requires_clause)
10735 << isFriend;
10736 } else if (isFriend && NewFD->isTemplated() &&
10737 !D.isFunctionDefinition()) {
10738 // C++ [temp.friend]p9:
10739 // A non-template friend declaration with a requires-clause shall be
10740 // a definition.
10741 Diag(NewFD->getBeginLoc(),
10742 diag::err_non_temp_friend_decl_with_requires_clause_must_be_def);
10743 NewFD->setInvalidDecl();
10744 } else if (!NewFD->isTemplated() ||
10745 !(isa<CXXMethodDecl>(NewFD) || D.isFunctionDefinition())) {
10746 Diag(TRC->getBeginLoc(),
10747 diag::err_constrained_non_templated_function);
10748 }
10749 }
10750 }
10751
10752 // We do not add HD attributes to specializations here because
10753 // they may have different constexpr-ness compared to their
10754 // templates and, after maybeAddHostDeviceAttrs() is applied,
10755 // may end up with different effective targets. Instead, a
10756 // specialization inherits its target attributes from its template
10757 // in the CheckFunctionTemplateSpecialization() call below.
10758 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
10760
10761 // Handle explicit specializations of function templates
10762 // and friend function declarations with an explicit
10763 // template argument list.
10764 if (isFunctionTemplateSpecialization) {
10765 bool isDependentSpecialization = false;
10766 if (isFriend) {
10767 // For friend function specializations, this is a dependent
10768 // specialization if its semantic context is dependent, its
10769 // type is dependent, or if its template-id is dependent.
10770 isDependentSpecialization =
10771 DC->isDependentContext() || NewFD->getType()->isDependentType() ||
10772 (HasExplicitTemplateArgs &&
10773 TemplateSpecializationType::
10774 anyInstantiationDependentTemplateArguments(
10775 TemplateArgs.arguments()));
10776 assert((!isDependentSpecialization ||
10777 (HasExplicitTemplateArgs == isDependentSpecialization)) &&
10778 "dependent friend function specialization without template "
10779 "args");
10780 } else {
10781 // For class-scope explicit specializations of function templates,
10782 // if the lexical context is dependent, then the specialization
10783 // is dependent.
10784 isDependentSpecialization =
10785 CurContext->isRecord() && CurContext->isDependentContext();
10786 }
10787
10788 TemplateArgumentListInfo *ExplicitTemplateArgs =
10789 HasExplicitTemplateArgs ? &TemplateArgs : nullptr;
10790 if (isDependentSpecialization) {
10791 // If it's a dependent specialization, it may not be possible
10792 // to determine the primary template (for explicit specializations)
10793 // or befriended declaration (for friends) until the enclosing
10794 // template is instantiated. In such cases, we store the declarations
10795 // found by name lookup and defer resolution until instantiation.
10797 NewFD, ExplicitTemplateArgs, Previous))
10798 NewFD->setInvalidDecl();
10799 } else if (!NewFD->isInvalidDecl()) {
10800 if (CheckFunctionTemplateSpecialization(NewFD, ExplicitTemplateArgs,
10801 Previous))
10802 NewFD->setInvalidDecl();
10803 }
10804 } else if (isMemberSpecialization && !FunctionTemplate) {
10806 NewFD->setInvalidDecl();
10807 }
10808
10809 // Perform semantic checking on the function declaration.
10810 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10811 CheckMain(NewFD, D.getDeclSpec());
10812
10813 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10814 CheckMSVCRTEntryPoint(NewFD);
10815
10816 if (!NewFD->isInvalidDecl())
10818 isMemberSpecialization,
10820 else if (!Previous.empty())
10821 // Recover gracefully from an invalid redeclaration.
10822 D.setRedeclaration(true);
10823
10824 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
10825 !D.isRedeclaration() ||
10826 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
10827 "previous declaration set still overloaded");
10828
10829 NamedDecl *PrincipalDecl = (FunctionTemplate
10831 : NewFD);
10832
10833 if (isFriend && NewFD->getPreviousDecl()) {
10834 AccessSpecifier Access = AS_public;
10835 if (!NewFD->isInvalidDecl())
10836 Access = NewFD->getPreviousDecl()->getAccess();
10837
10838 NewFD->setAccess(Access);
10839 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10840 }
10841
10842 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10844 PrincipalDecl->setNonMemberOperator();
10845
10846 // If we have a function template, check the template parameter
10847 // list. This will check and merge default template arguments.
10848 if (FunctionTemplate) {
10849 FunctionTemplateDecl *PrevTemplate =
10850 FunctionTemplate->getPreviousDecl();
10851 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
10852 PrevTemplate ? PrevTemplate->getTemplateParameters()
10853 : nullptr,
10858 : (D.getCXXScopeSpec().isSet() &&
10859 DC && DC->isRecord() &&
10860 DC->isDependentContext())
10863 }
10864
10865 if (NewFD->isInvalidDecl()) {
10866 // Ignore all the rest of this.
10867 } else if (!D.isRedeclaration()) {
10868 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
10869 AddToScope };
10870 // Fake up an access specifier if it's supposed to be a class member.
10871 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10872 NewFD->setAccess(AS_public);
10873
10874 // Qualified decls generally require a previous declaration.
10875 if (D.getCXXScopeSpec().isSet()) {
10876 // ...with the major exception of templated-scope or
10877 // dependent-scope friend declarations.
10878
10879 // TODO: we currently also suppress this check in dependent
10880 // contexts because (1) the parameter depth will be off when
10881 // matching friend templates and (2) we might actually be
10882 // selecting a friend based on a dependent factor. But there
10883 // are situations where these conditions don't apply and we
10884 // can actually do this check immediately.
10885 //
10886 // Unless the scope is dependent, it's always an error if qualified
10887 // redeclaration lookup found nothing at all. Diagnose that now;
10888 // nothing will diagnose that error later.
10889 if (isFriend &&
10891 (!Previous.empty() && CurContext->isDependentContext()))) {
10892 // ignore these
10893 } else if (NewFD->isCPUDispatchMultiVersion() ||
10894 NewFD->isCPUSpecificMultiVersion()) {
10895 // ignore this, we allow the redeclaration behavior here to create new
10896 // versions of the function.
10897 } else {
10898 // The user tried to provide an out-of-line definition for a
10899 // function that is a member of a class or namespace, but there
10900 // was no such member function declared (C++ [class.mfct]p2,
10901 // C++ [namespace.memdef]p2). For example:
10902 //
10903 // class X {
10904 // void f() const;
10905 // };
10906 //
10907 // void X::f() { } // ill-formed
10908 //
10909 // Complain about this problem, and attempt to suggest close
10910 // matches (e.g., those that differ only in cv-qualifiers and
10911 // whether the parameter types are references).
10912
10914 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
10915 AddToScope = ExtraArgs.AddToScope;
10916 return Result;
10917 }
10918 }
10919
10920 // Unqualified local friend declarations are required to resolve
10921 // to something.
10922 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
10924 *this, Previous, NewFD, ExtraArgs, true, S)) {
10925 AddToScope = ExtraArgs.AddToScope;
10926 return Result;
10927 }
10928 }
10929 } else if (!D.isFunctionDefinition() &&
10930 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
10931 !isFriend && !isFunctionTemplateSpecialization &&
10932 !isMemberSpecialization) {
10933 // An out-of-line member function declaration must also be a
10934 // definition (C++ [class.mfct]p2).
10935 // Note that this is not the case for explicit specializations of
10936 // function templates or member functions of class templates, per
10937 // C++ [temp.expl.spec]p2. We also allow these declarations as an
10938 // extension for compatibility with old SWIG code which likes to
10939 // generate them.
10940 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
10941 << D.getCXXScopeSpec().getRange();
10942 }
10943 }
10944
10945 if (getLangOpts().HLSL && D.isFunctionDefinition()) {
10946 // Any top level function could potentially be specified as an entry.
10947 if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier())
10948 HLSL().ActOnTopLevelFunction(NewFD);
10949
10950 if (NewFD->hasAttr<HLSLShaderAttr>())
10951 HLSL().CheckEntryPoint(NewFD);
10952 }
10953
10954 // If this is the first declaration of a library builtin function, add
10955 // attributes as appropriate.
10956 if (!D.isRedeclaration()) {
10957 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
10958 if (unsigned BuiltinID = II->getBuiltinID()) {
10959 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);
10960 if (!InStdNamespace &&
10962 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
10963 // Validate the type matches unless this builtin is specified as
10964 // matching regardless of its declared type.
10965 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
10966 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10967 } else {
10969 LookupNecessaryTypesForBuiltin(S, BuiltinID);
10970 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
10971
10972 if (!Error && !BuiltinType.isNull() &&
10973 Context.hasSameFunctionTypeIgnoringExceptionSpec(
10974 NewFD->getType(), BuiltinType))
10975 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10976 }
10977 }
10978 } else if (InStdNamespace && NewFD->isInStdNamespace() &&
10979 isStdBuiltin(Context, NewFD, BuiltinID)) {
10980 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10981 }
10982 }
10983 }
10984 }
10985
10986 ProcessPragmaWeak(S, NewFD);
10987 checkAttributesAfterMerging(*this, *NewFD);
10988
10990
10991 if (NewFD->hasAttr<OverloadableAttr>() &&
10992 !NewFD->getType()->getAs<FunctionProtoType>()) {
10993 Diag(NewFD->getLocation(),
10994 diag::err_attribute_overloadable_no_prototype)
10995 << NewFD;
10996 NewFD->dropAttr<OverloadableAttr>();
10997 }
10998
10999 // If there's a #pragma GCC visibility in scope, and this isn't a class
11000 // member, set the visibility of this function.
11001 if (!DC->isRecord() && NewFD->isExternallyVisible())
11003
11004 // If there's a #pragma clang arc_cf_code_audited in scope, consider
11005 // marking the function.
11006 ObjC().AddCFAuditedAttribute(NewFD);
11007
11008 // If this is a function definition, check if we have to apply any
11009 // attributes (i.e. optnone and no_builtin) due to a pragma.
11010 if (D.isFunctionDefinition()) {
11011 AddRangeBasedOptnone(NewFD);
11013 AddSectionMSAllocText(NewFD);
11015 }
11016
11017 // If this is the first declaration of an extern C variable, update
11018 // the map of such variables.
11019 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
11020 isIncompleteDeclExternC(*this, NewFD))
11022
11023 // Set this FunctionDecl's range up to the right paren.
11024 NewFD->setRangeEnd(D.getSourceRange().getEnd());
11025
11026 if (D.isRedeclaration() && !Previous.empty()) {
11027 NamedDecl *Prev = Previous.getRepresentativeDecl();
11028 checkDLLAttributeRedeclaration(*this, Prev, NewFD,
11029 isMemberSpecialization ||
11030 isFunctionTemplateSpecialization,
11032 }
11033
11034 if (getLangOpts().CUDA) {
11035 IdentifierInfo *II = NewFD->getIdentifier();
11036 if (II && II->isStr(CUDA().getConfigureFuncName()) &&
11037 !NewFD->isInvalidDecl() &&
11040 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
11042 Context.setcudaConfigureCallDecl(NewFD);
11043 }
11044
11045 // Variadic functions, other than a *declaration* of printf, are not allowed
11046 // in device-side CUDA code, unless someone passed
11047 // -fcuda-allow-variadic-functions.
11048 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
11049 (NewFD->hasAttr<CUDADeviceAttr>() ||
11050 NewFD->hasAttr<CUDAGlobalAttr>()) &&
11051 !(II && II->isStr("printf") && NewFD->isExternC() &&
11052 !D.isFunctionDefinition())) {
11053 Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
11054 }
11055 }
11056
11058
11059 if (getLangOpts().OpenCL && NewFD->hasAttr<DeviceKernelAttr>()) {
11060 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
11061 if (SC == SC_Static) {
11062 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
11063 D.setInvalidType();
11064 }
11065
11066 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
11067 if (!NewFD->getReturnType()->isVoidType()) {
11068 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
11069 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
11070 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
11071 : FixItHint());
11072 D.setInvalidType();
11073 }
11074
11076 for (auto *Param : NewFD->parameters())
11077 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
11078
11079 if (getLangOpts().OpenCLCPlusPlus) {
11080 if (DC->isRecord()) {
11081 Diag(D.getIdentifierLoc(), diag::err_method_kernel);
11082 D.setInvalidType();
11083 }
11084 if (FunctionTemplate) {
11085 Diag(D.getIdentifierLoc(), diag::err_template_kernel);
11086 D.setInvalidType();
11087 }
11088 }
11089 }
11090
11091 if (getLangOpts().CPlusPlus) {
11092 // Precalculate whether this is a friend function template with a constraint
11093 // that depends on an enclosing template, per [temp.friend]p9.
11094 if (isFriend && FunctionTemplate &&
11097
11098 // C++ [temp.friend]p9:
11099 // A friend function template with a constraint that depends on a
11100 // template parameter from an enclosing template shall be a definition.
11101 if (!D.isFunctionDefinition()) {
11102 Diag(NewFD->getBeginLoc(),
11103 diag::err_friend_decl_with_enclosing_temp_constraint_must_be_def);
11104 NewFD->setInvalidDecl();
11105 }
11106 }
11107
11108 if (FunctionTemplate) {
11109 if (NewFD->isInvalidDecl())
11110 FunctionTemplate->setInvalidDecl();
11111 return FunctionTemplate;
11112 }
11113
11114 if (isMemberSpecialization && !NewFD->isInvalidDecl())
11116 }
11117
11118 for (const ParmVarDecl *Param : NewFD->parameters()) {
11119 QualType PT = Param->getType();
11120
11121 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
11122 // types.
11123 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
11124 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
11125 QualType ElemTy = PipeTy->getElementType();
11126 if (ElemTy->isPointerOrReferenceType()) {
11127 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type);
11128 D.setInvalidType();
11129 }
11130 }
11131 }
11132 // WebAssembly tables can't be used as function parameters.
11133 if (Context.getTargetInfo().getTriple().isWasm()) {
11135 Diag(Param->getTypeSpecStartLoc(),
11136 diag::err_wasm_table_as_function_parameter);
11137 D.setInvalidType();
11138 }
11139 }
11140 }
11141
11142 // Diagnose availability attributes. Availability cannot be used on functions
11143 // that are run during load/unload.
11144 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
11145 if (NewFD->hasAttr<ConstructorAttr>()) {
11146 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
11147 << 1;
11148 NewFD->dropAttr<AvailabilityAttr>();
11149 }
11150 if (NewFD->hasAttr<DestructorAttr>()) {
11151 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
11152 << 2;
11153 NewFD->dropAttr<AvailabilityAttr>();
11154 }
11155 }
11156
11157 // Diagnose no_builtin attribute on function declaration that are not a
11158 // definition.
11159 // FIXME: We should really be doing this in
11160 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
11161 // the FunctionDecl and at this point of the code
11162 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
11163 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11164 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
11165 switch (D.getFunctionDefinitionKind()) {
11168 Diag(NBA->getLocation(),
11169 diag::err_attribute_no_builtin_on_defaulted_deleted_function)
11170 << NBA->getSpelling();
11171 break;
11173 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
11174 << NBA->getSpelling();
11175 break;
11177 break;
11178 }
11179
11180 // Similar to no_builtin logic above, at this point of the code
11181 // FunctionDecl::isThisDeclarationADefinition() always returns `false`
11182 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11183 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
11184 !NewFD->isInvalidDecl() &&
11186 ExternalDeclarations.push_back(NewFD);
11187
11188 // Used for a warning on the 'next' declaration when used with a
11189 // `routine(name)`.
11190 if (getLangOpts().OpenACC)
11192
11193 return NewFD;
11194}
11195
11196/// Return a CodeSegAttr from a containing class. The Microsoft docs say
11197/// when __declspec(code_seg) "is applied to a class, all member functions of
11198/// the class and nested classes -- this includes compiler-generated special
11199/// member functions -- are put in the specified segment."
11200/// The actual behavior is a little more complicated. The Microsoft compiler
11201/// won't check outer classes if there is an active value from #pragma code_seg.
11202/// The CodeSeg is always applied from the direct parent but only from outer
11203/// classes when the #pragma code_seg stack is empty. See:
11204/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
11205/// available since MS has removed the page.
11207 const auto *Method = dyn_cast<CXXMethodDecl>(FD);
11208 if (!Method)
11209 return nullptr;
11210 const CXXRecordDecl *Parent = Method->getParent();
11211 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11212 Attr *NewAttr = SAttr->clone(S.getASTContext());
11213 NewAttr->setImplicit(true);
11214 return NewAttr;
11215 }
11216
11217 // The Microsoft compiler won't check outer classes for the CodeSeg
11218 // when the #pragma code_seg stack is active.
11219 if (S.CodeSegStack.CurrentValue)
11220 return nullptr;
11221
11222 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
11223 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11224 Attr *NewAttr = SAttr->clone(S.getASTContext());
11225 NewAttr->setImplicit(true);
11226 return NewAttr;
11227 }
11228 }
11229 return nullptr;
11230}
11231
11233 bool IsDefinition) {
11234 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
11235 return A;
11236 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
11237 CodeSegStack.CurrentValue)
11238 return SectionAttr::CreateImplicit(
11239 getASTContext(), CodeSegStack.CurrentValue->getString(),
11240 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate);
11241 return nullptr;
11242}
11243
11245 QualType NewT, QualType OldT) {
11247 return true;
11248
11249 // For dependently-typed local extern declarations and friends, we can't
11250 // perform a correct type check in general until instantiation:
11251 //
11252 // int f();
11253 // template<typename T> void g() { T f(); }
11254 //
11255 // (valid if g() is only instantiated with T = int).
11256 if (NewT->isDependentType() &&
11257 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
11258 return false;
11259
11260 // Similarly, if the previous declaration was a dependent local extern
11261 // declaration, we don't really know its type yet.
11262 if (OldT->isDependentType() && OldD->isLocalExternDecl())
11263 return false;
11264
11265 return true;
11266}
11267
11270 return true;
11271
11272 // Don't chain dependent friend function definitions until instantiation, to
11273 // permit cases like
11274 //
11275 // void func();
11276 // template<typename T> class C1 { friend void func() {} };
11277 // template<typename T> class C2 { friend void func() {} };
11278 //
11279 // ... which is valid if only one of C1 and C2 is ever instantiated.
11280 //
11281 // FIXME: This need only apply to function definitions. For now, we proxy
11282 // this by checking for a file-scope function. We do not want this to apply
11283 // to friend declarations nominating member functions, because that gets in
11284 // the way of access checks.
11286 return false;
11287
11288 auto *VD = dyn_cast<ValueDecl>(D);
11289 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
11290 return !VD || !PrevVD ||
11291 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
11292 PrevVD->getType());
11293}
11294
11295/// Check the target or target_version attribute of the function for
11296/// MultiVersion validity.
11297///
11298/// Returns true if there was an error, false otherwise.
11299static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
11300 const auto *TA = FD->getAttr<TargetAttr>();
11301 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11302
11303 assert((TA || TVA) && "Expecting target or target_version attribute");
11304
11306 enum ErrType { Feature = 0, Architecture = 1 };
11307
11308 if (TA) {
11309 ParsedTargetAttr ParseInfo =
11310 S.getASTContext().getTargetInfo().parseTargetAttr(TA->getFeaturesStr());
11311 if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(ParseInfo.CPU)) {
11312 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11313 << Architecture << ParseInfo.CPU;
11314 return true;
11315 }
11316 for (const auto &Feat : ParseInfo.Features) {
11317 auto BareFeat = StringRef{Feat}.substr(1);
11318 if (Feat[0] == '-') {
11319 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11320 << Feature << ("no-" + BareFeat).str();
11321 return true;
11322 }
11323
11324 if (!TargetInfo.validateCpuSupports(BareFeat) ||
11325 !TargetInfo.isValidFeatureName(BareFeat) ||
11326 (BareFeat != "default" && TargetInfo.getFMVPriority(BareFeat) == 0)) {
11327 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11328 << Feature << BareFeat;
11329 return true;
11330 }
11331 }
11332 }
11333
11334 if (TVA) {
11336 ParsedTargetAttr ParseInfo;
11337 if (S.getASTContext().getTargetInfo().getTriple().isRISCV()) {
11338 ParseInfo =
11339 S.getASTContext().getTargetInfo().parseTargetAttr(TVA->getName());
11340 for (auto &Feat : ParseInfo.Features)
11341 Feats.push_back(StringRef{Feat}.substr(1));
11342 } else {
11343 assert(S.getASTContext().getTargetInfo().getTriple().isAArch64());
11344 TVA->getFeatures(Feats);
11345 }
11346 for (const auto &Feat : Feats) {
11347 if (!TargetInfo.validateCpuSupports(Feat)) {
11348 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11349 << Feature << Feat;
11350 return true;
11351 }
11352 }
11353 }
11354 return false;
11355}
11356
11357// Provide a white-list of attributes that are allowed to be combined with
11358// multiversion functions.
11360 MultiVersionKind MVKind) {
11361 // Note: this list/diagnosis must match the list in
11362 // checkMultiversionAttributesAllSame.
11363 switch (Kind) {
11364 default:
11365 return false;
11366 case attr::ArmLocallyStreaming:
11367 return MVKind == MultiVersionKind::TargetVersion ||
11369 case attr::Used:
11370 return MVKind == MultiVersionKind::Target;
11371 case attr::NonNull:
11372 case attr::NoThrow:
11373 return true;
11374 }
11375}
11376
11378 const FunctionDecl *FD,
11379 const FunctionDecl *CausedFD,
11380 MultiVersionKind MVKind) {
11381 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
11382 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
11383 << static_cast<unsigned>(MVKind) << A;
11384 if (CausedFD)
11385 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
11386 return true;
11387 };
11388
11389 for (const Attr *A : FD->attrs()) {
11390 switch (A->getKind()) {
11391 case attr::CPUDispatch:
11392 case attr::CPUSpecific:
11393 if (MVKind != MultiVersionKind::CPUDispatch &&
11395 return Diagnose(S, A);
11396 break;
11397 case attr::Target:
11398 if (MVKind != MultiVersionKind::Target)
11399 return Diagnose(S, A);
11400 break;
11401 case attr::TargetVersion:
11402 if (MVKind != MultiVersionKind::TargetVersion &&
11404 return Diagnose(S, A);
11405 break;
11406 case attr::TargetClones:
11407 if (MVKind != MultiVersionKind::TargetClones &&
11409 return Diagnose(S, A);
11410 break;
11411 default:
11412 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
11413 return Diagnose(S, A);
11414 break;
11415 }
11416 }
11417 return false;
11418}
11419
11421 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11422 const PartialDiagnostic &NoProtoDiagID,
11423 const PartialDiagnosticAt &NoteCausedDiagIDAt,
11424 const PartialDiagnosticAt &NoSupportDiagIDAt,
11425 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11426 bool ConstexprSupported, bool CLinkageMayDiffer) {
11427 enum DoesntSupport {
11428 FuncTemplates = 0,
11429 VirtFuncs = 1,
11430 DeducedReturn = 2,
11431 Constructors = 3,
11432 Destructors = 4,
11433 DeletedFuncs = 5,
11434 DefaultedFuncs = 6,
11435 ConstexprFuncs = 7,
11436 ConstevalFuncs = 8,
11437 Lambda = 9,
11438 };
11439 enum Different {
11440 CallingConv = 0,
11441 ReturnType = 1,
11442 ConstexprSpec = 2,
11443 InlineSpec = 3,
11444 Linkage = 4,
11445 LanguageLinkage = 5,
11446 };
11447
11448 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
11449 !OldFD->getType()->getAs<FunctionProtoType>()) {
11450 Diag(OldFD->getLocation(), NoProtoDiagID);
11451 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
11452 return true;
11453 }
11454
11455 if (NoProtoDiagID.getDiagID() != 0 &&
11456 !NewFD->getType()->getAs<FunctionProtoType>())
11457 return Diag(NewFD->getLocation(), NoProtoDiagID);
11458
11459 if (!TemplatesSupported &&
11461 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11462 << FuncTemplates;
11463
11464 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
11465 if (NewCXXFD->isVirtual())
11466 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11467 << VirtFuncs;
11468
11469 if (isa<CXXConstructorDecl>(NewCXXFD))
11470 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11471 << Constructors;
11472
11473 if (isa<CXXDestructorDecl>(NewCXXFD))
11474 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11475 << Destructors;
11476 }
11477
11478 if (NewFD->isDeleted())
11479 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11480 << DeletedFuncs;
11481
11482 if (NewFD->isDefaulted())
11483 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11484 << DefaultedFuncs;
11485
11486 if (!ConstexprSupported && NewFD->isConstexpr())
11487 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11488 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11489
11490 QualType NewQType = Context.getCanonicalType(NewFD->getType());
11491 const auto *NewType = cast<FunctionType>(NewQType);
11492 QualType NewReturnType = NewType->getReturnType();
11493
11494 if (NewReturnType->isUndeducedType())
11495 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11496 << DeducedReturn;
11497
11498 // Ensure the return type is identical.
11499 if (OldFD) {
11500 QualType OldQType = Context.getCanonicalType(OldFD->getType());
11501 const auto *OldType = cast<FunctionType>(OldQType);
11502 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11503 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11504
11505 const auto *OldFPT = OldFD->getType()->getAs<FunctionProtoType>();
11506 const auto *NewFPT = NewFD->getType()->getAs<FunctionProtoType>();
11507
11508 bool ArmStreamingCCMismatched = false;
11509 if (OldFPT && NewFPT) {
11510 unsigned Diff =
11511 OldFPT->getAArch64SMEAttributes() ^ NewFPT->getAArch64SMEAttributes();
11512 // Arm-streaming, arm-streaming-compatible and non-streaming versions
11513 // cannot be mixed.
11516 ArmStreamingCCMismatched = true;
11517 }
11518
11519 if (OldTypeInfo.getCC() != NewTypeInfo.getCC() || ArmStreamingCCMismatched)
11520 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
11521
11522 QualType OldReturnType = OldType->getReturnType();
11523
11524 if (OldReturnType != NewReturnType)
11525 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
11526
11527 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11528 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
11529
11530 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11531 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
11532
11533 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11534 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
11535
11536 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11537 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
11538
11539 if (CheckEquivalentExceptionSpec(OldFPT, OldFD->getLocation(), NewFPT,
11540 NewFD->getLocation()))
11541 return true;
11542 }
11543 return false;
11544}
11545
11547 const FunctionDecl *NewFD,
11548 bool CausesMV,
11549 MultiVersionKind MVKind) {
11551 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
11552 if (OldFD)
11553 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11554 return true;
11555 }
11556
11557 bool IsCPUSpecificCPUDispatchMVKind =
11560
11561 if (CausesMV && OldFD &&
11562 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
11563 return true;
11564
11565 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
11566 return true;
11567
11568 // Only allow transition to MultiVersion if it hasn't been used.
11569 if (OldFD && CausesMV && OldFD->isUsed(false)) {
11570 S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11571 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11572 return true;
11573 }
11574
11576 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
11578 S.PDiag(diag::note_multiversioning_caused_here)),
11580 S.PDiag(diag::err_multiversion_doesnt_support)
11581 << static_cast<unsigned>(MVKind)),
11583 S.PDiag(diag::err_multiversion_diff)),
11584 /*TemplatesSupported=*/false,
11585 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11586 /*CLinkageMayDiffer=*/false);
11587}
11588
11589/// Check the validity of a multiversion function declaration that is the
11590/// first of its kind. Also sets the multiversion'ness' of the function itself.
11591///
11592/// This sets NewFD->isInvalidDecl() to true if there was an error.
11593///
11594/// Returns true if there was an error, false otherwise.
11597 assert(MVKind != MultiVersionKind::None &&
11598 "Function lacks multiversion attribute");
11599 const auto *TA = FD->getAttr<TargetAttr>();
11600 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11601 // The target attribute only causes MV if this declaration is the default,
11602 // otherwise it is treated as a normal function.
11603 if (TA && !TA->isDefaultVersion())
11604 return false;
11605
11606 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11607 FD->setInvalidDecl();
11608 return true;
11609 }
11610
11611 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
11612 FD->setInvalidDecl();
11613 return true;
11614 }
11615
11616 FD->setIsMultiVersion();
11617 return false;
11618}
11619
11621 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11623 return true;
11624 }
11625
11626 return false;
11627}
11628
11630 if (!From->getASTContext().getTargetInfo().getTriple().isAArch64() &&
11631 !From->getASTContext().getTargetInfo().getTriple().isRISCV())
11632 return;
11633
11634 MultiVersionKind MVKindFrom = From->getMultiVersionKind();
11635 MultiVersionKind MVKindTo = To->getMultiVersionKind();
11636
11637 if (MVKindTo == MultiVersionKind::None &&
11638 (MVKindFrom == MultiVersionKind::TargetVersion ||
11639 MVKindFrom == MultiVersionKind::TargetClones))
11640 To->addAttr(TargetVersionAttr::CreateImplicit(
11641 To->getASTContext(), "default", To->getSourceRange()));
11642}
11643
11645 FunctionDecl *NewFD,
11646 bool &Redeclaration,
11647 NamedDecl *&OldDecl,
11649 assert(!OldFD->isMultiVersion() && "Unexpected MultiVersion");
11650
11651 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11652 const auto *OldTA = OldFD->getAttr<TargetAttr>();
11653 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11654 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11655
11656 assert((NewTA || NewTVA) && "Excpecting target or target_version attribute");
11657
11658 // The definitions should be allowed in any order. If we have discovered
11659 // a new target version and the preceeding was the default, then add the
11660 // corresponding attribute to it.
11661 patchDefaultTargetVersion(NewFD, OldFD);
11662
11663 // If the old decl is NOT MultiVersioned yet, and we don't cause that
11664 // to change, this is a simple redeclaration.
11665 if (NewTA && !NewTA->isDefaultVersion() &&
11666 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
11667 return false;
11668
11669 // Otherwise, this decl causes MultiVersioning.
11670 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
11673 NewFD->setInvalidDecl();
11674 return true;
11675 }
11676
11677 if (CheckMultiVersionValue(S, NewFD)) {
11678 NewFD->setInvalidDecl();
11679 return true;
11680 }
11681
11682 // If this is 'default', permit the forward declaration.
11683 if ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
11684 (NewTVA && NewTVA->isDefaultVersion() && !OldTVA)) {
11685 Redeclaration = true;
11686 OldDecl = OldFD;
11687 OldFD->setIsMultiVersion();
11688 NewFD->setIsMultiVersion();
11689 return false;
11690 }
11691
11692 if ((OldTA || OldTVA) && CheckMultiVersionValue(S, OldFD)) {
11693 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11694 NewFD->setInvalidDecl();
11695 return true;
11696 }
11697
11698 if (NewTA) {
11699 ParsedTargetAttr OldParsed =
11701 OldTA->getFeaturesStr());
11702 llvm::sort(OldParsed.Features);
11703 ParsedTargetAttr NewParsed =
11705 NewTA->getFeaturesStr());
11706 // Sort order doesn't matter, it just needs to be consistent.
11707 llvm::sort(NewParsed.Features);
11708 if (OldParsed == NewParsed) {
11709 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11710 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11711 NewFD->setInvalidDecl();
11712 return true;
11713 }
11714 }
11715
11716 for (const auto *FD : OldFD->redecls()) {
11717 const auto *CurTA = FD->getAttr<TargetAttr>();
11718 const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
11719 // We allow forward declarations before ANY multiversioning attributes, but
11720 // nothing after the fact.
11722 ((NewTA && (!CurTA || CurTA->isInherited())) ||
11723 (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
11724 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
11725 << (NewTA ? 0 : 2);
11726 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11727 NewFD->setInvalidDecl();
11728 return true;
11729 }
11730 }
11731
11732 OldFD->setIsMultiVersion();
11733 NewFD->setIsMultiVersion();
11734 Redeclaration = false;
11735 OldDecl = nullptr;
11736 Previous.clear();
11737 return false;
11738}
11739
11741 MultiVersionKind OldKind = Old->getMultiVersionKind();
11742 MultiVersionKind NewKind = New->getMultiVersionKind();
11743
11744 if (OldKind == NewKind || OldKind == MultiVersionKind::None ||
11745 NewKind == MultiVersionKind::None)
11746 return true;
11747
11748 if (Old->getASTContext().getTargetInfo().getTriple().isAArch64()) {
11749 switch (OldKind) {
11751 return NewKind == MultiVersionKind::TargetClones;
11753 return NewKind == MultiVersionKind::TargetVersion;
11754 default:
11755 return false;
11756 }
11757 } else {
11758 switch (OldKind) {
11760 return NewKind == MultiVersionKind::CPUSpecific;
11762 return NewKind == MultiVersionKind::CPUDispatch;
11763 default:
11764 return false;
11765 }
11766 }
11767}
11768
11769/// Check the validity of a new function declaration being added to an existing
11770/// multiversioned declaration collection.
11772 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
11773 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
11774 const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
11776
11777 // Disallow mixing of multiversioning types.
11778 if (!MultiVersionTypesCompatible(OldFD, NewFD)) {
11779 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
11780 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11781 NewFD->setInvalidDecl();
11782 return true;
11783 }
11784
11785 // Add the default target_version attribute if it's missing.
11786 patchDefaultTargetVersion(OldFD, NewFD);
11787 patchDefaultTargetVersion(NewFD, OldFD);
11788
11789 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11790 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11791 MultiVersionKind NewMVKind = NewFD->getMultiVersionKind();
11792 [[maybe_unused]] MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
11793
11794 ParsedTargetAttr NewParsed;
11795 if (NewTA) {
11797 NewTA->getFeaturesStr());
11798 llvm::sort(NewParsed.Features);
11799 }
11801 if (NewTVA) {
11802 NewTVA->getFeatures(NewFeats);
11803 llvm::sort(NewFeats);
11804 }
11805
11806 bool UseMemberUsingDeclRules =
11807 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
11808
11809 bool MayNeedOverloadableChecks =
11811
11812 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
11813 // of a previous member of the MultiVersion set.
11814 for (NamedDecl *ND : Previous) {
11815 FunctionDecl *CurFD = ND->getAsFunction();
11816 if (!CurFD || CurFD->isInvalidDecl())
11817 continue;
11818 if (MayNeedOverloadableChecks &&
11819 S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
11820 continue;
11821
11822 switch (NewMVKind) {
11824 assert(OldMVKind == MultiVersionKind::TargetClones &&
11825 "Only target_clones can be omitted in subsequent declarations");
11826 break;
11828 const auto *CurTA = CurFD->getAttr<TargetAttr>();
11829 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
11830 NewFD->setIsMultiVersion();
11831 Redeclaration = true;
11832 OldDecl = ND;
11833 return false;
11834 }
11835
11836 ParsedTargetAttr CurParsed =
11838 CurTA->getFeaturesStr());
11839 llvm::sort(CurParsed.Features);
11840 if (CurParsed == NewParsed) {
11841 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11842 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11843 NewFD->setInvalidDecl();
11844 return true;
11845 }
11846 break;
11847 }
11849 if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11850 if (CurTVA->getName() == NewTVA->getName()) {
11851 NewFD->setIsMultiVersion();
11852 Redeclaration = true;
11853 OldDecl = ND;
11854 return false;
11855 }
11857 CurTVA->getFeatures(CurFeats);
11858 llvm::sort(CurFeats);
11859
11860 if (CurFeats == NewFeats) {
11861 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11862 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11863 NewFD->setInvalidDecl();
11864 return true;
11865 }
11866 } else if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11867 // Default
11868 if (NewFeats.empty())
11869 break;
11870
11871 for (unsigned I = 0; I < CurClones->featuresStrs_size(); ++I) {
11873 CurClones->getFeatures(CurFeats, I);
11874 llvm::sort(CurFeats);
11875
11876 if (CurFeats == NewFeats) {
11877 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11878 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11879 NewFD->setInvalidDecl();
11880 return true;
11881 }
11882 }
11883 }
11884 break;
11885 }
11887 assert(NewClones && "MultiVersionKind does not match attribute type");
11888 if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11889 if (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
11890 !std::equal(CurClones->featuresStrs_begin(),
11891 CurClones->featuresStrs_end(),
11892 NewClones->featuresStrs_begin())) {
11893 S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
11894 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11895 NewFD->setInvalidDecl();
11896 return true;
11897 }
11898 } else if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11900 CurTVA->getFeatures(CurFeats);
11901 llvm::sort(CurFeats);
11902
11903 // Default
11904 if (CurFeats.empty())
11905 break;
11906
11907 for (unsigned I = 0; I < NewClones->featuresStrs_size(); ++I) {
11908 NewFeats.clear();
11909 NewClones->getFeatures(NewFeats, I);
11910 llvm::sort(NewFeats);
11911
11912 if (CurFeats == NewFeats) {
11913 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11914 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11915 NewFD->setInvalidDecl();
11916 return true;
11917 }
11918 }
11919 break;
11920 }
11921 Redeclaration = true;
11922 OldDecl = CurFD;
11923 NewFD->setIsMultiVersion();
11924 return false;
11925 }
11928 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
11929 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
11930 // Handle CPUDispatch/CPUSpecific versions.
11931 // Only 1 CPUDispatch function is allowed, this will make it go through
11932 // the redeclaration errors.
11933 if (NewMVKind == MultiVersionKind::CPUDispatch &&
11934 CurFD->hasAttr<CPUDispatchAttr>()) {
11935 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
11936 std::equal(
11937 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
11938 NewCPUDisp->cpus_begin(),
11939 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11940 return Cur->getName() == New->getName();
11941 })) {
11942 NewFD->setIsMultiVersion();
11943 Redeclaration = true;
11944 OldDecl = ND;
11945 return false;
11946 }
11947
11948 // If the declarations don't match, this is an error condition.
11949 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
11950 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11951 NewFD->setInvalidDecl();
11952 return true;
11953 }
11954 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
11955 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
11956 std::equal(
11957 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
11958 NewCPUSpec->cpus_begin(),
11959 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11960 return Cur->getName() == New->getName();
11961 })) {
11962 NewFD->setIsMultiVersion();
11963 Redeclaration = true;
11964 OldDecl = ND;
11965 return false;
11966 }
11967
11968 // Only 1 version of CPUSpecific is allowed for each CPU.
11969 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
11970 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
11971 if (CurII == NewII) {
11972 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
11973 << NewII;
11974 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11975 NewFD->setInvalidDecl();
11976 return true;
11977 }
11978 }
11979 }
11980 }
11981 break;
11982 }
11983 }
11984 }
11985
11986 // Else, this is simply a non-redecl case. Checking the 'value' is only
11987 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
11988 // handled in the attribute adding step.
11989 if ((NewTA || NewTVA) && CheckMultiVersionValue(S, NewFD)) {
11990 NewFD->setInvalidDecl();
11991 return true;
11992 }
11993
11994 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
11995 !OldFD->isMultiVersion(), NewMVKind)) {
11996 NewFD->setInvalidDecl();
11997 return true;
11998 }
11999
12000 // Permit forward declarations in the case where these two are compatible.
12001 if (!OldFD->isMultiVersion()) {
12002 OldFD->setIsMultiVersion();
12003 NewFD->setIsMultiVersion();
12004 Redeclaration = true;
12005 OldDecl = OldFD;
12006 return false;
12007 }
12008
12009 NewFD->setIsMultiVersion();
12010 Redeclaration = false;
12011 OldDecl = nullptr;
12012 Previous.clear();
12013 return false;
12014}
12015
12016/// Check the validity of a mulitversion function declaration.
12017/// Also sets the multiversion'ness' of the function itself.
12018///
12019/// This sets NewFD->isInvalidDecl() to true if there was an error.
12020///
12021/// Returns true if there was an error, false otherwise.
12023 bool &Redeclaration, NamedDecl *&OldDecl,
12025 const TargetInfo &TI = S.getASTContext().getTargetInfo();
12026
12027 // Check if FMV is disabled.
12028 if (TI.getTriple().isAArch64() && !TI.hasFeature("fmv"))
12029 return false;
12030
12031 const auto *NewTA = NewFD->getAttr<TargetAttr>();
12032 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
12033 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
12034 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
12035 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
12036 MultiVersionKind MVKind = NewFD->getMultiVersionKind();
12037
12038 // Main isn't allowed to become a multiversion function, however it IS
12039 // permitted to have 'main' be marked with the 'target' optimization hint,
12040 // for 'target_version' only default is allowed.
12041 if (NewFD->isMain()) {
12042 if (MVKind != MultiVersionKind::None &&
12043 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
12044 !(MVKind == MultiVersionKind::TargetVersion &&
12045 NewTVA->isDefaultVersion())) {
12046 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
12047 NewFD->setInvalidDecl();
12048 return true;
12049 }
12050 return false;
12051 }
12052
12053 // Target attribute on AArch64 is not used for multiversioning
12054 if (NewTA && TI.getTriple().isAArch64())
12055 return false;
12056
12057 // Target attribute on RISCV is not used for multiversioning
12058 if (NewTA && TI.getTriple().isRISCV())
12059 return false;
12060
12061 if (!OldDecl || !OldDecl->getAsFunction() ||
12062 !OldDecl->getDeclContext()->getRedeclContext()->Equals(
12063 NewFD->getDeclContext()->getRedeclContext())) {
12064 // If there's no previous declaration, AND this isn't attempting to cause
12065 // multiversioning, this isn't an error condition.
12066 if (MVKind == MultiVersionKind::None)
12067 return false;
12068 return CheckMultiVersionFirstFunction(S, NewFD);
12069 }
12070
12071 FunctionDecl *OldFD = OldDecl->getAsFunction();
12072
12073 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
12074 return false;
12075
12076 // Multiversioned redeclarations aren't allowed to omit the attribute, except
12077 // for target_clones and target_version.
12078 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
12081 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
12083 NewFD->setInvalidDecl();
12084 return true;
12085 }
12086
12087 if (!OldFD->isMultiVersion()) {
12088 switch (MVKind) {
12092 S, OldFD, NewFD, Redeclaration, OldDecl, Previous);
12094 if (OldFD->isUsed(false)) {
12095 NewFD->setInvalidDecl();
12096 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
12097 }
12098 OldFD->setIsMultiVersion();
12099 break;
12100
12104 break;
12105 }
12106 }
12107
12108 // At this point, we have a multiversion function decl (in OldFD) AND an
12109 // appropriate attribute in the current function decl. Resolve that these are
12110 // still compatible with previous declarations.
12111 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, NewCPUDisp,
12112 NewCPUSpec, NewClones, Redeclaration,
12113 OldDecl, Previous);
12114}
12115
12117 bool IsPure = NewFD->hasAttr<PureAttr>();
12118 bool IsConst = NewFD->hasAttr<ConstAttr>();
12119
12120 // If there are no pure or const attributes, there's nothing to check.
12121 if (!IsPure && !IsConst)
12122 return;
12123
12124 // If the function is marked both pure and const, we retain the const
12125 // attribute because it makes stronger guarantees than the pure attribute, and
12126 // we drop the pure attribute explicitly to prevent later confusion about
12127 // semantics.
12128 if (IsPure && IsConst) {
12129 S.Diag(NewFD->getLocation(), diag::warn_const_attr_with_pure_attr);
12130 NewFD->dropAttrs<PureAttr>();
12131 }
12132
12133 // Constructors and destructors are functions which return void, so are
12134 // handled here as well.
12135 if (NewFD->getReturnType()->isVoidType()) {
12136 S.Diag(NewFD->getLocation(), diag::warn_pure_function_returns_void)
12137 << IsConst;
12138 NewFD->dropAttrs<PureAttr, ConstAttr>();
12139 }
12140}
12141
12144 bool IsMemberSpecialization,
12145 bool DeclIsDefn) {
12146 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
12147 "Variably modified return types are not handled here");
12148
12149 // Determine whether the type of this function should be merged with
12150 // a previous visible declaration. This never happens for functions in C++,
12151 // and always happens in C if the previous declaration was visible.
12152 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
12153 !Previous.isShadowed();
12154
12155 bool Redeclaration = false;
12156 NamedDecl *OldDecl = nullptr;
12157 bool MayNeedOverloadableChecks = false;
12158
12160 // Merge or overload the declaration with an existing declaration of
12161 // the same name, if appropriate.
12162 if (!Previous.empty()) {
12163 // Determine whether NewFD is an overload of PrevDecl or
12164 // a declaration that requires merging. If it's an overload,
12165 // there's no more work to do here; we'll just add the new
12166 // function to the scope.
12168 NamedDecl *Candidate = Previous.getRepresentativeDecl();
12169 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
12170 Redeclaration = true;
12171 OldDecl = Candidate;
12172 }
12173 } else {
12174 MayNeedOverloadableChecks = true;
12175 switch (CheckOverload(S, NewFD, Previous, OldDecl,
12176 /*NewIsUsingDecl*/ false)) {
12178 Redeclaration = true;
12179 break;
12180
12182 Redeclaration = true;
12183 break;
12184
12186 Redeclaration = false;
12187 break;
12188 }
12189 }
12190 }
12191
12192 // Check for a previous extern "C" declaration with this name.
12193 if (!Redeclaration &&
12195 if (!Previous.empty()) {
12196 // This is an extern "C" declaration with the same name as a previous
12197 // declaration, and thus redeclares that entity...
12198 Redeclaration = true;
12199 OldDecl = Previous.getFoundDecl();
12200 MergeTypeWithPrevious = false;
12201
12202 // ... except in the presence of __attribute__((overloadable)).
12203 if (OldDecl->hasAttr<OverloadableAttr>() ||
12204 NewFD->hasAttr<OverloadableAttr>()) {
12205 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
12206 MayNeedOverloadableChecks = true;
12207 Redeclaration = false;
12208 OldDecl = nullptr;
12209 }
12210 }
12211 }
12212 }
12213
12214 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
12215 return Redeclaration;
12216
12217 // PPC MMA non-pointer types are not allowed as function return types.
12218 if (Context.getTargetInfo().getTriple().isPPC64() &&
12219 PPC().CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
12220 NewFD->setInvalidDecl();
12221 }
12222
12223 CheckConstPureAttributesUsage(*this, NewFD);
12224
12225 // C++ [dcl.spec.auto.general]p12:
12226 // Return type deduction for a templated function with a placeholder in its
12227 // declared type occurs when the definition is instantiated even if the
12228 // function body contains a return statement with a non-type-dependent
12229 // operand.
12230 //
12231 // C++ [temp.dep.expr]p3:
12232 // An id-expression is type-dependent if it is a template-id that is not a
12233 // concept-id and is dependent; or if its terminal name is:
12234 // - [...]
12235 // - associated by name lookup with one or more declarations of member
12236 // functions of a class that is the current instantiation declared with a
12237 // return type that contains a placeholder type,
12238 // - [...]
12239 //
12240 // If this is a templated function with a placeholder in its return type,
12241 // make the placeholder type dependent since it won't be deduced until the
12242 // definition is instantiated. We do this here because it needs to happen
12243 // for implicitly instantiated member functions/member function templates.
12244 if (getLangOpts().CPlusPlus14 &&
12245 (NewFD->isDependentContext() &&
12246 NewFD->getReturnType()->isUndeducedType())) {
12247 const FunctionProtoType *FPT =
12248 NewFD->getType()->castAs<FunctionProtoType>();
12249 QualType NewReturnType = SubstAutoTypeDependent(FPT->getReturnType());
12250 NewFD->setType(Context.getFunctionType(NewReturnType, FPT->getParamTypes(),
12251 FPT->getExtProtoInfo()));
12252 }
12253
12254 // C++11 [dcl.constexpr]p8:
12255 // A constexpr specifier for a non-static member function that is not
12256 // a constructor declares that member function to be const.
12257 //
12258 // This needs to be delayed until we know whether this is an out-of-line
12259 // definition of a static member function.
12260 //
12261 // This rule is not present in C++1y, so we produce a backwards
12262 // compatibility warning whenever it happens in C++11.
12263 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
12264 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
12265 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
12267 CXXMethodDecl *OldMD = nullptr;
12268 if (OldDecl)
12269 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
12270 if (!OldMD || !OldMD->isStatic()) {
12271 const FunctionProtoType *FPT =
12274 EPI.TypeQuals.addConst();
12275 MD->setType(Context.getFunctionType(FPT->getReturnType(),
12276 FPT->getParamTypes(), EPI));
12277
12278 // Warn that we did this, if we're not performing template instantiation.
12279 // In that case, we'll have warned already when the template was defined.
12280 if (!inTemplateInstantiation()) {
12281 SourceLocation AddConstLoc;
12284 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
12285
12286 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
12287 << FixItHint::CreateInsertion(AddConstLoc, " const");
12288 }
12289 }
12290 }
12291
12292 if (Redeclaration) {
12293 // NewFD and OldDecl represent declarations that need to be
12294 // merged.
12295 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
12296 DeclIsDefn)) {
12297 NewFD->setInvalidDecl();
12298 return Redeclaration;
12299 }
12300
12301 Previous.clear();
12302 Previous.addDecl(OldDecl);
12303
12304 if (FunctionTemplateDecl *OldTemplateDecl =
12305 dyn_cast<FunctionTemplateDecl>(OldDecl)) {
12306 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
12307 FunctionTemplateDecl *NewTemplateDecl
12309 assert(NewTemplateDecl && "Template/non-template mismatch");
12310
12311 // The call to MergeFunctionDecl above may have created some state in
12312 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
12313 // can add it as a redeclaration.
12314 NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
12315
12316 NewFD->setPreviousDeclaration(OldFD);
12317 if (NewFD->isCXXClassMember()) {
12318 NewFD->setAccess(OldTemplateDecl->getAccess());
12319 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
12320 }
12321
12322 // If this is an explicit specialization of a member that is a function
12323 // template, mark it as a member specialization.
12324 if (IsMemberSpecialization &&
12325 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
12326 NewTemplateDecl->setMemberSpecialization();
12327 assert(OldTemplateDecl->isMemberSpecialization());
12328 // Explicit specializations of a member template do not inherit deleted
12329 // status from the parent member template that they are specializing.
12330 if (OldFD->isDeleted()) {
12331 // FIXME: This assert will not hold in the presence of modules.
12332 assert(OldFD->getCanonicalDecl() == OldFD);
12333 // FIXME: We need an update record for this AST mutation.
12334 OldFD->setDeletedAsWritten(false);
12335 }
12336 }
12337
12338 } else {
12339 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
12340 auto *OldFD = cast<FunctionDecl>(OldDecl);
12341 // This needs to happen first so that 'inline' propagates.
12342 NewFD->setPreviousDeclaration(OldFD);
12343 if (NewFD->isCXXClassMember())
12344 NewFD->setAccess(OldFD->getAccess());
12345 }
12346 }
12347 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
12348 !NewFD->getAttr<OverloadableAttr>()) {
12349 assert((Previous.empty() ||
12350 llvm::any_of(Previous,
12351 [](const NamedDecl *ND) {
12352 return ND->hasAttr<OverloadableAttr>();
12353 })) &&
12354 "Non-redecls shouldn't happen without overloadable present");
12355
12356 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
12357 const auto *FD = dyn_cast<FunctionDecl>(ND);
12358 return FD && !FD->hasAttr<OverloadableAttr>();
12359 });
12360
12361 if (OtherUnmarkedIter != Previous.end()) {
12362 Diag(NewFD->getLocation(),
12363 diag::err_attribute_overloadable_multiple_unmarked_overloads);
12364 Diag((*OtherUnmarkedIter)->getLocation(),
12365 diag::note_attribute_overloadable_prev_overload)
12366 << false;
12367
12368 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
12369 }
12370 }
12371
12372 if (LangOpts.OpenMP)
12374
12375 if (NewFD->hasAttr<SYCLKernelEntryPointAttr>())
12377
12378 if (NewFD->hasAttr<SYCLExternalAttr>())
12380
12381 // Semantic checking for this function declaration (in isolation).
12382
12383 if (getLangOpts().CPlusPlus) {
12384 // C++-specific checks.
12385 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
12387 } else if (CXXDestructorDecl *Destructor =
12388 dyn_cast<CXXDestructorDecl>(NewFD)) {
12389 // We check here for invalid destructor names.
12390 // If we have a friend destructor declaration that is dependent, we can't
12391 // diagnose right away because cases like this are still valid:
12392 // template <class T> struct A { friend T::X::~Y(); };
12393 // struct B { struct Y { ~Y(); }; using X = Y; };
12394 // template struct A<B>;
12396 !Destructor->getFunctionObjectParameterType()->isDependentType()) {
12397 CanQualType ClassType =
12398 Context.getCanonicalTagType(Destructor->getParent());
12399
12400 DeclarationName Name =
12401 Context.DeclarationNames.getCXXDestructorName(ClassType);
12402 if (NewFD->getDeclName() != Name) {
12403 Diag(NewFD->getLocation(), diag::err_destructor_name);
12404 NewFD->setInvalidDecl();
12405 return Redeclaration;
12406 }
12407 }
12408 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
12409 if (auto *TD = Guide->getDescribedFunctionTemplate())
12411
12412 // A deduction guide is not on the list of entities that can be
12413 // explicitly specialized.
12414 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
12415 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
12416 << /*explicit specialization*/ 1;
12417 }
12418
12419 // Find any virtual functions that this function overrides.
12420 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
12421 if (!Method->isFunctionTemplateSpecialization() &&
12422 !Method->getDescribedFunctionTemplate() &&
12423 Method->isCanonicalDecl()) {
12424 AddOverriddenMethods(Method->getParent(), Method);
12425 }
12426 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
12427 // C++2a [class.virtual]p6
12428 // A virtual method shall not have a requires-clause.
12430 diag::err_constrained_virtual_method);
12431
12432 if (Method->isStatic())
12434 }
12435
12436 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
12437 ActOnConversionDeclarator(Conversion);
12438
12439 // Extra checking for C++ overloaded operators (C++ [over.oper]).
12440 if (NewFD->isOverloadedOperator() &&
12442 NewFD->setInvalidDecl();
12443 return Redeclaration;
12444 }
12445
12446 // Extra checking for C++0x literal operators (C++0x [over.literal]).
12447 if (NewFD->getLiteralIdentifier() &&
12449 NewFD->setInvalidDecl();
12450 return Redeclaration;
12451 }
12452
12453 // In C++, check default arguments now that we have merged decls. Unless
12454 // the lexical context is the class, because in this case this is done
12455 // during delayed parsing anyway.
12456 if (!CurContext->isRecord())
12458
12459 // If this function is declared as being extern "C", then check to see if
12460 // the function returns a UDT (class, struct, or union type) that is not C
12461 // compatible, and if it does, warn the user.
12462 // But, issue any diagnostic on the first declaration only.
12463 if (Previous.empty() && NewFD->isExternC()) {
12464 QualType R = NewFD->getReturnType();
12465 if (R->isIncompleteType() && !R->isVoidType())
12466 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
12467 << NewFD << R;
12468 else if (!R.isPODType(Context) && !R->isVoidType() &&
12470 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
12471 }
12472
12473 // C++1z [dcl.fct]p6:
12474 // [...] whether the function has a non-throwing exception-specification
12475 // [is] part of the function type
12476 //
12477 // This results in an ABI break between C++14 and C++17 for functions whose
12478 // declared type includes an exception-specification in a parameter or
12479 // return type. (Exception specifications on the function itself are OK in
12480 // most cases, and exception specifications are not permitted in most other
12481 // contexts where they could make it into a mangling.)
12482 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
12483 auto HasNoexcept = [&](QualType T) -> bool {
12484 // Strip off declarator chunks that could be between us and a function
12485 // type. We don't need to look far, exception specifications are very
12486 // restricted prior to C++17.
12487 if (auto *RT = T->getAs<ReferenceType>())
12488 T = RT->getPointeeType();
12489 else if (T->isAnyPointerType())
12490 T = T->getPointeeType();
12491 else if (auto *MPT = T->getAs<MemberPointerType>())
12492 T = MPT->getPointeeType();
12493 if (auto *FPT = T->getAs<FunctionProtoType>())
12494 if (FPT->isNothrow())
12495 return true;
12496 return false;
12497 };
12498
12499 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12500 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12501 for (QualType T : FPT->param_types())
12502 AnyNoexcept |= HasNoexcept(T);
12503 if (AnyNoexcept)
12504 Diag(NewFD->getLocation(),
12505 diag::warn_cxx17_compat_exception_spec_in_signature)
12506 << NewFD;
12507 }
12508
12509 if (!Redeclaration && LangOpts.CUDA) {
12510 bool IsKernel = NewFD->hasAttr<CUDAGlobalAttr>();
12511 for (auto *Parm : NewFD->parameters()) {
12512 if (!Parm->getType()->isDependentType() &&
12513 Parm->hasAttr<CUDAGridConstantAttr>() &&
12514 !(IsKernel && Parm->getType().isConstQualified()))
12515 Diag(Parm->getAttr<CUDAGridConstantAttr>()->getLocation(),
12516 diag::err_cuda_grid_constant_not_allowed);
12517 }
12519 }
12520 }
12521
12522 if (DeclIsDefn && Context.getTargetInfo().getTriple().isAArch64())
12524
12525 return Redeclaration;
12526}
12527
12529 // [basic.start.main]p3
12530 // The main function shall not be declared with C linkage-specification.
12531 if (FD->isExternCContext())
12532 Diag(FD->getLocation(), diag::ext_main_invalid_linkage_specification);
12533
12534 // C++11 [basic.start.main]p3:
12535 // A program that [...] declares main to be inline, static or
12536 // constexpr is ill-formed.
12537 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
12538 // appear in a declaration of main.
12539 // static main is not an error under C99, but we should warn about it.
12540 // We accept _Noreturn main as an extension.
12541 if (FD->getStorageClass() == SC_Static)
12543 ? diag::err_static_main : diag::warn_static_main)
12545 if (FD->isInlineSpecified())
12546 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
12548 if (DS.isNoreturnSpecified()) {
12549 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12550 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
12551 Diag(NoreturnLoc, diag::ext_noreturn_main);
12552 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
12553 << FixItHint::CreateRemoval(NoreturnRange);
12554 }
12555 if (FD->isConstexpr()) {
12556 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
12557 << FD->isConsteval()
12560 }
12561
12562 if (getLangOpts().OpenCL) {
12563 Diag(FD->getLocation(), diag::err_opencl_no_main)
12564 << FD->hasAttr<DeviceKernelAttr>();
12565 FD->setInvalidDecl();
12566 return;
12567 }
12568
12569 if (FD->hasAttr<SYCLExternalAttr>()) {
12570 Diag(FD->getLocation(), diag::err_sycl_external_invalid_main)
12571 << FD->getAttr<SYCLExternalAttr>();
12572 FD->setInvalidDecl();
12573 return;
12574 }
12575
12576 // Functions named main in hlsl are default entries, but don't have specific
12577 // signatures they are required to conform to.
12578 if (getLangOpts().HLSL)
12579 return;
12580
12581 QualType T = FD->getType();
12582 assert(T->isFunctionType() && "function decl is not of function type");
12583 const FunctionType* FT = T->castAs<FunctionType>();
12584
12585 // Set default calling convention for main()
12586 if (FT->getCallConv() != CC_C) {
12587 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
12588 FD->setType(QualType(FT, 0));
12589 T = Context.getCanonicalType(FD->getType());
12590 }
12591
12593 // In C with GNU extensions we allow main() to have non-integer return
12594 // type, but we should warn about the extension, and we disable the
12595 // implicit-return-zero rule.
12596
12597 // GCC in C mode accepts qualified 'int'.
12598 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
12599 FD->setHasImplicitReturnZero(true);
12600 else {
12601 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
12602 SourceRange RTRange = FD->getReturnTypeSourceRange();
12603 if (RTRange.isValid())
12604 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
12605 << FixItHint::CreateReplacement(RTRange, "int");
12606 }
12607 } else {
12608 // In C and C++, main magically returns 0 if you fall off the end;
12609 // set the flag which tells us that.
12610 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12611
12612 // All the standards say that main() should return 'int'.
12613 if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
12614 FD->setHasImplicitReturnZero(true);
12615 else {
12616 // Otherwise, this is just a flat-out error.
12617 SourceRange RTRange = FD->getReturnTypeSourceRange();
12618 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
12619 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
12620 : FixItHint());
12621 FD->setInvalidDecl(true);
12622 }
12623
12624 // [basic.start.main]p3:
12625 // A program that declares a function main that belongs to the global scope
12626 // and is attached to a named module is ill-formed.
12627 if (FD->isInNamedModule()) {
12628 const SourceLocation start = FD->getTypeSpecStartLoc();
12629 Diag(start, diag::warn_main_in_named_module)
12630 << FixItHint::CreateInsertion(start, "extern \"C++\" ", true);
12631 }
12632 }
12633
12634 // Treat protoless main() as nullary.
12635 if (isa<FunctionNoProtoType>(FT)) return;
12636
12638 unsigned nparams = FTP->getNumParams();
12639 assert(FD->getNumParams() == nparams);
12640
12641 bool HasExtraParameters = (nparams > 3);
12642
12643 if (FTP->isVariadic()) {
12644 Diag(FD->getLocation(), diag::ext_variadic_main);
12645 // FIXME: if we had information about the location of the ellipsis, we
12646 // could add a FixIt hint to remove it as a parameter.
12647 }
12648
12649 // Darwin passes an undocumented fourth argument of type char**. If
12650 // other platforms start sprouting these, the logic below will start
12651 // getting shifty.
12652 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12653 HasExtraParameters = false;
12654
12655 if (HasExtraParameters) {
12656 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
12657 FD->setInvalidDecl(true);
12658 nparams = 3;
12659 }
12660
12661 // FIXME: a lot of the following diagnostics would be improved
12662 // if we had some location information about types.
12663
12664 QualType CharPP =
12665 Context.getPointerType(Context.getPointerType(Context.CharTy));
12666 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12667
12668 for (unsigned i = 0; i < nparams; ++i) {
12669 QualType AT = FTP->getParamType(i);
12670
12671 bool mismatch = true;
12672
12673 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
12674 mismatch = false;
12675 else if (Expected[i] == CharPP) {
12676 // As an extension, the following forms are okay:
12677 // char const **
12678 // char const * const *
12679 // char * const *
12680
12682 const PointerType* PT;
12683 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
12684 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
12685 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
12686 Context.CharTy)) {
12687 qs.removeConst();
12688 mismatch = !qs.empty();
12689 }
12690 }
12691
12692 if (mismatch) {
12693 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
12694 // TODO: suggest replacing given type with expected type
12695 FD->setInvalidDecl(true);
12696 }
12697 }
12698
12699 if (nparams == 1 && !FD->isInvalidDecl()) {
12700 Diag(FD->getLocation(), diag::warn_main_one_arg);
12701 }
12702
12703 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12704 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12705 FD->setInvalidDecl();
12706 }
12707}
12708
12709static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
12710
12711 // Default calling convention for main and wmain is __cdecl
12712 if (FD->getName() == "main" || FD->getName() == "wmain")
12713 return false;
12714
12715 // Default calling convention for MinGW and Cygwin is __cdecl
12716 const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
12717 if (T.isOSCygMing())
12718 return false;
12719
12720 // Default calling convention for WinMain, wWinMain and DllMain
12721 // is __stdcall on 32 bit Windows
12722 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
12723 return true;
12724
12725 return false;
12726}
12727
12729 QualType T = FD->getType();
12730 assert(T->isFunctionType() && "function decl is not of function type");
12731 const FunctionType *FT = T->castAs<FunctionType>();
12732
12733 // Set an implicit return of 'zero' if the function can return some integral,
12734 // enumeration, pointer or nullptr type.
12738 // DllMain is exempt because a return value of zero means it failed.
12739 if (FD->getName() != "DllMain")
12740 FD->setHasImplicitReturnZero(true);
12741
12742 // Explicitly specified calling conventions are applied to MSVC entry points
12743 if (!hasExplicitCallingConv(T)) {
12744 if (isDefaultStdCall(FD, *this)) {
12745 if (FT->getCallConv() != CC_X86StdCall) {
12746 FT = Context.adjustFunctionType(
12748 FD->setType(QualType(FT, 0));
12749 }
12750 } else if (FT->getCallConv() != CC_C) {
12751 FT = Context.adjustFunctionType(FT,
12753 FD->setType(QualType(FT, 0));
12754 }
12755 }
12756
12757 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12758 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12759 FD->setInvalidDecl();
12760 }
12761}
12762
12764 // FIXME: Need strict checking. In C89, we need to check for
12765 // any assignment, increment, decrement, function-calls, or
12766 // commas outside of a sizeof. In C99, it's the same list,
12767 // except that the aforementioned are allowed in unevaluated
12768 // expressions. Everything else falls under the
12769 // "may accept other forms of constant expressions" exception.
12770 //
12771 // Regular C++ code will not end up here (exceptions: language extensions,
12772 // OpenCL C++ etc), so the constant expression rules there don't matter.
12773 if (Init->isValueDependent()) {
12774 assert(Init->containsErrors() &&
12775 "Dependent code should only occur in error-recovery path.");
12776 return true;
12777 }
12778 const Expr *Culprit;
12779 if (Init->isConstantInitializer(Context, false, &Culprit))
12780 return false;
12781 Diag(Culprit->getExprLoc(), DiagID) << Culprit->getSourceRange();
12782 return true;
12783}
12784
12785namespace {
12786 // Visits an initialization expression to see if OrigDecl is evaluated in
12787 // its own initialization and throws a warning if it does.
12788 class SelfReferenceChecker
12789 : public EvaluatedExprVisitor<SelfReferenceChecker> {
12790 Sema &S;
12791 Decl *OrigDecl;
12792 bool isRecordType;
12793 bool isPODType;
12794 bool isReferenceType;
12795 bool isInCXXOperatorCall;
12796
12797 bool isInitList;
12798 llvm::SmallVector<unsigned, 4> InitFieldIndex;
12799
12800 public:
12802
12803 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
12804 S(S), OrigDecl(OrigDecl) {
12805 isPODType = false;
12806 isRecordType = false;
12807 isReferenceType = false;
12808 isInCXXOperatorCall = false;
12809 isInitList = false;
12810 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
12811 isPODType = VD->getType().isPODType(S.Context);
12812 isRecordType = VD->getType()->isRecordType();
12813 isReferenceType = VD->getType()->isReferenceType();
12814 }
12815 }
12816
12817 // For most expressions, just call the visitor. For initializer lists,
12818 // track the index of the field being initialized since fields are
12819 // initialized in order allowing use of previously initialized fields.
12820 void CheckExpr(Expr *E) {
12821 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
12822 if (!InitList) {
12823 Visit(E);
12824 return;
12825 }
12826
12827 // Track and increment the index here.
12828 isInitList = true;
12829 InitFieldIndex.push_back(0);
12830 for (auto *Child : InitList->children()) {
12831 CheckExpr(cast<Expr>(Child));
12832 ++InitFieldIndex.back();
12833 }
12834 InitFieldIndex.pop_back();
12835 }
12836
12837 // Returns true if MemberExpr is checked and no further checking is needed.
12838 // Returns false if additional checking is required.
12839 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
12840 llvm::SmallVector<FieldDecl*, 4> Fields;
12841 Expr *Base = E;
12842 bool ReferenceField = false;
12843
12844 // Get the field members used.
12845 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12846 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
12847 if (!FD)
12848 return false;
12849 Fields.push_back(FD);
12850 if (FD->getType()->isReferenceType())
12851 ReferenceField = true;
12852 Base = ME->getBase()->IgnoreParenImpCasts();
12853 }
12854
12855 // Keep checking only if the base Decl is the same.
12856 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
12857 if (!DRE || DRE->getDecl() != OrigDecl)
12858 return false;
12859
12860 // A reference field can be bound to an unininitialized field.
12861 if (CheckReference && !ReferenceField)
12862 return true;
12863
12864 // Convert FieldDecls to their index number.
12865 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
12866 for (const FieldDecl *I : llvm::reverse(Fields))
12867 UsedFieldIndex.push_back(I->getFieldIndex());
12868
12869 // See if a warning is needed by checking the first difference in index
12870 // numbers. If field being used has index less than the field being
12871 // initialized, then the use is safe.
12872 for (auto UsedIter = UsedFieldIndex.begin(),
12873 UsedEnd = UsedFieldIndex.end(),
12874 OrigIter = InitFieldIndex.begin(),
12875 OrigEnd = InitFieldIndex.end();
12876 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
12877 if (*UsedIter < *OrigIter)
12878 return true;
12879 if (*UsedIter > *OrigIter)
12880 break;
12881 }
12882
12883 // TODO: Add a different warning which will print the field names.
12884 HandleDeclRefExpr(DRE);
12885 return true;
12886 }
12887
12888 // For most expressions, the cast is directly above the DeclRefExpr.
12889 // For conditional operators, the cast can be outside the conditional
12890 // operator if both expressions are DeclRefExpr's.
12891 void HandleValue(Expr *E) {
12892 E = E->IgnoreParens();
12893 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
12894 HandleDeclRefExpr(DRE);
12895 return;
12896 }
12897
12898 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
12899 Visit(CO->getCond());
12900 HandleValue(CO->getTrueExpr());
12901 HandleValue(CO->getFalseExpr());
12902 return;
12903 }
12904
12905 if (BinaryConditionalOperator *BCO =
12906 dyn_cast<BinaryConditionalOperator>(E)) {
12907 Visit(BCO->getCond());
12908 HandleValue(BCO->getFalseExpr());
12909 return;
12910 }
12911
12912 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
12913 if (Expr *SE = OVE->getSourceExpr())
12914 HandleValue(SE);
12915 return;
12916 }
12917
12918 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12919 if (BO->getOpcode() == BO_Comma) {
12920 Visit(BO->getLHS());
12921 HandleValue(BO->getRHS());
12922 return;
12923 }
12924 }
12925
12926 if (isa<MemberExpr>(E)) {
12927 if (isInitList) {
12928 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
12929 false /*CheckReference*/))
12930 return;
12931 }
12932
12933 Expr *Base = E->IgnoreParenImpCasts();
12934 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12935 // Check for static member variables and don't warn on them.
12936 if (!isa<FieldDecl>(ME->getMemberDecl()))
12937 return;
12938 Base = ME->getBase()->IgnoreParenImpCasts();
12939 }
12940 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
12941 HandleDeclRefExpr(DRE);
12942 return;
12943 }
12944
12945 Visit(E);
12946 }
12947
12948 // Reference types not handled in HandleValue are handled here since all
12949 // uses of references are bad, not just r-value uses.
12950 void VisitDeclRefExpr(DeclRefExpr *E) {
12951 if (isReferenceType)
12952 HandleDeclRefExpr(E);
12953 }
12954
12955 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
12956 if (E->getCastKind() == CK_LValueToRValue) {
12957 HandleValue(E->getSubExpr());
12958 return;
12959 }
12960
12961 Inherited::VisitImplicitCastExpr(E);
12962 }
12963
12964 void VisitMemberExpr(MemberExpr *E) {
12965 if (isInitList) {
12966 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
12967 return;
12968 }
12969
12970 // Don't warn on arrays since they can be treated as pointers.
12971 if (E->getType()->canDecayToPointerType()) return;
12972
12973 // Warn when a non-static method call is followed by non-static member
12974 // field accesses, which is followed by a DeclRefExpr.
12975 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
12976 bool Warn = (MD && !MD->isStatic());
12977 Expr *Base = E->getBase()->IgnoreParenImpCasts();
12978 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12979 if (!isa<FieldDecl>(ME->getMemberDecl()))
12980 Warn = false;
12981 Base = ME->getBase()->IgnoreParenImpCasts();
12982 }
12983
12984 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
12985 if (Warn)
12986 HandleDeclRefExpr(DRE);
12987 return;
12988 }
12989
12990 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
12991 // Visit that expression.
12992 Visit(Base);
12993 }
12994
12995 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
12996 llvm::SaveAndRestore CxxOpCallScope(isInCXXOperatorCall, true);
12997 Expr *Callee = E->getCallee();
12998
12999 if (isa<UnresolvedLookupExpr>(Callee))
13000 return Inherited::VisitCXXOperatorCallExpr(E);
13001
13002 Visit(Callee);
13003 for (auto Arg: E->arguments())
13004 HandleValue(Arg->IgnoreParenImpCasts());
13005 }
13006
13007 void VisitLambdaExpr(LambdaExpr *E) {
13008 if (!isInCXXOperatorCall) {
13009 Inherited::VisitLambdaExpr(E);
13010 return;
13011 }
13012
13013 for (Expr *Init : E->capture_inits())
13014 if (DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(Init))
13015 HandleDeclRefExpr(DRE);
13016 else if (Init)
13017 Visit(Init);
13018 }
13019
13020 void VisitUnaryOperator(UnaryOperator *E) {
13021 // For POD record types, addresses of its own members are well-defined.
13022 if (E->getOpcode() == UO_AddrOf && isRecordType &&
13024 if (!isPODType)
13025 HandleValue(E->getSubExpr());
13026 return;
13027 }
13028
13029 if (E->isIncrementDecrementOp()) {
13030 HandleValue(E->getSubExpr());
13031 return;
13032 }
13033
13034 Inherited::VisitUnaryOperator(E);
13035 }
13036
13037 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
13038
13039 void VisitCXXConstructExpr(CXXConstructExpr *E) {
13040 if (E->getConstructor()->isCopyConstructor()) {
13041 Expr *ArgExpr = E->getArg(0);
13042 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
13043 if (ILE->getNumInits() == 1)
13044 ArgExpr = ILE->getInit(0);
13045 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
13046 if (ICE->getCastKind() == CK_NoOp)
13047 ArgExpr = ICE->getSubExpr();
13048 HandleValue(ArgExpr);
13049 return;
13050 }
13051 Inherited::VisitCXXConstructExpr(E);
13052 }
13053
13054 void VisitCallExpr(CallExpr *E) {
13055 // Treat std::move as a use.
13056 if (E->isCallToStdMove()) {
13057 HandleValue(E->getArg(0));
13058 return;
13059 }
13060
13061 Inherited::VisitCallExpr(E);
13062 }
13063
13064 void VisitBinaryOperator(BinaryOperator *E) {
13065 if (E->isCompoundAssignmentOp()) {
13066 HandleValue(E->getLHS());
13067 Visit(E->getRHS());
13068 return;
13069 }
13070
13071 Inherited::VisitBinaryOperator(E);
13072 }
13073
13074 // A custom visitor for BinaryConditionalOperator is needed because the
13075 // regular visitor would check the condition and true expression separately
13076 // but both point to the same place giving duplicate diagnostics.
13077 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
13078 Visit(E->getCond());
13079 Visit(E->getFalseExpr());
13080 }
13081
13082 void HandleDeclRefExpr(DeclRefExpr *DRE) {
13083 Decl* ReferenceDecl = DRE->getDecl();
13084 if (OrigDecl != ReferenceDecl) return;
13085 unsigned diag;
13086 if (isReferenceType) {
13087 diag = diag::warn_uninit_self_reference_in_reference_init;
13088 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
13089 diag = diag::warn_static_self_reference_in_init;
13090 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
13091 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
13092 DRE->getDecl()->getType()->isRecordType()) {
13093 diag = diag::warn_uninit_self_reference_in_init;
13094 } else {
13095 // Local variables will be handled by the CFG analysis.
13096 return;
13097 }
13098
13099 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
13100 S.PDiag(diag)
13101 << DRE->getDecl() << OrigDecl->getLocation()
13102 << DRE->getSourceRange());
13103 }
13104 };
13105
13106 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
13107 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
13108 bool DirectInit) {
13109 // Parameters arguments are occassionially constructed with itself,
13110 // for instance, in recursive functions. Skip them.
13111 if (isa<ParmVarDecl>(OrigDecl))
13112 return;
13113
13114 E = E->IgnoreParens();
13115
13116 // Skip checking T a = a where T is not a record or reference type.
13117 // Doing so is a way to silence uninitialized warnings.
13118 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
13119 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
13120 if (ICE->getCastKind() == CK_LValueToRValue)
13121 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
13122 if (DRE->getDecl() == OrigDecl)
13123 return;
13124
13125 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
13126 }
13127} // end anonymous namespace
13128
13129namespace {
13130 // Simple wrapper to add the name of a variable or (if no variable is
13131 // available) a DeclarationName into a diagnostic.
13132 struct VarDeclOrName {
13133 VarDecl *VDecl;
13134 DeclarationName Name;
13135
13136 friend const Sema::SemaDiagnosticBuilder &
13137 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
13138 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
13139 }
13140 };
13141} // end anonymous namespace
13142
13145 TypeSourceInfo *TSI,
13146 SourceRange Range, bool DirectInit,
13147 Expr *Init) {
13148 bool IsInitCapture = !VDecl;
13149 assert((!VDecl || !VDecl->isInitCapture()) &&
13150 "init captures are expected to be deduced prior to initialization");
13151
13152 VarDeclOrName VN{VDecl, Name};
13153
13154 DeducedType *Deduced = Type->getContainedDeducedType();
13155 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
13156
13157 // Diagnose auto array declarations in C23, unless it's a supported extension.
13158 if (getLangOpts().C23 && Type->isArrayType() &&
13159 !isa_and_present<StringLiteral, InitListExpr>(Init)) {
13160 Diag(Range.getBegin(), diag::err_auto_not_allowed)
13161 << (int)Deduced->getContainedAutoType()->getKeyword()
13162 << /*in array decl*/ 23 << Range;
13163 return QualType();
13164 }
13165
13166 // C++11 [dcl.spec.auto]p3
13167 if (!Init) {
13168 assert(VDecl && "no init for init capture deduction?");
13169
13170 // Except for class argument deduction, and then for an initializing
13171 // declaration only, i.e. no static at class scope or extern.
13173 VDecl->hasExternalStorage() ||
13174 VDecl->isStaticDataMember()) {
13175 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
13176 << VDecl->getDeclName() << Type;
13177 return QualType();
13178 }
13179 }
13180
13181 ArrayRef<Expr*> DeduceInits;
13182 if (Init)
13183 DeduceInits = Init;
13184
13185 auto *PL = dyn_cast_if_present<ParenListExpr>(Init);
13186 if (DirectInit && PL)
13187 DeduceInits = PL->exprs();
13188
13190 assert(VDecl && "non-auto type for init capture deduction?");
13193 VDecl->getLocation(), DirectInit, Init);
13194 // FIXME: Initialization should not be taking a mutable list of inits.
13195 SmallVector<Expr *, 8> InitsCopy(DeduceInits);
13196 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
13197 InitsCopy);
13198 }
13199
13200 if (DirectInit) {
13201 if (auto *IL = dyn_cast<InitListExpr>(Init))
13202 DeduceInits = IL->inits();
13203 }
13204
13205 // Deduction only works if we have exactly one source expression.
13206 if (DeduceInits.empty()) {
13207 // It isn't possible to write this directly, but it is possible to
13208 // end up in this situation with "auto x(some_pack...);"
13209 Diag(Init->getBeginLoc(), IsInitCapture
13210 ? diag::err_init_capture_no_expression
13211 : diag::err_auto_var_init_no_expression)
13212 << VN << Type << Range;
13213 return QualType();
13214 }
13215
13216 if (DeduceInits.size() > 1) {
13217 Diag(DeduceInits[1]->getBeginLoc(),
13218 IsInitCapture ? diag::err_init_capture_multiple_expressions
13219 : diag::err_auto_var_init_multiple_expressions)
13220 << VN << Type << Range;
13221 return QualType();
13222 }
13223
13224 Expr *DeduceInit = DeduceInits[0];
13225 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
13226 Diag(Init->getBeginLoc(), IsInitCapture
13227 ? diag::err_init_capture_paren_braces
13228 : diag::err_auto_var_init_paren_braces)
13229 << isa<InitListExpr>(Init) << VN << Type << Range;
13230 return QualType();
13231 }
13232
13233 // Expressions default to 'id' when we're in a debugger.
13234 bool DefaultedAnyToId = false;
13235 if (getLangOpts().DebuggerCastResultToId &&
13236 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
13238 if (Result.isInvalid()) {
13239 return QualType();
13240 }
13241 Init = Result.get();
13242 DefaultedAnyToId = true;
13243 }
13244
13245 // C++ [dcl.decomp]p1:
13246 // If the assignment-expression [...] has array type A and no ref-qualifier
13247 // is present, e has type cv A
13248 if (VDecl && isa<DecompositionDecl>(VDecl) &&
13249 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
13250 DeduceInit->getType()->isConstantArrayType())
13251 return Context.getQualifiedType(DeduceInit->getType(),
13252 Type.getQualifiers());
13253
13254 QualType DeducedType;
13255 TemplateDeductionInfo Info(DeduceInit->getExprLoc());
13257 DeduceAutoType(TSI->getTypeLoc(), DeduceInit, DeducedType, Info);
13260 if (!IsInitCapture)
13261 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
13262 else if (isa<InitListExpr>(Init))
13263 Diag(Range.getBegin(),
13264 diag::err_init_capture_deduction_failure_from_init_list)
13265 << VN
13266 << (DeduceInit->getType().isNull() ? TSI->getType()
13267 : DeduceInit->getType())
13268 << DeduceInit->getSourceRange();
13269 else
13270 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
13271 << VN << TSI->getType()
13272 << (DeduceInit->getType().isNull() ? TSI->getType()
13273 : DeduceInit->getType())
13274 << DeduceInit->getSourceRange();
13275 }
13276
13277 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
13278 // 'id' instead of a specific object type prevents most of our usual
13279 // checks.
13280 // We only want to warn outside of template instantiations, though:
13281 // inside a template, the 'id' could have come from a parameter.
13282 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
13283 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
13284 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
13285 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
13286 }
13287
13288 return DeducedType;
13289}
13290
13292 Expr *Init) {
13293 assert(!Init || !Init->containsErrors());
13295 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
13296 VDecl->getSourceRange(), DirectInit, Init);
13297 if (DeducedType.isNull()) {
13298 VDecl->setInvalidDecl();
13299 return true;
13300 }
13301
13302 VDecl->setType(DeducedType);
13303 assert(VDecl->isLinkageValid());
13304
13305 // In ARC, infer lifetime.
13306 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(VDecl))
13307 VDecl->setInvalidDecl();
13308
13309 if (getLangOpts().OpenCL)
13311
13312 if (getLangOpts().HLSL)
13313 HLSL().deduceAddressSpace(VDecl);
13314
13315 // If this is a redeclaration, check that the type we just deduced matches
13316 // the previously declared type.
13317 if (VarDecl *Old = VDecl->getPreviousDecl()) {
13318 // We never need to merge the type, because we cannot form an incomplete
13319 // array of auto, nor deduce such a type.
13320 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
13321 }
13322
13323 // Check the deduced type is valid for a variable declaration.
13325 return VDecl->isInvalidDecl();
13326}
13327
13329 SourceLocation Loc) {
13330 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
13331 Init = EWC->getSubExpr();
13332
13333 if (auto *CE = dyn_cast<ConstantExpr>(Init))
13334 Init = CE->getSubExpr();
13335
13336 QualType InitType = Init->getType();
13339 "shouldn't be called if type doesn't have a non-trivial C struct");
13340 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
13341 for (auto *I : ILE->inits()) {
13342 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
13343 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
13344 continue;
13345 SourceLocation SL = I->getExprLoc();
13346 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
13347 }
13348 return;
13349 }
13350
13353 checkNonTrivialCUnion(InitType, Loc,
13355 NTCUK_Init);
13356 } else {
13357 // Assume all other explicit initializers involving copying some existing
13358 // object.
13359 // TODO: ignore any explicit initializers where we can guarantee
13360 // copy-elision.
13363 NTCUK_Copy);
13364 }
13365}
13366
13367namespace {
13368
13369bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
13370 // Ignore unavailable fields. A field can be marked as unavailable explicitly
13371 // in the source code or implicitly by the compiler if it is in a union
13372 // defined in a system header and has non-trivial ObjC ownership
13373 // qualifications. We don't want those fields to participate in determining
13374 // whether the containing union is non-trivial.
13375 return FD->hasAttr<UnavailableAttr>();
13376}
13377
13378struct DiagNonTrivalCUnionDefaultInitializeVisitor
13379 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13380 void> {
13381 using Super =
13382 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13383 void>;
13384
13385 DiagNonTrivalCUnionDefaultInitializeVisitor(
13386 QualType OrigTy, SourceLocation OrigLoc,
13387 NonTrivialCUnionContext UseContext, Sema &S)
13388 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13389
13390 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
13391 const FieldDecl *FD, bool InNonTrivialUnion) {
13392 if (const auto *AT = S.Context.getAsArrayType(QT))
13393 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13394 InNonTrivialUnion);
13395 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
13396 }
13397
13398 void visitARCStrong(QualType QT, const FieldDecl *FD,
13399 bool InNonTrivialUnion) {
13400 if (InNonTrivialUnion)
13401 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13402 << 1 << 0 << QT << FD->getName();
13403 }
13404
13405 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13406 if (InNonTrivialUnion)
13407 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13408 << 1 << 0 << QT << FD->getName();
13409 }
13410
13411 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13412 const auto *RD = QT->castAsRecordDecl();
13413 if (RD->isUnion()) {
13414 if (OrigLoc.isValid()) {
13415 bool IsUnion = false;
13416 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13417 IsUnion = OrigRD->isUnion();
13418 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13419 << 0 << OrigTy << IsUnion << UseContext;
13420 // Reset OrigLoc so that this diagnostic is emitted only once.
13421 OrigLoc = SourceLocation();
13422 }
13423 InNonTrivialUnion = true;
13424 }
13425
13426 if (InNonTrivialUnion)
13427 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13428 << 0 << 0 << QT.getUnqualifiedType() << "";
13429
13430 for (const FieldDecl *FD : RD->fields())
13431 if (!shouldIgnoreForRecordTriviality(FD))
13432 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13433 }
13434
13435 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13436
13437 // The non-trivial C union type or the struct/union type that contains a
13438 // non-trivial C union.
13439 QualType OrigTy;
13440 SourceLocation OrigLoc;
13441 NonTrivialCUnionContext UseContext;
13442 Sema &S;
13443};
13444
13445struct DiagNonTrivalCUnionDestructedTypeVisitor
13446 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
13447 using Super =
13448 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
13449
13450 DiagNonTrivalCUnionDestructedTypeVisitor(QualType OrigTy,
13451 SourceLocation OrigLoc,
13452 NonTrivialCUnionContext UseContext,
13453 Sema &S)
13454 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13455
13456 void visitWithKind(QualType::DestructionKind DK, QualType QT,
13457 const FieldDecl *FD, bool InNonTrivialUnion) {
13458 if (const auto *AT = S.Context.getAsArrayType(QT))
13459 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13460 InNonTrivialUnion);
13461 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
13462 }
13463
13464 void visitARCStrong(QualType QT, const FieldDecl *FD,
13465 bool InNonTrivialUnion) {
13466 if (InNonTrivialUnion)
13467 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13468 << 1 << 1 << QT << FD->getName();
13469 }
13470
13471 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13472 if (InNonTrivialUnion)
13473 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13474 << 1 << 1 << QT << FD->getName();
13475 }
13476
13477 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13478 const auto *RD = QT->castAsRecordDecl();
13479 if (RD->isUnion()) {
13480 if (OrigLoc.isValid()) {
13481 bool IsUnion = false;
13482 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13483 IsUnion = OrigRD->isUnion();
13484 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13485 << 1 << OrigTy << IsUnion << UseContext;
13486 // Reset OrigLoc so that this diagnostic is emitted only once.
13487 OrigLoc = SourceLocation();
13488 }
13489 InNonTrivialUnion = true;
13490 }
13491
13492 if (InNonTrivialUnion)
13493 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13494 << 0 << 1 << QT.getUnqualifiedType() << "";
13495
13496 for (const FieldDecl *FD : RD->fields())
13497 if (!shouldIgnoreForRecordTriviality(FD))
13498 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13499 }
13500
13501 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13502 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
13503 bool InNonTrivialUnion) {}
13504
13505 // The non-trivial C union type or the struct/union type that contains a
13506 // non-trivial C union.
13507 QualType OrigTy;
13508 SourceLocation OrigLoc;
13509 NonTrivialCUnionContext UseContext;
13510 Sema &S;
13511};
13512
13513struct DiagNonTrivalCUnionCopyVisitor
13514 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
13515 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
13516
13517 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
13518 NonTrivialCUnionContext UseContext, Sema &S)
13519 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13520
13521 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
13522 const FieldDecl *FD, bool InNonTrivialUnion) {
13523 if (const auto *AT = S.Context.getAsArrayType(QT))
13524 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13525 InNonTrivialUnion);
13526 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
13527 }
13528
13529 void visitARCStrong(QualType QT, const FieldDecl *FD,
13530 bool InNonTrivialUnion) {
13531 if (InNonTrivialUnion)
13532 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13533 << 1 << 2 << QT << FD->getName();
13534 }
13535
13536 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13537 if (InNonTrivialUnion)
13538 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13539 << 1 << 2 << QT << FD->getName();
13540 }
13541
13542 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13543 const auto *RD = QT->castAsRecordDecl();
13544 if (RD->isUnion()) {
13545 if (OrigLoc.isValid()) {
13546 bool IsUnion = false;
13547 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13548 IsUnion = OrigRD->isUnion();
13549 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13550 << 2 << OrigTy << IsUnion << UseContext;
13551 // Reset OrigLoc so that this diagnostic is emitted only once.
13552 OrigLoc = SourceLocation();
13553 }
13554 InNonTrivialUnion = true;
13555 }
13556
13557 if (InNonTrivialUnion)
13558 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13559 << 0 << 2 << QT.getUnqualifiedType() << "";
13560
13561 for (const FieldDecl *FD : RD->fields())
13562 if (!shouldIgnoreForRecordTriviality(FD))
13563 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13564 }
13565
13566 void visitPtrAuth(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13567 if (InNonTrivialUnion)
13568 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13569 << 1 << 2 << QT << FD->getName();
13570 }
13571
13572 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13573 const FieldDecl *FD, bool InNonTrivialUnion) {}
13574 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13575 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13576 bool InNonTrivialUnion) {}
13577
13578 // The non-trivial C union type or the struct/union type that contains a
13579 // non-trivial C union.
13580 QualType OrigTy;
13581 SourceLocation OrigLoc;
13582 NonTrivialCUnionContext UseContext;
13583 Sema &S;
13584};
13585
13586} // namespace
13587
13589 NonTrivialCUnionContext UseContext,
13590 unsigned NonTrivialKind) {
13594 "shouldn't be called if type doesn't have a non-trivial C union");
13595
13596 if ((NonTrivialKind & NTCUK_Init) &&
13598 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
13599 .visit(QT, nullptr, false);
13600 if ((NonTrivialKind & NTCUK_Destruct) &&
13602 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
13603 .visit(QT, nullptr, false);
13604 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
13605 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
13606 .visit(QT, nullptr, false);
13607}
13608
13610 const VarDecl *Dcl) {
13611 if (!getLangOpts().CPlusPlus)
13612 return false;
13613
13614 // We only need to warn if the definition is in a header file, so wait to
13615 // diagnose until we've seen the definition.
13616 if (!Dcl->isThisDeclarationADefinition())
13617 return false;
13618
13619 // If an object is defined in a source file, its definition can't get
13620 // duplicated since it will never appear in more than one TU.
13622 return false;
13623
13624 // If the variable we're looking at is a static local, then we actually care
13625 // about the properties of the function containing it.
13626 const ValueDecl *Target = Dcl;
13627 // VarDecls and FunctionDecls have different functions for checking
13628 // inline-ness, and whether they were originally templated, so we have to
13629 // call the appropriate functions manually.
13630 bool TargetIsInline = Dcl->isInline();
13631 bool TargetWasTemplated =
13633
13634 // Update the Target and TargetIsInline property if necessary
13635 if (Dcl->isStaticLocal()) {
13636 const DeclContext *Ctx = Dcl->getDeclContext();
13637 if (!Ctx)
13638 return false;
13639
13640 const FunctionDecl *FunDcl =
13641 dyn_cast_if_present<FunctionDecl>(Ctx->getNonClosureAncestor());
13642 if (!FunDcl)
13643 return false;
13644
13645 Target = FunDcl;
13646 // IsInlined() checks for the C++ inline property
13647 TargetIsInline = FunDcl->isInlined();
13648 TargetWasTemplated =
13650 }
13651
13652 // Non-inline functions/variables can only legally appear in one TU
13653 // unless they were part of a template. Unfortunately, making complex
13654 // template instantiations visible is infeasible in practice, since
13655 // everything the template depends on also has to be visible. To avoid
13656 // giving impractical-to-fix warnings, don't warn if we're inside
13657 // something that was templated, even on inline stuff.
13658 if (!TargetIsInline || TargetWasTemplated)
13659 return false;
13660
13661 // If the object isn't hidden, the dynamic linker will prevent duplication.
13662 clang::LinkageInfo Lnk = Target->getLinkageAndVisibility();
13663
13664 // The target is "hidden" (from the dynamic linker) if:
13665 // 1. On posix, it has hidden visibility, or
13666 // 2. On windows, it has no import/export annotation, and neither does the
13667 // class which directly contains it.
13668 if (Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
13669 if (Target->hasAttr<DLLExportAttr>() || Target->hasAttr<DLLImportAttr>())
13670 return false;
13671
13672 // If the variable isn't directly annotated, check to see if it's a member
13673 // of an annotated class.
13674 const CXXRecordDecl *Ctx =
13675 dyn_cast<CXXRecordDecl>(Target->getDeclContext());
13676 if (Ctx && (Ctx->hasAttr<DLLExportAttr>() || Ctx->hasAttr<DLLImportAttr>()))
13677 return false;
13678
13679 } else if (Lnk.getVisibility() != HiddenVisibility) {
13680 // Posix case
13681 return false;
13682 }
13683
13684 // If the obj doesn't have external linkage, it's supposed to be duplicated.
13686 return false;
13687
13688 return true;
13689}
13690
13691// Determine whether the object seems mutable for the purpose of diagnosing
13692// possible unique object duplication, i.e. non-const-qualified, and
13693// not an always-constant type like a function.
13694// Not perfect: doesn't account for mutable members, for example, or
13695// elements of container types.
13696// For nested pointers, any individual level being non-const is sufficient.
13697static bool looksMutable(QualType T, const ASTContext &Ctx) {
13698 T = T.getNonReferenceType();
13699 if (T->isFunctionType())
13700 return false;
13701 if (!T.isConstant(Ctx))
13702 return true;
13703 if (T->isPointerType())
13704 return looksMutable(T->getPointeeType(), Ctx);
13705 return false;
13706}
13707
13709 // If this object has external linkage and hidden visibility, it might be
13710 // duplicated when built into a shared library, which causes problems if it's
13711 // mutable (since the copies won't be in sync) or its initialization has side
13712 // effects (since it will run once per copy instead of once globally).
13713
13714 // Don't diagnose if we're inside a template, because it's not practical to
13715 // fix the warning in most cases.
13716 if (!VD->isTemplated() &&
13718
13719 QualType Type = VD->getType();
13720 if (looksMutable(Type, VD->getASTContext())) {
13721 Diag(VD->getLocation(), diag::warn_possible_object_duplication_mutable)
13722 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
13723 }
13724
13725 // To keep false positives low, only warn if we're certain that the
13726 // initializer has side effects. Don't warn on operator new, since a mutable
13727 // pointer will trigger the previous warning, and an immutable pointer
13728 // getting duplicated just results in a little extra memory usage.
13729 const Expr *Init = VD->getAnyInitializer();
13730 if (Init &&
13731 Init->HasSideEffects(VD->getASTContext(),
13732 /*IncludePossibleEffects=*/false) &&
13733 !isa<CXXNewExpr>(Init->IgnoreParenImpCasts())) {
13734 Diag(Init->getExprLoc(), diag::warn_possible_object_duplication_init)
13735 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
13736 }
13737 }
13738}
13739
13741 // If there is no declaration, there was an error parsing it. Just ignore
13742 // the initializer.
13743 if (!RealDecl) {
13744 return;
13745 }
13746
13747 if (auto *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
13748 if (!Method->isInvalidDecl()) {
13749 // Pure-specifiers are handled in ActOnPureSpecifier.
13750 Diag(Method->getLocation(), diag::err_member_function_initialization)
13751 << Method->getDeclName() << Init->getSourceRange();
13752 Method->setInvalidDecl();
13753 }
13754 return;
13755 }
13756
13757 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
13758 if (!VDecl) {
13759 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
13760 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
13761 RealDecl->setInvalidDecl();
13762 return;
13763 }
13764
13765 if (VDecl->isInvalidDecl()) {
13766 ExprResult Recovery =
13767 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), {Init});
13768 if (Expr *E = Recovery.get())
13769 VDecl->setInit(E);
13770 return;
13771 }
13772
13773 // WebAssembly tables can't be used to initialise a variable.
13774 if (!Init->getType().isNull() && Init->getType()->isWebAssemblyTableType()) {
13775 Diag(Init->getExprLoc(), diag::err_wasm_table_art) << 0;
13776 VDecl->setInvalidDecl();
13777 return;
13778 }
13779
13780 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
13781 if (VDecl->getType()->isUndeducedType()) {
13782 if (Init->containsErrors()) {
13783 // Invalidate the decl as we don't know the type for recovery-expr yet.
13784 RealDecl->setInvalidDecl();
13785 VDecl->setInit(Init);
13786 return;
13787 }
13788
13790 return;
13791 }
13792
13793 // dllimport cannot be used on variable definitions.
13794 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
13795 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
13796 VDecl->setInvalidDecl();
13797 return;
13798 }
13799
13800 // C99 6.7.8p5. If the declaration of an identifier has block scope, and
13801 // the identifier has external or internal linkage, the declaration shall
13802 // have no initializer for the identifier.
13803 // C++14 [dcl.init]p5 is the same restriction for C++.
13804 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
13805 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
13806 VDecl->setInvalidDecl();
13807 return;
13808 }
13809
13810 if (!VDecl->getType()->isDependentType()) {
13811 // A definition must end up with a complete type, which means it must be
13812 // complete with the restriction that an array type might be completed by
13813 // the initializer; note that later code assumes this restriction.
13814 QualType BaseDeclType = VDecl->getType();
13815 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
13816 BaseDeclType = Array->getElementType();
13817 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
13818 diag::err_typecheck_decl_incomplete_type)) {
13819 RealDecl->setInvalidDecl();
13820 return;
13821 }
13822
13823 // The variable can not have an abstract class type.
13824 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
13825 diag::err_abstract_type_in_decl,
13827 VDecl->setInvalidDecl();
13828 }
13829
13830 // C++ [module.import/6] external definitions are not permitted in header
13831 // units.
13832 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
13833 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
13834 VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() &&
13835 !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(VDecl) &&
13837 Diag(VDecl->getLocation(), diag::err_extern_def_in_header_unit);
13838 VDecl->setInvalidDecl();
13839 }
13840
13841 // If adding the initializer will turn this declaration into a definition,
13842 // and we already have a definition for this variable, diagnose or otherwise
13843 // handle the situation.
13844 if (VarDecl *Def = VDecl->getDefinition())
13845 if (Def != VDecl &&
13846 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
13848 checkVarDeclRedefinition(Def, VDecl))
13849 return;
13850
13851 if (getLangOpts().CPlusPlus) {
13852 // C++ [class.static.data]p4
13853 // If a static data member is of const integral or const
13854 // enumeration type, its declaration in the class definition can
13855 // specify a constant-initializer which shall be an integral
13856 // constant expression (5.19). In that case, the member can appear
13857 // in integral constant expressions. The member shall still be
13858 // defined in a namespace scope if it is used in the program and the
13859 // namespace scope definition shall not contain an initializer.
13860 //
13861 // We already performed a redefinition check above, but for static
13862 // data members we also need to check whether there was an in-class
13863 // declaration with an initializer.
13864 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
13865 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
13866 << VDecl->getDeclName();
13867 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
13868 diag::note_previous_initializer)
13869 << 0;
13870 return;
13871 }
13872
13874 VDecl->setInvalidDecl();
13875 return;
13876 }
13877 }
13878
13879 // If the variable has an initializer and local storage, check whether
13880 // anything jumps over the initialization.
13881 if (VDecl->hasLocalStorage())
13883
13884 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
13885 // a kernel function cannot be initialized."
13886 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
13887 Diag(VDecl->getLocation(), diag::err_local_cant_init);
13888 VDecl->setInvalidDecl();
13889 return;
13890 }
13891
13892 // The LoaderUninitialized attribute acts as a definition (of undef).
13893 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
13894 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
13895 VDecl->setInvalidDecl();
13896 return;
13897 }
13898
13899 if (getLangOpts().HLSL)
13900 if (!HLSL().handleInitialization(VDecl, Init))
13901 return;
13902
13903 // Get the decls type and save a reference for later, since
13904 // CheckInitializerTypes may change it.
13905 QualType DclT = VDecl->getType(), SavT = DclT;
13906
13907 // Expressions default to 'id' when we're in a debugger
13908 // and we are assigning it to a variable of Objective-C pointer type.
13909 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
13910 Init->getType() == Context.UnknownAnyTy) {
13912 if (!Result.isUsable()) {
13913 VDecl->setInvalidDecl();
13914 return;
13915 }
13916 Init = Result.get();
13917 }
13918
13919 // Perform the initialization.
13920 bool InitializedFromParenListExpr = false;
13921 bool IsParenListInit = false;
13922 if (!VDecl->isInvalidDecl()) {
13925 VDecl->getLocation(), DirectInit, Init);
13926
13927 MultiExprArg Args = Init;
13928 if (auto *CXXDirectInit = dyn_cast<ParenListExpr>(Init)) {
13929 Args =
13930 MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
13931 InitializedFromParenListExpr = true;
13932 } else if (auto *CXXDirectInit = dyn_cast<CXXParenListInitExpr>(Init)) {
13933 Args = CXXDirectInit->getInitExprs();
13934 InitializedFromParenListExpr = true;
13935 }
13936
13937 InitializationSequence InitSeq(*this, Entity, Kind, Args,
13938 /*TopLevelOfInitList=*/false,
13939 /*TreatUnavailableAsInvalid=*/false);
13940 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
13941 if (!Result.isUsable()) {
13942 // If the provided initializer fails to initialize the var decl,
13943 // we attach a recovery expr for better recovery.
13944 auto RecoveryExpr =
13945 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
13946 if (RecoveryExpr.get())
13947 VDecl->setInit(RecoveryExpr.get());
13948 // In general, for error recovery purposes, the initializer doesn't play
13949 // part in the valid bit of the declaration. There are a few exceptions:
13950 // 1) if the var decl has a deduced auto type, and the type cannot be
13951 // deduced by an invalid initializer;
13952 // 2) if the var decl is a decomposition decl with a non-deduced type,
13953 // and the initialization fails (e.g. `int [a] = {1, 2};`);
13954 // Case 1) was already handled elsewhere.
13955 if (isa<DecompositionDecl>(VDecl)) // Case 2)
13956 VDecl->setInvalidDecl();
13957 return;
13958 }
13959
13960 Init = Result.getAs<Expr>();
13961 IsParenListInit = !InitSeq.steps().empty() &&
13962 InitSeq.step_begin()->Kind ==
13964 QualType VDeclType = VDecl->getType();
13965 if (!Init->getType().isNull() && !Init->getType()->isDependentType() &&
13966 !VDeclType->isDependentType() &&
13967 Context.getAsIncompleteArrayType(VDeclType) &&
13968 Context.getAsIncompleteArrayType(Init->getType())) {
13969 // Bail out if it is not possible to deduce array size from the
13970 // initializer.
13971 Diag(VDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)
13972 << VDeclType;
13973 VDecl->setInvalidDecl();
13974 return;
13975 }
13976 }
13977
13978 // Check for self-references within variable initializers.
13979 // Variables declared within a function/method body (except for references)
13980 // are handled by a dataflow analysis.
13981 // This is undefined behavior in C++, but valid in C.
13982 if (getLangOpts().CPlusPlus)
13983 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
13984 VDecl->getType()->isReferenceType())
13985 CheckSelfReference(*this, RealDecl, Init, DirectInit);
13986
13987 // If the type changed, it means we had an incomplete type that was
13988 // completed by the initializer. For example:
13989 // int ary[] = { 1, 3, 5 };
13990 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
13991 if (!VDecl->isInvalidDecl() && (DclT != SavT))
13992 VDecl->setType(DclT);
13993
13994 if (!VDecl->isInvalidDecl()) {
13995 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
13996
13997 if (VDecl->hasAttr<BlocksAttr>())
13998 ObjC().checkRetainCycles(VDecl, Init);
13999
14000 // It is safe to assign a weak reference into a strong variable.
14001 // Although this code can still have problems:
14002 // id x = self.weakProp;
14003 // id y = self.weakProp;
14004 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14005 // paths through the function. This should be revisited if
14006 // -Wrepeated-use-of-weak is made flow-sensitive.
14007 if (FunctionScopeInfo *FSI = getCurFunction())
14008 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
14010 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
14011 Init->getBeginLoc()))
14012 FSI->markSafeWeakUse(Init);
14013 }
14014
14015 // The initialization is usually a full-expression.
14016 //
14017 // FIXME: If this is a braced initialization of an aggregate, it is not
14018 // an expression, and each individual field initializer is a separate
14019 // full-expression. For instance, in:
14020 //
14021 // struct Temp { ~Temp(); };
14022 // struct S { S(Temp); };
14023 // struct T { S a, b; } t = { Temp(), Temp() }
14024 //
14025 // we should destroy the first Temp before constructing the second.
14028 /*DiscardedValue*/ false, VDecl->isConstexpr());
14029 if (!Result.isUsable()) {
14030 VDecl->setInvalidDecl();
14031 return;
14032 }
14033 Init = Result.get();
14034
14035 // Attach the initializer to the decl.
14036 VDecl->setInit(Init);
14037
14038 if (VDecl->isLocalVarDecl()) {
14039 // Don't check the initializer if the declaration is malformed.
14040 if (VDecl->isInvalidDecl()) {
14041 // do nothing
14042
14043 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
14044 // This is true even in C++ for OpenCL.
14045 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
14047
14048 // Otherwise, C++ does not restrict the initializer.
14049 } else if (getLangOpts().CPlusPlus) {
14050 // do nothing
14051
14052 // C99 6.7.8p4: All the expressions in an initializer for an object that has
14053 // static storage duration shall be constant expressions or string literals.
14054 } else if (VDecl->getStorageClass() == SC_Static) {
14056
14057 // C89 is stricter than C99 for aggregate initializers.
14058 // C89 6.5.7p3: All the expressions [...] in an initializer list
14059 // for an object that has aggregate or union type shall be
14060 // constant expressions.
14061 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
14063 CheckForConstantInitializer(Init, diag::ext_aggregate_init_not_constant);
14064 }
14065
14066 if (auto *E = dyn_cast<ExprWithCleanups>(Init))
14067 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
14068 if (VDecl->hasLocalStorage())
14069 BE->getBlockDecl()->setCanAvoidCopyToHeap();
14070 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
14071 VDecl->getLexicalDeclContext()->isRecord()) {
14072 // This is an in-class initialization for a static data member, e.g.,
14073 //
14074 // struct S {
14075 // static const int value = 17;
14076 // };
14077
14078 // C++ [class.mem]p4:
14079 // A member-declarator can contain a constant-initializer only
14080 // if it declares a static member (9.4) of const integral or
14081 // const enumeration type, see 9.4.2.
14082 //
14083 // C++11 [class.static.data]p3:
14084 // If a non-volatile non-inline const static data member is of integral
14085 // or enumeration type, its declaration in the class definition can
14086 // specify a brace-or-equal-initializer in which every initializer-clause
14087 // that is an assignment-expression is a constant expression. A static
14088 // data member of literal type can be declared in the class definition
14089 // with the constexpr specifier; if so, its declaration shall specify a
14090 // brace-or-equal-initializer in which every initializer-clause that is
14091 // an assignment-expression is a constant expression.
14092
14093 // Do nothing on dependent types.
14094 if (DclT->isDependentType()) {
14095
14096 // Allow any 'static constexpr' members, whether or not they are of literal
14097 // type. We separately check that every constexpr variable is of literal
14098 // type.
14099 } else if (VDecl->isConstexpr()) {
14100
14101 // Require constness.
14102 } else if (!DclT.isConstQualified()) {
14103 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
14104 << Init->getSourceRange();
14105 VDecl->setInvalidDecl();
14106
14107 // We allow integer constant expressions in all cases.
14108 } else if (DclT->isIntegralOrEnumerationType()) {
14110 // In C++11, a non-constexpr const static data member with an
14111 // in-class initializer cannot be volatile.
14112 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
14113
14114 // We allow foldable floating-point constants as an extension.
14115 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
14116 // In C++98, this is a GNU extension. In C++11, it is not, but we support
14117 // it anyway and provide a fixit to add the 'constexpr'.
14118 if (getLangOpts().CPlusPlus11) {
14119 Diag(VDecl->getLocation(),
14120 diag::ext_in_class_initializer_float_type_cxx11)
14121 << DclT << Init->getSourceRange();
14122 Diag(VDecl->getBeginLoc(),
14123 diag::note_in_class_initializer_float_type_cxx11)
14124 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
14125 } else {
14126 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
14127 << DclT << Init->getSourceRange();
14128
14129 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
14130 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
14131 << Init->getSourceRange();
14132 VDecl->setInvalidDecl();
14133 }
14134 }
14135
14136 // Suggest adding 'constexpr' in C++11 for literal types.
14137 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
14138 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
14139 << DclT << Init->getSourceRange()
14140 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
14141 VDecl->setConstexpr(true);
14142
14143 } else {
14144 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
14145 << DclT << Init->getSourceRange();
14146 VDecl->setInvalidDecl();
14147 }
14148 } else if (VDecl->isFileVarDecl()) {
14149 // In C, extern is typically used to avoid tentative definitions when
14150 // declaring variables in headers, but adding an initializer makes it a
14151 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
14152 // In C++, extern is often used to give implicitly static const variables
14153 // external linkage, so don't warn in that case. If selectany is present,
14154 // this might be header code intended for C and C++ inclusion, so apply the
14155 // C++ rules.
14156 if (VDecl->getStorageClass() == SC_Extern &&
14157 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
14158 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
14159 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
14161 Diag(VDecl->getLocation(), diag::warn_extern_init);
14162
14163 // In Microsoft C++ mode, a const variable defined in namespace scope has
14164 // external linkage by default if the variable is declared with
14165 // __declspec(dllexport).
14166 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14168 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
14169 VDecl->setStorageClass(SC_Extern);
14170
14171 // C99 6.7.8p4. All file scoped initializers need to be constant.
14172 // Avoid duplicate diagnostics for constexpr variables.
14173 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
14174 !VDecl->isConstexpr())
14176 }
14177
14178 QualType InitType = Init->getType();
14179 if (!InitType.isNull() &&
14183
14184 // We will represent direct-initialization similarly to copy-initialization:
14185 // int x(1); -as-> int x = 1;
14186 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
14187 //
14188 // Clients that want to distinguish between the two forms, can check for
14189 // direct initializer using VarDecl::getInitStyle().
14190 // A major benefit is that clients that don't particularly care about which
14191 // exactly form was it (like the CodeGen) can handle both cases without
14192 // special case code.
14193
14194 // C++ 8.5p11:
14195 // The form of initialization (using parentheses or '=') matters
14196 // when the entity being initialized has class type.
14197 if (InitializedFromParenListExpr) {
14198 assert(DirectInit && "Call-style initializer must be direct init.");
14199 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
14201 } else if (DirectInit) {
14202 // This must be list-initialization. No other way is direct-initialization.
14204 }
14205
14206 if (LangOpts.OpenMP &&
14207 (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&
14208 VDecl->isFileVarDecl())
14209 DeclsToCheckForDeferredDiags.insert(VDecl);
14211
14212 if (LangOpts.OpenACC && !InitType.isNull())
14213 OpenACC().ActOnVariableInit(VDecl, InitType);
14214}
14215
14217 // Our main concern here is re-establishing invariants like "a
14218 // variable's type is either dependent or complete".
14219 if (!D || D->isInvalidDecl()) return;
14220
14221 VarDecl *VD = dyn_cast<VarDecl>(D);
14222 if (!VD) return;
14223
14224 // Bindings are not usable if we can't make sense of the initializer.
14225 if (auto *DD = dyn_cast<DecompositionDecl>(D))
14226 for (auto *BD : DD->bindings())
14227 BD->setInvalidDecl();
14228
14229 // Auto types are meaningless if we can't make sense of the initializer.
14230 if (VD->getType()->isUndeducedType()) {
14231 D->setInvalidDecl();
14232 return;
14233 }
14234
14235 QualType Ty = VD->getType();
14236 if (Ty->isDependentType()) return;
14237
14238 // Require a complete type.
14240 Context.getBaseElementType(Ty),
14241 diag::err_typecheck_decl_incomplete_type)) {
14242 VD->setInvalidDecl();
14243 return;
14244 }
14245
14246 // Require a non-abstract type.
14247 if (RequireNonAbstractType(VD->getLocation(), Ty,
14248 diag::err_abstract_type_in_decl,
14250 VD->setInvalidDecl();
14251 return;
14252 }
14253
14254 // Don't bother complaining about constructors or destructors,
14255 // though.
14256}
14257
14259 // If there is no declaration, there was an error parsing it. Just ignore it.
14260 if (!RealDecl)
14261 return;
14262
14263 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
14264 QualType Type = Var->getType();
14265
14266 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
14267 if (isa<DecompositionDecl>(RealDecl)) {
14268 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
14269 Var->setInvalidDecl();
14270 return;
14271 }
14272
14273 if (Type->isUndeducedType() &&
14274 DeduceVariableDeclarationType(Var, false, nullptr))
14275 return;
14276
14277 // C++11 [class.static.data]p3: A static data member can be declared with
14278 // the constexpr specifier; if so, its declaration shall specify
14279 // a brace-or-equal-initializer.
14280 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
14281 // the definition of a variable [...] or the declaration of a static data
14282 // member.
14283 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
14284 !Var->isThisDeclarationADemotedDefinition()) {
14285 if (Var->isStaticDataMember()) {
14286 // C++1z removes the relevant rule; the in-class declaration is always
14287 // a definition there.
14288 if (!getLangOpts().CPlusPlus17 &&
14289 !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14290 Diag(Var->getLocation(),
14291 diag::err_constexpr_static_mem_var_requires_init)
14292 << Var;
14293 Var->setInvalidDecl();
14294 return;
14295 }
14296 } else {
14297 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
14298 Var->setInvalidDecl();
14299 return;
14300 }
14301 }
14302
14303 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
14304 // be initialized.
14305 if (!Var->isInvalidDecl() &&
14306 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
14307 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
14308 bool HasConstExprDefaultConstructor = false;
14309 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14310 for (auto *Ctor : RD->ctors()) {
14311 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
14312 Ctor->getMethodQualifiers().getAddressSpace() ==
14314 HasConstExprDefaultConstructor = true;
14315 }
14316 }
14317 }
14318 if (!HasConstExprDefaultConstructor) {
14319 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
14320 Var->setInvalidDecl();
14321 return;
14322 }
14323 }
14324
14325 // HLSL variable with the `vk::constant_id` attribute must be initialized.
14326 if (!Var->isInvalidDecl() && Var->hasAttr<HLSLVkConstantIdAttr>()) {
14327 Diag(Var->getLocation(), diag::err_specialization_const);
14328 Var->setInvalidDecl();
14329 return;
14330 }
14331
14332 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
14333 if (Var->getStorageClass() == SC_Extern) {
14334 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
14335 << Var;
14336 Var->setInvalidDecl();
14337 return;
14338 }
14339 if (RequireCompleteType(Var->getLocation(), Var->getType(),
14340 diag::err_typecheck_decl_incomplete_type)) {
14341 Var->setInvalidDecl();
14342 return;
14343 }
14344 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14345 if (!RD->hasTrivialDefaultConstructor()) {
14346 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
14347 Var->setInvalidDecl();
14348 return;
14349 }
14350 }
14351 // The declaration is uninitialized, no need for further checks.
14352 return;
14353 }
14354
14355 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
14356 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
14357 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
14358 checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
14360 NTCUK_Init);
14361
14362 switch (DefKind) {
14364 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
14365 break;
14366
14367 // We have an out-of-line definition of a static data member
14368 // that has an in-class initializer, so we type-check this like
14369 // a declaration.
14370 //
14371 [[fallthrough]];
14372
14374 // It's only a declaration.
14375
14376 // Block scope. C99 6.7p7: If an identifier for an object is
14377 // declared with no linkage (C99 6.2.2p6), the type for the
14378 // object shall be complete.
14379 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
14380 !Var->hasLinkage() && !Var->isInvalidDecl() &&
14381 RequireCompleteType(Var->getLocation(), Type,
14382 diag::err_typecheck_decl_incomplete_type))
14383 Var->setInvalidDecl();
14384
14385 // Make sure that the type is not abstract.
14386 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14387 RequireNonAbstractType(Var->getLocation(), Type,
14388 diag::err_abstract_type_in_decl,
14390 Var->setInvalidDecl();
14391 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14392 Var->getStorageClass() == SC_PrivateExtern) {
14393 Diag(Var->getLocation(), diag::warn_private_extern);
14394 Diag(Var->getLocation(), diag::note_private_extern);
14395 }
14396
14397 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
14398 !Var->isInvalidDecl())
14399 ExternalDeclarations.push_back(Var);
14400
14401 return;
14402
14404 // File scope. C99 6.9.2p2: A declaration of an identifier for an
14405 // object that has file scope without an initializer, and without a
14406 // storage-class specifier or with the storage-class specifier "static",
14407 // constitutes a tentative definition. Note: A tentative definition with
14408 // external linkage is valid (C99 6.2.2p5).
14409 if (!Var->isInvalidDecl()) {
14410 if (const IncompleteArrayType *ArrayT
14411 = Context.getAsIncompleteArrayType(Type)) {
14413 Var->getLocation(), ArrayT->getElementType(),
14414 diag::err_array_incomplete_or_sizeless_type))
14415 Var->setInvalidDecl();
14416 }
14417 if (Var->getStorageClass() == SC_Static) {
14418 // C99 6.9.2p3: If the declaration of an identifier for an object is
14419 // a tentative definition and has internal linkage (C99 6.2.2p3), the
14420 // declared type shall not be an incomplete type.
14421 // NOTE: code such as the following
14422 // static struct s;
14423 // struct s { int a; };
14424 // is accepted by gcc. Hence here we issue a warning instead of
14425 // an error and we do not invalidate the static declaration.
14426 // NOTE: to avoid multiple warnings, only check the first declaration.
14427 if (Var->isFirstDecl())
14428 RequireCompleteType(Var->getLocation(), Type,
14429 diag::ext_typecheck_decl_incomplete_type,
14430 Type->isArrayType());
14431 }
14432 }
14433
14434 // Record the tentative definition; we're done.
14435 if (!Var->isInvalidDecl())
14436 TentativeDefinitions.push_back(Var);
14437 return;
14438 }
14439
14440 // Provide a specific diagnostic for uninitialized variable definitions
14441 // with incomplete array type, unless it is a global unbounded HLSL resource
14442 // array.
14443 if (Type->isIncompleteArrayType() &&
14444 !(getLangOpts().HLSL && Var->hasGlobalStorage() &&
14446 if (Var->isConstexpr())
14447 Diag(Var->getLocation(), diag::err_constexpr_var_requires_const_init)
14448 << Var;
14449 else
14450 Diag(Var->getLocation(),
14451 diag::err_typecheck_incomplete_array_needs_initializer);
14452 Var->setInvalidDecl();
14453 return;
14454 }
14455
14456 // Provide a specific diagnostic for uninitialized variable
14457 // definitions with reference type.
14458 if (Type->isReferenceType()) {
14459 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
14460 << Var << SourceRange(Var->getLocation(), Var->getLocation());
14461 return;
14462 }
14463
14464 // Do not attempt to type-check the default initializer for a
14465 // variable with dependent type.
14466 if (Type->isDependentType())
14467 return;
14468
14469 if (Var->isInvalidDecl())
14470 return;
14471
14472 if (!Var->hasAttr<AliasAttr>()) {
14473 if (RequireCompleteType(Var->getLocation(),
14474 Context.getBaseElementType(Type),
14475 diag::err_typecheck_decl_incomplete_type)) {
14476 Var->setInvalidDecl();
14477 return;
14478 }
14479 } else {
14480 return;
14481 }
14482
14483 // The variable can not have an abstract class type.
14484 if (RequireNonAbstractType(Var->getLocation(), Type,
14485 diag::err_abstract_type_in_decl,
14487 Var->setInvalidDecl();
14488 return;
14489 }
14490
14491 // In C, if the definition is const-qualified and has no initializer, it
14492 // is left uninitialized unless it has static or thread storage duration.
14493 if (!getLangOpts().CPlusPlus && Type.isConstQualified()) {
14494 unsigned DiagID = diag::warn_default_init_const_unsafe;
14495 if (Var->getStorageDuration() == SD_Static ||
14496 Var->getStorageDuration() == SD_Thread)
14497 DiagID = diag::warn_default_init_const;
14498
14499 bool EmitCppCompat = !Diags.isIgnored(
14500 diag::warn_cxx_compat_hack_fake_diagnostic_do_not_emit,
14501 Var->getLocation());
14502
14503 Diag(Var->getLocation(), DiagID) << Type << EmitCppCompat;
14504 }
14505
14506 // Check for jumps past the implicit initializer. C++0x
14507 // clarifies that this applies to a "variable with automatic
14508 // storage duration", not a "local variable".
14509 // C++11 [stmt.dcl]p3
14510 // A program that jumps from a point where a variable with automatic
14511 // storage duration is not in scope to a point where it is in scope is
14512 // ill-formed unless the variable has scalar type, class type with a
14513 // trivial default constructor and a trivial destructor, a cv-qualified
14514 // version of one of these types, or an array of one of the preceding
14515 // types and is declared without an initializer.
14516 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
14517 if (const auto *CXXRecord =
14518 Context.getBaseElementType(Type)->getAsCXXRecordDecl()) {
14519 // Mark the function (if we're in one) for further checking even if the
14520 // looser rules of C++11 do not require such checks, so that we can
14521 // diagnose incompatibilities with C++98.
14522 if (!CXXRecord->isPOD())
14524 }
14525 }
14526 // In OpenCL, we can't initialize objects in the __local address space,
14527 // even implicitly, so don't synthesize an implicit initializer.
14528 if (getLangOpts().OpenCL &&
14529 Var->getType().getAddressSpace() == LangAS::opencl_local)
14530 return;
14531
14532 // Handle HLSL uninitialized decls
14533 if (getLangOpts().HLSL && HLSL().ActOnUninitializedVarDecl(Var))
14534 return;
14535
14536 // HLSL input variables are expected to be externally initialized, even
14537 // when marked `static`.
14538 if (getLangOpts().HLSL &&
14539 Var->getType().getAddressSpace() == LangAS::hlsl_input)
14540 return;
14541
14542 // C++03 [dcl.init]p9:
14543 // If no initializer is specified for an object, and the
14544 // object is of (possibly cv-qualified) non-POD class type (or
14545 // array thereof), the object shall be default-initialized; if
14546 // the object is of const-qualified type, the underlying class
14547 // type shall have a user-declared default
14548 // constructor. Otherwise, if no initializer is specified for
14549 // a non- static object, the object and its subobjects, if
14550 // any, have an indeterminate initial value); if the object
14551 // or any of its subobjects are of const-qualified type, the
14552 // program is ill-formed.
14553 // C++0x [dcl.init]p11:
14554 // If no initializer is specified for an object, the object is
14555 // default-initialized; [...].
14558 = InitializationKind::CreateDefault(Var->getLocation());
14559
14560 InitializationSequence InitSeq(*this, Entity, Kind, {});
14561 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, {});
14562
14563 if (Init.get()) {
14564 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
14565 // This is important for template substitution.
14566 Var->setInitStyle(VarDecl::CallInit);
14567 } else if (Init.isInvalid()) {
14568 // If default-init fails, attach a recovery-expr initializer to track
14569 // that initialization was attempted and failed.
14570 auto RecoveryExpr =
14571 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
14572 if (RecoveryExpr.get())
14573 Var->setInit(RecoveryExpr.get());
14574 }
14575
14577 }
14578}
14579
14581 // If there is no declaration, there was an error parsing it. Ignore it.
14582 if (!D)
14583 return;
14584
14585 VarDecl *VD = dyn_cast<VarDecl>(D);
14586 if (!VD) {
14587 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
14588 D->setInvalidDecl();
14589 return;
14590 }
14591
14592 VD->setCXXForRangeDecl(true);
14593
14594 // for-range-declaration cannot be given a storage class specifier.
14595 int Error = -1;
14596 switch (VD->getStorageClass()) {
14597 case SC_None:
14598 break;
14599 case SC_Extern:
14600 Error = 0;
14601 break;
14602 case SC_Static:
14603 Error = 1;
14604 break;
14605 case SC_PrivateExtern:
14606 Error = 2;
14607 break;
14608 case SC_Auto:
14609 Error = 3;
14610 break;
14611 case SC_Register:
14612 Error = 4;
14613 break;
14614 }
14615
14616 // for-range-declaration cannot be given a storage class specifier con't.
14617 switch (VD->getTSCSpec()) {
14618 case TSCS_thread_local:
14619 Error = 6;
14620 break;
14621 case TSCS___thread:
14622 case TSCS__Thread_local:
14623 case TSCS_unspecified:
14624 break;
14625 }
14626
14627 if (Error != -1) {
14628 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
14629 << VD << Error;
14630 D->setInvalidDecl();
14631 }
14632}
14633
14635 IdentifierInfo *Ident,
14636 ParsedAttributes &Attrs) {
14637 // C++1y [stmt.iter]p1:
14638 // A range-based for statement of the form
14639 // for ( for-range-identifier : for-range-initializer ) statement
14640 // is equivalent to
14641 // for ( auto&& for-range-identifier : for-range-initializer ) statement
14642 DeclSpec DS(Attrs.getPool().getFactory());
14643
14644 const char *PrevSpec;
14645 unsigned DiagID;
14646 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
14648
14650 D.SetIdentifier(Ident, IdentLoc);
14651 D.takeAttributes(Attrs);
14652
14653 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
14654 IdentLoc);
14655 Decl *Var = ActOnDeclarator(S, D);
14656 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
14658 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
14659 Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
14660 : IdentLoc);
14661}
14662
14664 if (var->isInvalidDecl()) return;
14665
14667
14668 if (getLangOpts().OpenCL) {
14669 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
14670 // initialiser
14671 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
14672 !var->hasInit()) {
14673 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
14674 << 1 /*Init*/;
14675 var->setInvalidDecl();
14676 return;
14677 }
14678 }
14679
14680 // In Objective-C, don't allow jumps past the implicit initialization of a
14681 // local retaining variable.
14682 if (getLangOpts().ObjC &&
14683 var->hasLocalStorage()) {
14684 switch (var->getType().getObjCLifetime()) {
14688 break;
14689
14693 break;
14694 }
14695 }
14696
14697 if (var->hasLocalStorage() &&
14698 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
14700
14701 // Warn about externally-visible variables being defined without a
14702 // prior declaration. We only want to do this for global
14703 // declarations, but we also specifically need to avoid doing it for
14704 // class members because the linkage of an anonymous class can
14705 // change if it's later given a typedef name.
14706 if (var->isThisDeclarationADefinition() &&
14707 var->getDeclContext()->getRedeclContext()->isFileContext() &&
14708 var->isExternallyVisible() && var->hasLinkage() &&
14709 !var->isInline() && !var->getDescribedVarTemplate() &&
14710 var->getStorageClass() != SC_Register &&
14712 !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
14713 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
14714 var->getLocation())) {
14715 // Find a previous declaration that's not a definition.
14716 VarDecl *prev = var->getPreviousDecl();
14717 while (prev && prev->isThisDeclarationADefinition())
14718 prev = prev->getPreviousDecl();
14719
14720 if (!prev) {
14721 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
14722 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14723 << /* variable */ 0;
14724 }
14725 }
14726
14727 // Cache the result of checking for constant initialization.
14728 std::optional<bool> CacheHasConstInit;
14729 const Expr *CacheCulprit = nullptr;
14730 auto checkConstInit = [&]() mutable {
14731 const Expr *Init = var->getInit();
14732 if (Init->isInstantiationDependent())
14733 return true;
14734
14735 if (!CacheHasConstInit)
14736 CacheHasConstInit = var->getInit()->isConstantInitializer(
14737 Context, var->getType()->isReferenceType(), &CacheCulprit);
14738 return *CacheHasConstInit;
14739 };
14740
14741 if (var->getTLSKind() == VarDecl::TLS_Static) {
14742 if (var->getType().isDestructedType()) {
14743 // GNU C++98 edits for __thread, [basic.start.term]p3:
14744 // The type of an object with thread storage duration shall not
14745 // have a non-trivial destructor.
14746 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
14748 Diag(var->getLocation(), diag::note_use_thread_local);
14749 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
14750 if (!checkConstInit()) {
14751 // GNU C++98 edits for __thread, [basic.start.init]p4:
14752 // An object of thread storage duration shall not require dynamic
14753 // initialization.
14754 // FIXME: Need strict checking here.
14755 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
14756 << CacheCulprit->getSourceRange();
14758 Diag(var->getLocation(), diag::note_use_thread_local);
14759 }
14760 }
14761 }
14762
14763
14764 if (!var->getType()->isStructureType() && var->hasInit() &&
14765 isa<InitListExpr>(var->getInit())) {
14766 const auto *ILE = cast<InitListExpr>(var->getInit());
14767 unsigned NumInits = ILE->getNumInits();
14768 if (NumInits > 2)
14769 for (unsigned I = 0; I < NumInits; ++I) {
14770 const auto *Init = ILE->getInit(I);
14771 if (!Init)
14772 break;
14773 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14774 if (!SL)
14775 break;
14776
14777 unsigned NumConcat = SL->getNumConcatenated();
14778 // Diagnose missing comma in string array initialization.
14779 // Do not warn when all the elements in the initializer are concatenated
14780 // together. Do not warn for macros too.
14781 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
14782 bool OnlyOneMissingComma = true;
14783 for (unsigned J = I + 1; J < NumInits; ++J) {
14784 const auto *Init = ILE->getInit(J);
14785 if (!Init)
14786 break;
14787 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14788 if (!SLJ || SLJ->getNumConcatenated() > 1) {
14789 OnlyOneMissingComma = false;
14790 break;
14791 }
14792 }
14793
14794 if (OnlyOneMissingComma) {
14796 for (unsigned i = 0; i < NumConcat - 1; ++i)
14797 Hints.push_back(FixItHint::CreateInsertion(
14798 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
14799
14800 Diag(SL->getStrTokenLoc(1),
14801 diag::warn_concatenated_literal_array_init)
14802 << Hints;
14803 Diag(SL->getBeginLoc(),
14804 diag::note_concatenated_string_literal_silence);
14805 }
14806 // In any case, stop now.
14807 break;
14808 }
14809 }
14810 }
14811
14812
14813 QualType type = var->getType();
14814
14815 if (var->hasAttr<BlocksAttr>())
14817
14818 Expr *Init = var->getInit();
14819 bool GlobalStorage = var->hasGlobalStorage();
14820 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
14821 QualType baseType = Context.getBaseElementType(type);
14822 bool HasConstInit = true;
14823
14824 if (getLangOpts().C23 && var->isConstexpr() && !Init)
14825 Diag(var->getLocation(), diag::err_constexpr_var_requires_const_init)
14826 << var;
14827
14828 // Check whether the initializer is sufficiently constant.
14829 if ((getLangOpts().CPlusPlus || (getLangOpts().C23 && var->isConstexpr())) &&
14830 !type->isDependentType() && Init && !Init->isValueDependent() &&
14831 (GlobalStorage || var->isConstexpr() ||
14832 var->mightBeUsableInConstantExpressions(Context))) {
14833 // If this variable might have a constant initializer or might be usable in
14834 // constant expressions, check whether or not it actually is now. We can't
14835 // do this lazily, because the result might depend on things that change
14836 // later, such as which constexpr functions happen to be defined.
14838 if (!getLangOpts().CPlusPlus11 && !getLangOpts().C23) {
14839 // Prior to C++11, in contexts where a constant initializer is required,
14840 // the set of valid constant initializers is described by syntactic rules
14841 // in [expr.const]p2-6.
14842 // FIXME: Stricter checking for these rules would be useful for constinit /
14843 // -Wglobal-constructors.
14844 HasConstInit = checkConstInit();
14845
14846 // Compute and cache the constant value, and remember that we have a
14847 // constant initializer.
14848 if (HasConstInit) {
14849 if (var->isStaticDataMember() && !var->isInline() &&
14850 var->getLexicalDeclContext()->isRecord() &&
14851 type->isIntegralOrEnumerationType()) {
14852 // In C++98, in-class initialization for a static data member must
14853 // be an integer constant expression.
14854 if (!Init->isIntegerConstantExpr(Context)) {
14855 Diag(Init->getExprLoc(),
14856 diag::ext_in_class_initializer_non_constant)
14857 << Init->getSourceRange();
14858 }
14859 }
14860 (void)var->checkForConstantInitialization(Notes);
14861 Notes.clear();
14862 } else if (CacheCulprit) {
14863 Notes.emplace_back(CacheCulprit->getExprLoc(),
14864 PDiag(diag::note_invalid_subexpr_in_const_expr));
14865 Notes.back().second << CacheCulprit->getSourceRange();
14866 }
14867 } else {
14868 // Evaluate the initializer to see if it's a constant initializer.
14869 HasConstInit = var->checkForConstantInitialization(Notes);
14870 }
14871
14872 if (HasConstInit) {
14873 // FIXME: Consider replacing the initializer with a ConstantExpr.
14874 } else if (var->isConstexpr()) {
14875 SourceLocation DiagLoc = var->getLocation();
14876 // If the note doesn't add any useful information other than a source
14877 // location, fold it into the primary diagnostic.
14878 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14879 diag::note_invalid_subexpr_in_const_expr) {
14880 DiagLoc = Notes[0].first;
14881 Notes.clear();
14882 }
14883 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
14884 << var << Init->getSourceRange();
14885 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
14886 Diag(Notes[I].first, Notes[I].second);
14887 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
14888 auto *Attr = var->getAttr<ConstInitAttr>();
14889 Diag(var->getLocation(), diag::err_require_constant_init_failed)
14890 << Init->getSourceRange();
14891 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
14892 << Attr->getRange() << Attr->isConstinit();
14893 for (auto &it : Notes)
14894 Diag(it.first, it.second);
14895 } else if (var->isStaticDataMember() && !var->isInline() &&
14896 var->getLexicalDeclContext()->isRecord()) {
14897 Diag(var->getLocation(), diag::err_in_class_initializer_non_constant)
14898 << Init->getSourceRange();
14899 for (auto &it : Notes)
14900 Diag(it.first, it.second);
14901 var->setInvalidDecl();
14902 } else if (IsGlobal &&
14903 !getDiagnostics().isIgnored(diag::warn_global_constructor,
14904 var->getLocation())) {
14905 // Warn about globals which don't have a constant initializer. Don't
14906 // warn about globals with a non-trivial destructor because we already
14907 // warned about them.
14908 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
14909 if (!(RD && !RD->hasTrivialDestructor())) {
14910 // checkConstInit() here permits trivial default initialization even in
14911 // C++11 onwards, where such an initializer is not a constant initializer
14912 // but nonetheless doesn't require a global constructor.
14913 if (!checkConstInit())
14914 Diag(var->getLocation(), diag::warn_global_constructor)
14915 << Init->getSourceRange();
14916 }
14917 }
14918 }
14919
14920 // Apply section attributes and pragmas to global variables.
14921 if (GlobalStorage && var->isThisDeclarationADefinition() &&
14923 PragmaStack<StringLiteral *> *Stack = nullptr;
14924 int SectionFlags = ASTContext::PSF_Read;
14925 bool MSVCEnv =
14926 Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment();
14927 std::optional<QualType::NonConstantStorageReason> Reason;
14928 if (HasConstInit &&
14929 !(Reason = var->getType().isNonConstantStorage(Context, true, false))) {
14930 Stack = &ConstSegStack;
14931 } else {
14932 SectionFlags |= ASTContext::PSF_Write;
14933 Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack;
14934 }
14935 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
14936 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
14937 SectionFlags |= ASTContext::PSF_Implicit;
14938 UnifySection(SA->getName(), SectionFlags, var);
14939 } else if (Stack->CurrentValue) {
14940 if (Stack != &ConstSegStack && MSVCEnv &&
14941 ConstSegStack.CurrentValue != ConstSegStack.DefaultValue &&
14942 var->getType().isConstQualified()) {
14943 assert((!Reason || Reason != QualType::NonConstantStorageReason::
14944 NonConstNonReferenceType) &&
14945 "This case should've already been handled elsewhere");
14946 Diag(var->getLocation(), diag::warn_section_msvc_compat)
14947 << var << ConstSegStack.CurrentValue << (int)(!HasConstInit
14949 : *Reason);
14950 }
14951 SectionFlags |= ASTContext::PSF_Implicit;
14952 auto SectionName = Stack->CurrentValue->getString();
14953 var->addAttr(SectionAttr::CreateImplicit(Context, SectionName,
14954 Stack->CurrentPragmaLocation,
14955 SectionAttr::Declspec_allocate));
14956 if (UnifySection(SectionName, SectionFlags, var))
14957 var->dropAttr<SectionAttr>();
14958 }
14959
14960 // Apply the init_seg attribute if this has an initializer. If the
14961 // initializer turns out to not be dynamic, we'll end up ignoring this
14962 // attribute.
14963 if (CurInitSeg && var->getInit())
14964 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
14965 CurInitSegLoc));
14966 }
14967
14968 // All the following checks are C++ only.
14969 if (!getLangOpts().CPlusPlus) {
14970 // If this variable must be emitted, add it as an initializer for the
14971 // current module.
14972 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14973 Context.addModuleInitializer(ModuleScopes.back().Module, var);
14974 return;
14975 }
14976
14978
14979 // Require the destructor.
14980 if (!type->isDependentType())
14981 if (auto *RD = baseType->getAsCXXRecordDecl())
14983
14984 // If this variable must be emitted, add it as an initializer for the current
14985 // module.
14986 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14987 Context.addModuleInitializer(ModuleScopes.back().Module, var);
14988
14989 // Build the bindings if this is a structured binding declaration.
14990 if (auto *DD = dyn_cast<DecompositionDecl>(var))
14992}
14993
14995 assert(VD->isStaticLocal());
14996
14997 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14998
14999 // Find outermost function when VD is in lambda function.
15000 while (FD && !getDLLAttr(FD) &&
15001 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
15002 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
15003 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
15004 }
15005
15006 if (!FD)
15007 return;
15008
15009 // Static locals inherit dll attributes from their function.
15010 if (Attr *A = getDLLAttr(FD)) {
15011 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
15012 NewAttr->setInherited(true);
15013 VD->addAttr(NewAttr);
15014 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
15015 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
15016 NewAttr->setInherited(true);
15017 VD->addAttr(NewAttr);
15018
15019 // Export this function to enforce exporting this static variable even
15020 // if it is not used in this compilation unit.
15021 if (!FD->hasAttr<DLLExportAttr>())
15022 FD->addAttr(NewAttr);
15023
15024 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
15025 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
15026 NewAttr->setInherited(true);
15027 VD->addAttr(NewAttr);
15028 }
15029}
15030
15032 assert(VD->getTLSKind());
15033
15034 // Perform TLS alignment check here after attributes attached to the variable
15035 // which may affect the alignment have been processed. Only perform the check
15036 // if the target has a maximum TLS alignment (zero means no constraints).
15037 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
15038 // Protect the check so that it's not performed on dependent types and
15039 // dependent alignments (we can't determine the alignment in that case).
15040 if (!VD->hasDependentAlignment()) {
15041 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
15042 if (Context.getDeclAlign(VD) > MaxAlignChars) {
15043 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
15044 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
15045 << (unsigned)MaxAlignChars.getQuantity();
15046 }
15047 }
15048 }
15049}
15050
15052 // Note that we are no longer parsing the initializer for this declaration.
15053 ParsingInitForAutoVars.erase(ThisDecl);
15054
15055 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
15056 if (!VD)
15057 return;
15058
15059 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
15061 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
15062 if (PragmaClangBSSSection.Valid)
15063 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
15064 Context, PragmaClangBSSSection.SectionName,
15065 PragmaClangBSSSection.PragmaLocation));
15066 if (PragmaClangDataSection.Valid)
15067 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
15068 Context, PragmaClangDataSection.SectionName,
15069 PragmaClangDataSection.PragmaLocation));
15070 if (PragmaClangRodataSection.Valid)
15071 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
15072 Context, PragmaClangRodataSection.SectionName,
15073 PragmaClangRodataSection.PragmaLocation));
15074 if (PragmaClangRelroSection.Valid)
15075 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
15076 Context, PragmaClangRelroSection.SectionName,
15077 PragmaClangRelroSection.PragmaLocation));
15078 }
15079
15080 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
15081 for (auto *BD : DD->bindings()) {
15083 }
15084 }
15085
15086 CheckInvalidBuiltinCountedByRef(VD->getInit(),
15088
15089 checkAttributesAfterMerging(*this, *VD);
15090
15091 if (VD->isStaticLocal())
15093
15094 if (VD->getTLSKind())
15096
15097 // Perform check for initializers of device-side global variables.
15098 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
15099 // 7.5). We must also apply the same checks to all __shared__
15100 // variables whether they are local or not. CUDA also allows
15101 // constant initializers for __constant__ and __device__ variables.
15102 if (getLangOpts().CUDA)
15104
15105 // Grab the dllimport or dllexport attribute off of the VarDecl.
15106 const InheritableAttr *DLLAttr = getDLLAttr(VD);
15107
15108 // Imported static data members cannot be defined out-of-line.
15109 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
15110 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
15112 // We allow definitions of dllimport class template static data members
15113 // with a warning.
15116 bool IsClassTemplateMember =
15118 Context->getDescribedClassTemplate();
15119
15120 Diag(VD->getLocation(),
15121 IsClassTemplateMember
15122 ? diag::warn_attribute_dllimport_static_field_definition
15123 : diag::err_attribute_dllimport_static_field_definition);
15124 Diag(IA->getLocation(), diag::note_attribute);
15125 if (!IsClassTemplateMember)
15126 VD->setInvalidDecl();
15127 }
15128 }
15129
15130 // dllimport/dllexport variables cannot be thread local, their TLS index
15131 // isn't exported with the variable.
15132 if (DLLAttr && VD->getTLSKind()) {
15133 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
15134 if (F && getDLLAttr(F)) {
15135 assert(VD->isStaticLocal());
15136 // But if this is a static local in a dlimport/dllexport function, the
15137 // function will never be inlined, which means the var would never be
15138 // imported, so having it marked import/export is safe.
15139 } else {
15140 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
15141 << DLLAttr;
15142 VD->setInvalidDecl();
15143 }
15144 }
15145
15146 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
15147 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
15148 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
15149 << Attr;
15150 VD->dropAttr<UsedAttr>();
15151 }
15152 }
15153 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
15154 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
15155 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
15156 << Attr;
15157 VD->dropAttr<RetainAttr>();
15158 }
15159 }
15160
15161 const DeclContext *DC = VD->getDeclContext();
15162 // If there's a #pragma GCC visibility in scope, and this isn't a class
15163 // member, set the visibility of this variable.
15166
15167 // FIXME: Warn on unused var template partial specializations.
15170
15171 // Now we have parsed the initializer and can update the table of magic
15172 // tag values.
15173 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
15175 return;
15176
15177 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
15178 const Expr *MagicValueExpr = VD->getInit();
15179 if (!MagicValueExpr) {
15180 continue;
15181 }
15182 std::optional<llvm::APSInt> MagicValueInt;
15183 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
15184 Diag(I->getRange().getBegin(),
15185 diag::err_type_tag_for_datatype_not_ice)
15186 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15187 continue;
15188 }
15189 if (MagicValueInt->getActiveBits() > 64) {
15190 Diag(I->getRange().getBegin(),
15191 diag::err_type_tag_for_datatype_too_large)
15192 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15193 continue;
15194 }
15195 uint64_t MagicValue = MagicValueInt->getZExtValue();
15196 RegisterTypeTagForDatatype(I->getArgumentKind(),
15197 MagicValue,
15198 I->getMatchingCType(),
15199 I->getLayoutCompatible(),
15200 I->getMustBeNull());
15201 }
15202}
15203
15205 auto *VD = dyn_cast<VarDecl>(DD);
15206 return VD && !VD->getType()->hasAutoForTrailingReturnType();
15207}
15208
15210 ArrayRef<Decl *> Group) {
15212
15213 if (DS.isTypeSpecOwned())
15214 Decls.push_back(DS.getRepAsDecl());
15215
15216 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
15217 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
15218 bool DiagnosedMultipleDecomps = false;
15219 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
15220 bool DiagnosedNonDeducedAuto = false;
15221
15222 for (Decl *D : Group) {
15223 if (!D)
15224 continue;
15225 // Check if the Decl has been declared in '#pragma omp declare target'
15226 // directive and has static storage duration.
15227 if (auto *VD = dyn_cast<VarDecl>(D);
15228 LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&
15229 VD->hasGlobalStorage())
15231 // For declarators, there are some additional syntactic-ish checks we need
15232 // to perform.
15233 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
15234 if (!FirstDeclaratorInGroup)
15235 FirstDeclaratorInGroup = DD;
15236 if (!FirstDecompDeclaratorInGroup)
15237 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
15238 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
15239 !hasDeducedAuto(DD))
15240 FirstNonDeducedAutoInGroup = DD;
15241
15242 if (FirstDeclaratorInGroup != DD) {
15243 // A decomposition declaration cannot be combined with any other
15244 // declaration in the same group.
15245 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
15246 Diag(FirstDecompDeclaratorInGroup->getLocation(),
15247 diag::err_decomp_decl_not_alone)
15248 << FirstDeclaratorInGroup->getSourceRange()
15249 << DD->getSourceRange();
15250 DiagnosedMultipleDecomps = true;
15251 }
15252
15253 // A declarator that uses 'auto' in any way other than to declare a
15254 // variable with a deduced type cannot be combined with any other
15255 // declarator in the same group.
15256 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
15257 Diag(FirstNonDeducedAutoInGroup->getLocation(),
15258 diag::err_auto_non_deduced_not_alone)
15259 << FirstNonDeducedAutoInGroup->getType()
15261 << FirstDeclaratorInGroup->getSourceRange()
15262 << DD->getSourceRange();
15263 DiagnosedNonDeducedAuto = true;
15264 }
15265 }
15266 }
15267
15268 Decls.push_back(D);
15269 }
15270
15272 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
15273 handleTagNumbering(Tag, S);
15274 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
15276 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
15277 }
15278 }
15279
15280 return BuildDeclaratorGroup(Decls);
15281}
15282
15285 // C++14 [dcl.spec.auto]p7: (DR1347)
15286 // If the type that replaces the placeholder type is not the same in each
15287 // deduction, the program is ill-formed.
15288 if (Group.size() > 1) {
15289 QualType Deduced;
15290 VarDecl *DeducedDecl = nullptr;
15291 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
15292 VarDecl *D = dyn_cast<VarDecl>(Group[i]);
15293 if (!D || D->isInvalidDecl())
15294 break;
15295 DeducedType *DT = D->getType()->getContainedDeducedType();
15296 if (!DT || DT->getDeducedType().isNull())
15297 continue;
15298 if (Deduced.isNull()) {
15299 Deduced = DT->getDeducedType();
15300 DeducedDecl = D;
15301 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
15302 auto *AT = dyn_cast<AutoType>(DT);
15303 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
15304 diag::err_auto_different_deductions)
15305 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
15306 << DeducedDecl->getDeclName() << DT->getDeducedType()
15307 << D->getDeclName();
15308 if (DeducedDecl->hasInit())
15309 Dia << DeducedDecl->getInit()->getSourceRange();
15310 if (D->getInit())
15311 Dia << D->getInit()->getSourceRange();
15312 D->setInvalidDecl();
15313 break;
15314 }
15315 }
15316 }
15317
15319
15320 return DeclGroupPtrTy::make(
15321 DeclGroupRef::Create(Context, Group.data(), Group.size()));
15322}
15323
15327
15329 // Don't parse the comment if Doxygen diagnostics are ignored.
15330 if (Group.empty() || !Group[0])
15331 return;
15332
15333 if (Diags.isIgnored(diag::warn_doc_param_not_found,
15334 Group[0]->getLocation()) &&
15335 Diags.isIgnored(diag::warn_unknown_comment_command_name,
15336 Group[0]->getLocation()))
15337 return;
15338
15339 if (Group.size() >= 2) {
15340 // This is a decl group. Normally it will contain only declarations
15341 // produced from declarator list. But in case we have any definitions or
15342 // additional declaration references:
15343 // 'typedef struct S {} S;'
15344 // 'typedef struct S *S;'
15345 // 'struct S *pS;'
15346 // FinalizeDeclaratorGroup adds these as separate declarations.
15347 Decl *MaybeTagDecl = Group[0];
15348 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
15349 Group = Group.slice(1);
15350 }
15351 }
15352
15353 // FIMXE: We assume every Decl in the group is in the same file.
15354 // This is false when preprocessor constructs the group from decls in
15355 // different files (e. g. macros or #include).
15356 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
15357}
15358
15360 // Check that there are no default arguments inside the type of this
15361 // parameter.
15362 if (getLangOpts().CPlusPlus)
15364
15365 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
15366 if (D.getCXXScopeSpec().isSet()) {
15367 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
15368 << D.getCXXScopeSpec().getRange();
15369 }
15370
15371 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
15372 // simple identifier except [...irrelevant cases...].
15373 switch (D.getName().getKind()) {
15375 break;
15376
15384 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
15386 break;
15387
15390 // GetNameForDeclarator would not produce a useful name in this case.
15391 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
15392 break;
15393 }
15394}
15395
15397 // This only matters in C.
15398 if (getLangOpts().CPlusPlus)
15399 return;
15400
15401 // This only matters if the declaration has a type.
15402 const auto *VD = dyn_cast<ValueDecl>(D);
15403 if (!VD)
15404 return;
15405
15406 // Get the type, this only matters for tag types.
15407 QualType QT = VD->getType();
15408 const auto *TD = QT->getAsTagDecl();
15409 if (!TD)
15410 return;
15411
15412 // Check if the tag declaration is lexically declared somewhere different
15413 // from the lexical declaration of the given object, then it will be hidden
15414 // in C++ and we should warn on it.
15415 if (!TD->getLexicalParent()->LexicallyEncloses(D->getLexicalDeclContext())) {
15416 unsigned Kind = TD->isEnum() ? 2 : TD->isUnion() ? 1 : 0;
15417 Diag(D->getLocation(), diag::warn_decl_hidden_in_cpp) << Kind;
15418 Diag(TD->getLocation(), diag::note_declared_at);
15419 }
15420}
15421
15423 SourceLocation ExplicitThisLoc) {
15424 if (!ExplicitThisLoc.isValid())
15425 return;
15426 assert(S.getLangOpts().CPlusPlus &&
15427 "explicit parameter in non-cplusplus mode");
15428 if (!S.getLangOpts().CPlusPlus23)
15429 S.Diag(ExplicitThisLoc, diag::err_cxx20_deducing_this)
15430 << P->getSourceRange();
15431
15432 // C++2b [dcl.fct/7] An explicit object parameter shall not be a function
15433 // parameter pack.
15434 if (P->isParameterPack()) {
15435 S.Diag(P->getBeginLoc(), diag::err_explicit_object_parameter_pack)
15436 << P->getSourceRange();
15437 return;
15438 }
15439 P->setExplicitObjectParameterLoc(ExplicitThisLoc);
15440 if (LambdaScopeInfo *LSI = S.getCurLambda())
15441 LSI->ExplicitObjectParameter = P;
15442}
15443
15445 SourceLocation ExplicitThisLoc) {
15446 const DeclSpec &DS = D.getDeclSpec();
15447
15448 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
15449 // C2y 6.7.7.4p4: A parameter declaration shall not specify a void type,
15450 // except for the special case of a single unnamed parameter of type void
15451 // with no storage class specifier, no type qualifier, and no following
15452 // ellipsis terminator.
15453 // Clang applies the C2y rules for 'register void' in all C language modes,
15454 // same as GCC, because it's questionable what that could possibly mean.
15455
15456 // C++03 [dcl.stc]p2 also permits 'auto'.
15457 StorageClass SC = SC_None;
15459 SC = SC_Register;
15460 // In C++11, the 'register' storage class specifier is deprecated.
15461 // In C++17, it is not allowed, but we tolerate it as an extension.
15462 if (getLangOpts().CPlusPlus11) {
15464 ? diag::ext_register_storage_class
15465 : diag::warn_deprecated_register)
15467 } else if (!getLangOpts().CPlusPlus &&
15469 D.getNumTypeObjects() == 0) {
15471 diag::err_invalid_storage_class_in_func_decl)
15474 }
15475 } else if (getLangOpts().CPlusPlus &&
15477 SC = SC_Auto;
15480 diag::err_invalid_storage_class_in_func_decl);
15482 }
15483
15485 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
15487 if (DS.isInlineSpecified())
15488 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
15489 << getLangOpts().CPlusPlus17;
15490 if (DS.hasConstexprSpecifier())
15491 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
15492 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
15493
15495
15497
15499 QualType parmDeclType = TInfo->getType();
15500
15501 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
15502 const IdentifierInfo *II = D.getIdentifier();
15503 if (II) {
15506 LookupName(R, S);
15507 if (!R.empty()) {
15508 NamedDecl *PrevDecl = *R.begin();
15509 if (R.isSingleResult() && PrevDecl->isTemplateParameter()) {
15510 // Maybe we will complain about the shadowed template parameter.
15512 // Just pretend that we didn't see the previous declaration.
15513 PrevDecl = nullptr;
15514 }
15515 if (PrevDecl && S->isDeclScope(PrevDecl)) {
15516 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
15517 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15518 // Recover by removing the name
15519 II = nullptr;
15520 D.SetIdentifier(nullptr, D.getIdentifierLoc());
15521 D.setInvalidType(true);
15522 }
15523 }
15524 }
15525
15526 // Incomplete resource arrays are not allowed as function parameters in HLSL
15527 if (getLangOpts().HLSL && parmDeclType->isIncompleteArrayType() &&
15528 parmDeclType->isHLSLResourceRecordArray()) {
15530 diag::err_hlsl_incomplete_resource_array_in_function_param);
15531 D.setInvalidType(true);
15532 }
15533
15534 // Temporarily put parameter variables in the translation unit, not
15535 // the enclosing context. This prevents them from accidentally
15536 // looking like class members in C++.
15537 ParmVarDecl *New =
15538 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
15539 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
15540
15541 if (D.isInvalidType())
15542 New->setInvalidDecl();
15543
15544 CheckExplicitObjectParameter(*this, New, ExplicitThisLoc);
15545
15546 assert(S->isFunctionPrototypeScope());
15547 assert(S->getFunctionPrototypeDepth() >= 1);
15548 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
15550
15552
15553 // Add the parameter declaration into this scope.
15554 S->AddDecl(New);
15555 if (II)
15556 IdResolver.AddDecl(New);
15557
15559
15561 Diag(New->getLocation(), diag::err_module_private_local)
15564
15565 if (New->hasAttr<BlocksAttr>()) {
15566 Diag(New->getLocation(), diag::err_block_on_nonlocal);
15567 }
15568
15569 if (getLangOpts().OpenCL)
15571
15572 return New;
15573}
15574
15576 SourceLocation Loc,
15577 QualType T) {
15578 /* FIXME: setting StartLoc == Loc.
15579 Would it be worth to modify callers so as to provide proper source
15580 location for the unnamed parameters, embedding the parameter's type? */
15581 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
15582 T, Context.getTrivialTypeSourceInfo(T, Loc),
15583 SC_None, nullptr);
15584 Param->setImplicit();
15585 return Param;
15586}
15587
15589 // Don't diagnose unused-parameter errors in template instantiations; we
15590 // will already have done so in the template itself.
15592 return;
15593
15594 for (const ParmVarDecl *Parameter : Parameters) {
15595 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
15596 !Parameter->hasAttr<UnusedAttr>() &&
15597 !Parameter->getIdentifier()->isPlaceholder()) {
15598 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
15599 << Parameter->getDeclName();
15600 }
15601 }
15602}
15603
15605 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
15606 if (LangOpts.NumLargeByValueCopy == 0) // No check.
15607 return;
15608
15609 // Warn if the return value is pass-by-value and larger than the specified
15610 // threshold.
15611 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
15612 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
15613 if (Size > LangOpts.NumLargeByValueCopy)
15614 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
15615 }
15616
15617 // Warn if any parameter is pass-by-value and larger than the specified
15618 // threshold.
15619 for (const ParmVarDecl *Parameter : Parameters) {
15620 QualType T = Parameter->getType();
15621 if (T->isDependentType() || !T.isPODType(Context))
15622 continue;
15623 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
15624 if (Size > LangOpts.NumLargeByValueCopy)
15625 Diag(Parameter->getLocation(), diag::warn_parameter_size)
15626 << Parameter << Size;
15627 }
15628}
15629
15631 SourceLocation NameLoc,
15632 const IdentifierInfo *Name, QualType T,
15633 TypeSourceInfo *TSInfo, StorageClass SC) {
15634 // In ARC, infer a lifetime qualifier for appropriate parameter types.
15635 if (getLangOpts().ObjCAutoRefCount &&
15636 T.getObjCLifetime() == Qualifiers::OCL_None &&
15637 T->isObjCLifetimeType()) {
15638
15639 Qualifiers::ObjCLifetime lifetime;
15640
15641 // Special cases for arrays:
15642 // - if it's const, use __unsafe_unretained
15643 // - otherwise, it's an error
15644 if (T->isArrayType()) {
15645 if (!T.isConstQualified()) {
15649 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
15650 else
15651 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
15652 << TSInfo->getTypeLoc().getSourceRange();
15653 }
15655 } else {
15656 lifetime = T->getObjCARCImplicitLifetime();
15657 }
15658 T = Context.getLifetimeQualifiedType(T, lifetime);
15659 }
15660
15661 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
15662 Context.getAdjustedParameterType(T),
15663 TSInfo, SC, nullptr);
15664
15665 // Make a note if we created a new pack in the scope of a lambda, so that
15666 // we know that references to that pack must also be expanded within the
15667 // lambda scope.
15668 if (New->isParameterPack())
15669 if (auto *CSI = getEnclosingLambdaOrBlock())
15670 CSI->LocalPacks.push_back(New);
15671
15672 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
15673 New->getType().hasNonTrivialToPrimitiveCopyCUnion())
15674 checkNonTrivialCUnion(New->getType(), New->getLocation(),
15677
15678 // Parameter declarators cannot be interface types. All ObjC objects are
15679 // passed by reference.
15680 if (T->isObjCObjectType()) {
15681 SourceLocation TypeEndLoc =
15683 Diag(NameLoc,
15684 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
15685 << FixItHint::CreateInsertion(TypeEndLoc, "*");
15686 T = Context.getObjCObjectPointerType(T);
15687 New->setType(T);
15688 }
15689
15690 // __ptrauth is forbidden on parameters.
15691 if (T.getPointerAuth()) {
15692 Diag(NameLoc, diag::err_ptrauth_qualifier_invalid) << T << 1;
15693 New->setInvalidDecl();
15694 }
15695
15696 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
15697 // duration shall not be qualified by an address-space qualifier."
15698 // Since all parameters have automatic store duration, they can not have
15699 // an address space.
15700 if (T.getAddressSpace() != LangAS::Default &&
15701 // OpenCL allows function arguments declared to be an array of a type
15702 // to be qualified with an address space.
15703 !(getLangOpts().OpenCL &&
15704 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&
15705 // WebAssembly allows reference types as parameters. Funcref in particular
15706 // lives in a different address space.
15707 !(T->isFunctionPointerType() &&
15708 T.getAddressSpace() == LangAS::wasm_funcref)) {
15709 Diag(NameLoc, diag::err_arg_with_address_space);
15710 New->setInvalidDecl();
15711 }
15712
15713 // PPC MMA non-pointer types are not allowed as function argument types.
15714 if (Context.getTargetInfo().getTriple().isPPC64() &&
15715 PPC().CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
15716 New->setInvalidDecl();
15717 }
15718
15719 return New;
15720}
15721
15723 SourceLocation LocAfterDecls) {
15725
15726 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
15727 // in the declaration list shall have at least one declarator, those
15728 // declarators shall only declare identifiers from the identifier list, and
15729 // every identifier in the identifier list shall be declared.
15730 //
15731 // C89 3.7.1p5 "If a declarator includes an identifier list, only the
15732 // identifiers it names shall be declared in the declaration list."
15733 //
15734 // This is why we only diagnose in C99 and later. Note, the other conditions
15735 // listed are checked elsewhere.
15736 if (!FTI.hasPrototype) {
15737 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
15738 --i;
15739 if (FTI.Params[i].Param == nullptr) {
15740 if (getLangOpts().C99) {
15741 SmallString<256> Code;
15742 llvm::raw_svector_ostream(Code)
15743 << " int " << FTI.Params[i].Ident->getName() << ";\n";
15744 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
15745 << FTI.Params[i].Ident
15746 << FixItHint::CreateInsertion(LocAfterDecls, Code);
15747 }
15748
15749 // Implicitly declare the argument as type 'int' for lack of a better
15750 // type.
15751 AttributeFactory attrs;
15752 DeclSpec DS(attrs);
15753 const char* PrevSpec; // unused
15754 unsigned DiagID; // unused
15755 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
15756 DiagID, Context.getPrintingPolicy());
15757 // Use the identifier location for the type source range.
15758 DS.SetRangeStart(FTI.Params[i].IdentLoc);
15759 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
15762 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
15763 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
15764 }
15765 }
15766 }
15767}
15768
15769Decl *
15771 MultiTemplateParamsArg TemplateParameterLists,
15772 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
15773 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
15774 assert(D.isFunctionDeclarator() && "Not a function declarator!");
15775 Scope *ParentScope = FnBodyScope->getParent();
15776
15777 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
15778 // we define a non-templated function definition, we will create a declaration
15779 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
15780 // The base function declaration will have the equivalent of an `omp declare
15781 // variant` annotation which specifies the mangled definition as a
15782 // specialization function under the OpenMP context defined as part of the
15783 // `omp begin declare variant`.
15785 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
15787 ParentScope, D, TemplateParameterLists, Bases);
15788
15790 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
15791 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
15792
15793 if (!Bases.empty())
15795 Bases);
15796
15797 return Dcl;
15798}
15799
15801 Consumer.HandleInlineFunctionDefinition(D);
15802}
15803
15805 const FunctionDecl *&PossiblePrototype) {
15806 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
15807 Prev = Prev->getPreviousDecl()) {
15808 // Ignore any declarations that occur in function or method
15809 // scope, because they aren't visible from the header.
15810 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
15811 continue;
15812
15813 PossiblePrototype = Prev;
15814 return Prev->getType()->isFunctionProtoType();
15815 }
15816 return false;
15817}
15818
15819static bool
15821 const FunctionDecl *&PossiblePrototype) {
15822 // Don't warn about invalid declarations.
15823 if (FD->isInvalidDecl())
15824 return false;
15825
15826 // Or declarations that aren't global.
15827 if (!FD->isGlobal())
15828 return false;
15829
15830 // Don't warn about C++ member functions.
15831 if (isa<CXXMethodDecl>(FD))
15832 return false;
15833
15834 // Don't warn about 'main'.
15836 if (IdentifierInfo *II = FD->getIdentifier())
15837 if (II->isStr("main") || II->isStr("efi_main"))
15838 return false;
15839
15840 if (FD->isMSVCRTEntryPoint())
15841 return false;
15842
15843 // Don't warn about inline functions.
15844 if (FD->isInlined())
15845 return false;
15846
15847 // Don't warn about function templates.
15849 return false;
15850
15851 // Don't warn about function template specializations.
15853 return false;
15854
15855 // Don't warn for OpenCL kernels.
15856 if (FD->hasAttr<DeviceKernelAttr>())
15857 return false;
15858
15859 // Don't warn on explicitly deleted functions.
15860 if (FD->isDeleted())
15861 return false;
15862
15863 // Don't warn on implicitly local functions (such as having local-typed
15864 // parameters).
15865 if (!FD->isExternallyVisible())
15866 return false;
15867
15868 // If we were able to find a potential prototype, don't warn.
15869 if (FindPossiblePrototype(FD, PossiblePrototype))
15870 return false;
15871
15872 return true;
15873}
15874
15875void
15877 const FunctionDecl *EffectiveDefinition,
15878 SkipBodyInfo *SkipBody) {
15879 const FunctionDecl *Definition = EffectiveDefinition;
15880 if (!Definition &&
15881 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
15882 return;
15883
15884 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
15885 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
15886 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
15887 // A merged copy of the same function, instantiated as a member of
15888 // the same class, is OK.
15889 if (declaresSameEntity(OrigFD, OrigDef) &&
15890 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
15892 return;
15893 }
15894 }
15895 }
15896
15898 return;
15899
15900 // Don't emit an error when this is redefinition of a typo-corrected
15901 // definition.
15903 return;
15904
15905 bool DefinitionVisible = false;
15906 if (SkipBody && isRedefinitionAllowedFor(Definition, DefinitionVisible) &&
15907 (Definition->getFormalLinkage() == Linkage::Internal ||
15908 Definition->isInlined() || Definition->getDescribedFunctionTemplate() ||
15909 Definition->getNumTemplateParameterLists())) {
15910 SkipBody->ShouldSkip = true;
15911 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
15912 if (!DefinitionVisible) {
15913 if (auto *TD = Definition->getDescribedFunctionTemplate())
15916 }
15917 return;
15918 }
15919
15920 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
15921 Definition->getStorageClass() == SC_Extern)
15922 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
15923 << FD << getLangOpts().CPlusPlus;
15924 else
15925 Diag(FD->getLocation(), diag::err_redefinition) << FD;
15926
15927 Diag(Definition->getLocation(), diag::note_previous_definition);
15928 FD->setInvalidDecl();
15929}
15930
15932 CXXRecordDecl *LambdaClass = CallOperator->getParent();
15933
15935 LSI->CallOperator = CallOperator;
15936 LSI->Lambda = LambdaClass;
15937 LSI->ReturnType = CallOperator->getReturnType();
15938 // When this function is called in situation where the context of the call
15939 // operator is not entered, we set AfterParameterList to false, so that
15940 // `tryCaptureVariable` finds explicit captures in the appropriate context.
15941 // There is also at least a situation as in FinishTemplateArgumentDeduction(),
15942 // where we would set the CurContext to the lambda operator before
15943 // substituting into it. In this case the flag needs to be true such that
15944 // tryCaptureVariable can correctly handle potential captures thereof.
15945 LSI->AfterParameterList = CurContext == CallOperator;
15946
15947 // GLTemplateParameterList is necessary for getCurGenericLambda() which is
15948 // used at the point of dealing with potential captures.
15949 //
15950 // We don't use LambdaClass->isGenericLambda() because this value doesn't
15951 // flip for instantiated generic lambdas, where no FunctionTemplateDecls are
15952 // associated. (Technically, we could recover that list from their
15953 // instantiation patterns, but for now, the GLTemplateParameterList seems
15954 // unnecessary in these cases.)
15955 if (FunctionTemplateDecl *FTD = CallOperator->getDescribedFunctionTemplate())
15956 LSI->GLTemplateParameterList = FTD->getTemplateParameters();
15957 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
15958
15959 if (LCD == LCD_None)
15961 else if (LCD == LCD_ByCopy)
15963 else if (LCD == LCD_ByRef)
15965 DeclarationNameInfo DNI = CallOperator->getNameInfo();
15966
15968 LSI->Mutable = !CallOperator->isConst();
15969 if (CallOperator->isExplicitObjectMemberFunction())
15970 LSI->ExplicitObjectParameter = CallOperator->getParamDecl(0);
15971
15972 // Add the captures to the LSI so they can be noted as already
15973 // captured within tryCaptureVar.
15974 auto I = LambdaClass->field_begin();
15975 for (const auto &C : LambdaClass->captures()) {
15976 if (C.capturesVariable()) {
15977 ValueDecl *VD = C.getCapturedVar();
15978 if (VD->isInitCapture())
15979 CurrentInstantiationScope->InstantiatedLocal(VD, VD);
15980 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
15981 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
15982 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
15983 /*EllipsisLoc*/C.isPackExpansion()
15984 ? C.getEllipsisLoc() : SourceLocation(),
15985 I->getType(), /*Invalid*/false);
15986
15987 } else if (C.capturesThis()) {
15988 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
15989 C.getCaptureKind() == LCK_StarThis);
15990 } else {
15991 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
15992 I->getType());
15993 }
15994 ++I;
15995 }
15996 return LSI;
15997}
15998
16000 SkipBodyInfo *SkipBody,
16001 FnBodyKind BodyKind) {
16002 if (!D) {
16003 // Parsing the function declaration failed in some way. Push on a fake scope
16004 // anyway so we can try to parse the function body.
16007 return D;
16008 }
16009
16010 FunctionDecl *FD = nullptr;
16011
16012 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
16013 FD = FunTmpl->getTemplatedDecl();
16014 else
16015 FD = cast<FunctionDecl>(D);
16016
16017 // Do not push if it is a lambda because one is already pushed when building
16018 // the lambda in ActOnStartOfLambdaDefinition().
16019 if (!isLambdaCallOperator(FD))
16021 FD);
16022
16023 // Check for defining attributes before the check for redefinition.
16024 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
16025 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
16026 FD->dropAttr<AliasAttr>();
16027 FD->setInvalidDecl();
16028 }
16029 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
16030 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
16031 FD->dropAttr<IFuncAttr>();
16032 FD->setInvalidDecl();
16033 }
16034 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
16035 if (Context.getTargetInfo().getTriple().isAArch64() &&
16036 !Context.getTargetInfo().hasFeature("fmv") &&
16037 !Attr->isDefaultVersion()) {
16038 // If function multi versioning disabled skip parsing function body
16039 // defined with non-default target_version attribute
16040 if (SkipBody)
16041 SkipBody->ShouldSkip = true;
16042 return nullptr;
16043 }
16044 }
16045
16046 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
16047 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
16048 Ctor->isDefaultConstructor() &&
16049 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
16050 // If this is an MS ABI dllexport default constructor, instantiate any
16051 // default arguments.
16053 }
16054 }
16055
16056 // See if this is a redefinition. If 'will have body' (or similar) is already
16057 // set, then these checks were already performed when it was set.
16058 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
16060 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
16061
16062 // If we're skipping the body, we're done. Don't enter the scope.
16063 if (SkipBody && SkipBody->ShouldSkip)
16064 return D;
16065 }
16066
16067 // Mark this function as "will have a body eventually". This lets users to
16068 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
16069 // this function.
16070 FD->setWillHaveBody();
16071
16072 // If we are instantiating a generic lambda call operator, push
16073 // a LambdaScopeInfo onto the function stack. But use the information
16074 // that's already been calculated (ActOnLambdaExpr) to prime the current
16075 // LambdaScopeInfo.
16076 // When the template operator is being specialized, the LambdaScopeInfo,
16077 // has to be properly restored so that tryCaptureVariable doesn't try
16078 // and capture any new variables. In addition when calculating potential
16079 // captures during transformation of nested lambdas, it is necessary to
16080 // have the LSI properly restored.
16082 // C++2c 7.5.5.2p17 A member of a closure type shall not be explicitly
16083 // instantiated, explicitly specialized.
16086 Diag(FD->getLocation(), diag::err_lambda_explicit_spec);
16087 FD->setInvalidDecl();
16089 } else {
16090 assert(inTemplateInstantiation() &&
16091 "There should be an active template instantiation on the stack "
16092 "when instantiating a generic lambda!");
16094 }
16095 } else {
16096 // Enter a new function scope
16098 }
16099
16100 // Builtin functions cannot be defined.
16101 if (unsigned BuiltinID = FD->getBuiltinID()) {
16102 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
16103 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
16104 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
16105 FD->setInvalidDecl();
16106 }
16107 }
16108
16109 // The return type of a function definition must be complete (C99 6.9.1p3).
16110 // C++23 [dcl.fct.def.general]/p2
16111 // The type of [...] the return for a function definition
16112 // shall not be a (possibly cv-qualified) class type that is incomplete
16113 // or abstract within the function body unless the function is deleted.
16114 QualType ResultType = FD->getReturnType();
16115 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
16116 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
16117 (RequireCompleteType(FD->getLocation(), ResultType,
16118 diag::err_func_def_incomplete_result) ||
16120 diag::err_abstract_type_in_decl,
16122 FD->setInvalidDecl();
16123
16124 if (FnBodyScope)
16125 PushDeclContext(FnBodyScope, FD);
16126
16127 // Check the validity of our function parameters
16128 if (BodyKind != FnBodyKind::Delete)
16130 /*CheckParameterNames=*/true);
16131
16132 // Add non-parameter declarations already in the function to the current
16133 // scope.
16134 if (FnBodyScope) {
16135 for (Decl *NPD : FD->decls()) {
16136 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
16137 if (!NonParmDecl)
16138 continue;
16139 assert(!isa<ParmVarDecl>(NonParmDecl) &&
16140 "parameters should not be in newly created FD yet");
16141
16142 // If the decl has a name, make it accessible in the current scope.
16143 if (NonParmDecl->getDeclName())
16144 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
16145
16146 // Similarly, dive into enums and fish their constants out, making them
16147 // accessible in this scope.
16148 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
16149 for (auto *EI : ED->enumerators())
16150 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
16151 }
16152 }
16153 }
16154
16155 // Introduce our parameters into the function scope
16156 for (auto *Param : FD->parameters()) {
16157 Param->setOwningFunction(FD);
16158
16159 // If this has an identifier, add it to the scope stack.
16160 if (Param->getIdentifier() && FnBodyScope) {
16161 CheckShadow(FnBodyScope, Param);
16162
16163 PushOnScopeChains(Param, FnBodyScope);
16164 }
16165 }
16166
16167 // C++ [module.import/6] external definitions are not permitted in header
16168 // units. Deleted and Defaulted functions are implicitly inline (but the
16169 // inline state is not set at this point, so check the BodyKind explicitly).
16170 // FIXME: Consider an alternate location for the test where the inlined()
16171 // state is complete.
16172 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
16173 !FD->isInvalidDecl() && !FD->isInlined() &&
16174 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
16175 FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() &&
16176 !FD->isTemplateInstantiation()) {
16177 assert(FD->isThisDeclarationADefinition());
16178 Diag(FD->getLocation(), diag::err_extern_def_in_header_unit);
16179 FD->setInvalidDecl();
16180 }
16181
16182 // Ensure that the function's exception specification is instantiated.
16183 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
16185
16186 // dllimport cannot be applied to non-inline function definitions.
16187 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
16188 !FD->isTemplateInstantiation()) {
16189 assert(!FD->hasAttr<DLLExportAttr>());
16190 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
16191 FD->setInvalidDecl();
16192 return D;
16193 }
16194
16195 // Some function attributes (like OptimizeNoneAttr) need actions before
16196 // parsing body started.
16198
16199 // We want to attach documentation to original Decl (which might be
16200 // a function template).
16202 if (getCurLexicalContext()->isObjCContainer() &&
16203 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
16204 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
16205 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
16206
16208
16209 return D;
16210}
16211
16213 if (!FD || FD->isInvalidDecl())
16214 return;
16215 if (auto *TD = dyn_cast<FunctionTemplateDecl>(FD))
16216 FD = TD->getTemplatedDecl();
16217 if (FD && FD->hasAttr<OptimizeNoneAttr>()) {
16220 CurFPFeatures.applyChanges(FPO);
16221 FpPragmaStack.CurrentValue =
16222 CurFPFeatures.getChangesFrom(FPOptions(LangOpts));
16223 }
16224}
16225
16227 ReturnStmt **Returns = Scope->Returns.data();
16228
16229 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
16230 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
16231 if (!NRVOCandidate->isNRVOVariable()) {
16232 Diag(Returns[I]->getRetValue()->getExprLoc(),
16233 diag::warn_not_eliding_copy_on_return);
16234 Returns[I]->setNRVOCandidate(nullptr);
16235 }
16236 }
16237 }
16238}
16239
16241 // We can't delay parsing the body of a constexpr function template (yet).
16243 return false;
16244
16245 // We can't delay parsing the body of a function template with a deduced
16246 // return type (yet).
16247 if (D.getDeclSpec().hasAutoTypeSpec()) {
16248 // If the placeholder introduces a non-deduced trailing return type,
16249 // we can still delay parsing it.
16250 if (D.getNumTypeObjects()) {
16251 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
16252 if (Outer.Kind == DeclaratorChunk::Function &&
16253 Outer.Fun.hasTrailingReturnType()) {
16254 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
16255 return Ty.isNull() || !Ty->isUndeducedType();
16256 }
16257 }
16258 return false;
16259 }
16260
16261 return true;
16262}
16263
16265 // We cannot skip the body of a function (or function template) which is
16266 // constexpr, since we may need to evaluate its body in order to parse the
16267 // rest of the file.
16268 // We cannot skip the body of a function with an undeduced return type,
16269 // because any callers of that function need to know the type.
16270 if (const FunctionDecl *FD = D->getAsFunction()) {
16271 if (FD->isConstexpr())
16272 return false;
16273 // We can't simply call Type::isUndeducedType here, because inside template
16274 // auto can be deduced to a dependent type, which is not considered
16275 // "undeduced".
16276 if (FD->getReturnType()->getContainedDeducedType())
16277 return false;
16278 }
16279 return Consumer.shouldSkipFunctionBody(D);
16280}
16281
16283 if (!Decl)
16284 return nullptr;
16285 if (FunctionDecl *FD = Decl->getAsFunction())
16286 FD->setHasSkippedBody();
16287 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
16288 MD->setHasSkippedBody();
16289 return Decl;
16290}
16291
16292/// RAII object that pops an ExpressionEvaluationContext when exiting a function
16293/// body.
16295public:
16296 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
16298 if (!IsLambda)
16299 S.PopExpressionEvaluationContext();
16300 }
16301
16302private:
16303 Sema &S;
16304 bool IsLambda = false;
16305};
16306
16308 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
16309
16310 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
16311 auto [It, Inserted] = EscapeInfo.try_emplace(BD);
16312 if (!Inserted)
16313 return It->second;
16314
16315 bool R = false;
16316 const BlockDecl *CurBD = BD;
16317
16318 do {
16319 R = !CurBD->doesNotEscape();
16320 if (R)
16321 break;
16322 CurBD = CurBD->getParent()->getInnermostBlockDecl();
16323 } while (CurBD);
16324
16325 return It->second = R;
16326 };
16327
16328 // If the location where 'self' is implicitly retained is inside a escaping
16329 // block, emit a diagnostic.
16330 for (const std::pair<SourceLocation, const BlockDecl *> &P :
16332 if (IsOrNestedInEscapingBlock(P.second))
16333 S.Diag(P.first, diag::warn_implicitly_retains_self)
16334 << FixItHint::CreateInsertion(P.first, "self->");
16335}
16336
16337static bool methodHasName(const FunctionDecl *FD, StringRef Name) {
16338 return isa<CXXMethodDecl>(FD) && FD->param_empty() &&
16339 FD->getDeclName().isIdentifier() && FD->getName() == Name;
16340}
16341
16343 return methodHasName(FD, "get_return_object");
16344}
16345
16347 return FD->isStatic() &&
16348 methodHasName(FD, "get_return_object_on_allocation_failure");
16349}
16350
16353 if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>())
16354 return;
16355 // Allow some_promise_type::get_return_object().
16357 return;
16358 if (!FD->hasAttr<CoroWrapperAttr>())
16359 Diag(FD->getLocation(), diag::err_coroutine_return_type) << RD;
16360}
16361
16362Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, bool IsInstantiation,
16363 bool RetainFunctionScopeInfo) {
16365 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
16366
16367 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
16368 FD->addAttr(StrictFPAttr::CreateImplicit(Context));
16369
16370 SourceLocation AnalysisLoc;
16371 if (Body)
16372 AnalysisLoc = Body->getEndLoc();
16373 else if (FD)
16374 AnalysisLoc = FD->getEndLoc();
16376 AnalysisWarnings.getPolicyInEffectAt(AnalysisLoc);
16377 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
16378
16379 // If we skip function body, we can't tell if a function is a coroutine.
16380 if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) {
16381 if (FSI->isCoroutine())
16383 else
16385 }
16386
16387 // Diagnose invalid SYCL kernel entry point function declarations
16388 // and build SYCLKernelCallStmts for valid ones.
16389 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLKernelEntryPointAttr>()) {
16390 SYCLKernelEntryPointAttr *SKEPAttr =
16391 FD->getAttr<SYCLKernelEntryPointAttr>();
16392 if (FD->isDefaulted()) {
16393 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16394 << SKEPAttr << /*defaulted function*/ 3;
16395 SKEPAttr->setInvalidAttr();
16396 } else if (FD->isDeleted()) {
16397 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16398 << SKEPAttr << /*deleted function*/ 2;
16399 SKEPAttr->setInvalidAttr();
16400 } else if (FSI->isCoroutine()) {
16401 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16402 << SKEPAttr << /*coroutine*/ 7;
16403 SKEPAttr->setInvalidAttr();
16404 } else if (Body && isa<CXXTryStmt>(Body)) {
16405 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16406 << SKEPAttr << /*function defined with a function try block*/ 8;
16407 SKEPAttr->setInvalidAttr();
16408 }
16409
16410 if (Body && !FD->isTemplated() && !SKEPAttr->isInvalidAttr()) {
16411 StmtResult SR =
16413 if (SR.isInvalid())
16414 return nullptr;
16415 Body = SR.get();
16416 }
16417 }
16418
16419 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLExternalAttr>()) {
16420 SYCLExternalAttr *SEAttr = FD->getAttr<SYCLExternalAttr>();
16421 if (FD->isDeletedAsWritten())
16422 Diag(SEAttr->getLocation(),
16423 diag::err_sycl_external_invalid_deleted_function)
16424 << SEAttr;
16425 }
16426
16427 {
16428 // Do not call PopExpressionEvaluationContext() if it is a lambda because
16429 // one is already popped when finishing the lambda in BuildLambdaExpr().
16430 // This is meant to pop the context added in ActOnStartOfFunctionDef().
16431 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
16432 if (FD) {
16433 // The function body and the DefaultedOrDeletedInfo, if present, use
16434 // the same storage; don't overwrite the latter if the former is null
16435 // (the body is initialised to null anyway, so even if the latter isn't
16436 // present, this would still be a no-op).
16437 if (Body)
16438 FD->setBody(Body);
16439 FD->setWillHaveBody(false);
16440
16441 if (getLangOpts().CPlusPlus14) {
16442 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
16443 FD->getReturnType()->isUndeducedType()) {
16444 // For a function with a deduced result type to return void,
16445 // the result type as written must be 'auto' or 'decltype(auto)',
16446 // possibly cv-qualified or constrained, but not ref-qualified.
16447 if (!FD->getReturnType()->getAs<AutoType>()) {
16448 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
16449 << FD->getReturnType();
16450 FD->setInvalidDecl();
16451 } else {
16452 // Falling off the end of the function is the same as 'return;'.
16453 Expr *Dummy = nullptr;
16455 FD, dcl->getLocation(), Dummy,
16456 FD->getReturnType()->getAs<AutoType>()))
16457 FD->setInvalidDecl();
16458 }
16459 }
16460 } else if (getLangOpts().CPlusPlus && isLambdaCallOperator(FD)) {
16461 // In C++11, we don't use 'auto' deduction rules for lambda call
16462 // operators because we don't support return type deduction.
16463 auto *LSI = getCurLambda();
16464 if (LSI->HasImplicitReturnType) {
16466
16467 // C++11 [expr.prim.lambda]p4:
16468 // [...] if there are no return statements in the compound-statement
16469 // [the deduced type is] the type void
16470 QualType RetType =
16471 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
16472
16473 // Update the return type to the deduced type.
16474 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
16475 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
16476 Proto->getExtProtoInfo()));
16477 }
16478 }
16479
16480 // If the function implicitly returns zero (like 'main') or is naked,
16481 // don't complain about missing return statements.
16482 // Clang implicitly returns 0 in C89 mode, but that's considered an
16483 // extension. The check is necessary to ensure the expected extension
16484 // warning is emitted in C89 mode.
16485 if ((FD->hasImplicitReturnZero() &&
16486 (getLangOpts().CPlusPlus || getLangOpts().C99 || !FD->isMain())) ||
16487 FD->hasAttr<NakedAttr>())
16489
16490 // MSVC permits the use of pure specifier (=0) on function definition,
16491 // defined at class scope, warn about this non-standard construct.
16492 if (getLangOpts().MicrosoftExt && FD->isPureVirtual() &&
16493 !FD->isOutOfLine())
16494 Diag(FD->getLocation(), diag::ext_pure_function_definition);
16495
16496 if (!FD->isInvalidDecl()) {
16497 // Don't diagnose unused parameters of defaulted, deleted or naked
16498 // functions.
16499 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
16500 !FD->hasAttr<NakedAttr>())
16503 FD->getReturnType(), FD);
16504
16505 // If this is a structor, we need a vtable.
16506 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
16507 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
16508 else if (CXXDestructorDecl *Destructor =
16509 dyn_cast<CXXDestructorDecl>(FD))
16510 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
16511
16512 // Try to apply the named return value optimization. We have to check
16513 // if we can do this here because lambdas keep return statements around
16514 // to deduce an implicit return type.
16515 if (FD->getReturnType()->isRecordType() &&
16517 computeNRVO(Body, FSI);
16518 }
16519
16520 // GNU warning -Wmissing-prototypes:
16521 // Warn if a global function is defined without a previous
16522 // prototype declaration. This warning is issued even if the
16523 // definition itself provides a prototype. The aim is to detect
16524 // global functions that fail to be declared in header files.
16525 const FunctionDecl *PossiblePrototype = nullptr;
16526 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
16527 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
16528
16529 if (PossiblePrototype) {
16530 // We found a declaration that is not a prototype,
16531 // but that could be a zero-parameter prototype
16532 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
16533 TypeLoc TL = TI->getTypeLoc();
16535 Diag(PossiblePrototype->getLocation(),
16536 diag::note_declaration_not_a_prototype)
16537 << (FD->getNumParams() != 0)
16539 FTL.getRParenLoc(), "void")
16540 : FixItHint{});
16541 }
16542 } else {
16543 // Returns true if the token beginning at this Loc is `const`.
16544 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
16545 const LangOptions &LangOpts) {
16546 FileIDAndOffset LocInfo = SM.getDecomposedLoc(Loc);
16547 if (LocInfo.first.isInvalid())
16548 return false;
16549
16550 bool Invalid = false;
16551 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
16552 if (Invalid)
16553 return false;
16554
16555 if (LocInfo.second > Buffer.size())
16556 return false;
16557
16558 const char *LexStart = Buffer.data() + LocInfo.second;
16559 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
16560
16561 return StartTok.consume_front("const") &&
16562 (StartTok.empty() || isWhitespace(StartTok[0]) ||
16563 StartTok.starts_with("/*") || StartTok.starts_with("//"));
16564 };
16565
16566 auto findBeginLoc = [&]() {
16567 // If the return type has `const` qualifier, we want to insert
16568 // `static` before `const` (and not before the typename).
16569 if ((FD->getReturnType()->isAnyPointerType() &&
16572 // But only do this if we can determine where the `const` is.
16573
16574 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
16575 getLangOpts()))
16576
16577 return FD->getBeginLoc();
16578 }
16579 return FD->getTypeSpecStartLoc();
16580 };
16582 diag::note_static_for_internal_linkage)
16583 << /* function */ 1
16584 << (FD->getStorageClass() == SC_None
16585 ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
16586 : FixItHint{});
16587 }
16588 }
16589
16590 // We might not have found a prototype because we didn't wish to warn on
16591 // the lack of a missing prototype. Try again without the checks for
16592 // whether we want to warn on the missing prototype.
16593 if (!PossiblePrototype)
16594 (void)FindPossiblePrototype(FD, PossiblePrototype);
16595
16596 // If the function being defined does not have a prototype, then we may
16597 // need to diagnose it as changing behavior in C23 because we now know
16598 // whether the function accepts arguments or not. This only handles the
16599 // case where the definition has no prototype but does have parameters
16600 // and either there is no previous potential prototype, or the previous
16601 // potential prototype also has no actual prototype. This handles cases
16602 // like:
16603 // void f(); void f(a) int a; {}
16604 // void g(a) int a; {}
16605 // See MergeFunctionDecl() for other cases of the behavior change
16606 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
16607 // type without a prototype.
16608 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
16609 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
16610 !PossiblePrototype->isImplicit()))) {
16611 // The function definition has parameters, so this will change behavior
16612 // in C23. If there is a possible prototype, it comes before the
16613 // function definition.
16614 // FIXME: The declaration may have already been diagnosed as being
16615 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
16616 // there's no way to test for the "changes behavior" condition in
16617 // SemaType.cpp when forming the declaration's function type. So, we do
16618 // this awkward dance instead.
16619 //
16620 // If we have a possible prototype and it declares a function with a
16621 // prototype, we don't want to diagnose it; if we have a possible
16622 // prototype and it has no prototype, it may have already been
16623 // diagnosed in SemaType.cpp as deprecated depending on whether
16624 // -Wstrict-prototypes is enabled. If we already warned about it being
16625 // deprecated, add a note that it also changes behavior. If we didn't
16626 // warn about it being deprecated (because the diagnostic is not
16627 // enabled), warn now that it is deprecated and changes behavior.
16628
16629 // This K&R C function definition definitely changes behavior in C23,
16630 // so diagnose it.
16631 Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
16632 << /*definition*/ 1 << /* not supported in C23 */ 0;
16633
16634 // If we have a possible prototype for the function which is a user-
16635 // visible declaration, we already tested that it has no prototype.
16636 // This will change behavior in C23. This gets a warning rather than a
16637 // note because it's the same behavior-changing problem as with the
16638 // definition.
16639 if (PossiblePrototype)
16640 Diag(PossiblePrototype->getLocation(),
16641 diag::warn_non_prototype_changes_behavior)
16642 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
16643 << /*definition*/ 1;
16644 }
16645
16646 // Warn on CPUDispatch with an actual body.
16647 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
16648 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
16649 if (!CmpndBody->body_empty())
16650 Diag(CmpndBody->body_front()->getBeginLoc(),
16651 diag::warn_dispatch_body_ignored);
16652
16653 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
16654 const CXXMethodDecl *KeyFunction;
16655 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
16656 MD->isVirtual() &&
16657 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
16658 MD == KeyFunction->getCanonicalDecl()) {
16659 // Update the key-function state if necessary for this ABI.
16660 if (FD->isInlined() &&
16661 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
16662 Context.setNonKeyFunction(MD);
16663
16664 // If the newly-chosen key function is already defined, then we
16665 // need to mark the vtable as used retroactively.
16666 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
16667 const FunctionDecl *Definition;
16668 if (KeyFunction && KeyFunction->isDefined(Definition))
16669 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
16670 } else {
16671 // We just defined they key function; mark the vtable as used.
16672 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
16673 }
16674 }
16675 }
16676
16677 assert((FD == getCurFunctionDecl(/*AllowLambdas=*/true)) &&
16678 "Function parsing confused");
16679 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
16680 assert(MD == getCurMethodDecl() && "Method parsing confused");
16681 MD->setBody(Body);
16682 if (!MD->isInvalidDecl()) {
16684 MD->getReturnType(), MD);
16685
16686 if (Body)
16687 computeNRVO(Body, FSI);
16688 }
16689 if (FSI->ObjCShouldCallSuper) {
16690 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
16691 << MD->getSelector().getAsString();
16692 FSI->ObjCShouldCallSuper = false;
16693 }
16695 const ObjCMethodDecl *InitMethod = nullptr;
16696 bool isDesignated =
16697 MD->isDesignatedInitializerForTheInterface(&InitMethod);
16698 assert(isDesignated && InitMethod);
16699 (void)isDesignated;
16700
16701 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
16702 auto IFace = MD->getClassInterface();
16703 if (!IFace)
16704 return false;
16705 auto SuperD = IFace->getSuperClass();
16706 if (!SuperD)
16707 return false;
16708 return SuperD->getIdentifier() ==
16709 ObjC().NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
16710 };
16711 // Don't issue this warning for unavailable inits or direct subclasses
16712 // of NSObject.
16713 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
16714 Diag(MD->getLocation(),
16715 diag::warn_objc_designated_init_missing_super_call);
16716 Diag(InitMethod->getLocation(),
16717 diag::note_objc_designated_init_marked_here);
16718 }
16720 }
16721 if (FSI->ObjCWarnForNoInitDelegation) {
16722 // Don't issue this warning for unavailable inits.
16723 if (!MD->isUnavailable())
16724 Diag(MD->getLocation(),
16725 diag::warn_objc_secondary_init_missing_init_call);
16726 FSI->ObjCWarnForNoInitDelegation = false;
16727 }
16728
16730 } else {
16731 // Parsing the function declaration failed in some way. Pop the fake scope
16732 // we pushed on.
16733 PopFunctionScopeInfo(ActivePolicy, dcl);
16734 return nullptr;
16735 }
16736
16737 if (Body && FSI->HasPotentialAvailabilityViolations)
16739
16740 assert(!FSI->ObjCShouldCallSuper &&
16741 "This should only be set for ObjC methods, which should have been "
16742 "handled in the block above.");
16743
16744 // Verify and clean out per-function state.
16745 if (Body && (!FD || !FD->isDefaulted())) {
16746 // C++ constructors that have function-try-blocks can't have return
16747 // statements in the handlers of that block. (C++ [except.handle]p14)
16748 // Verify this.
16749 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
16751
16752 // Verify that gotos and switch cases don't jump into scopes illegally.
16753 if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
16755
16756 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
16757 if (!Destructor->getParent()->isDependentType())
16759
16761 Destructor->getParent());
16762 }
16763
16764 // If any errors have occurred, clear out any temporaries that may have
16765 // been leftover. This ensures that these temporaries won't be picked up
16766 // for deletion in some later function.
16769 getDiagnostics().getSuppressAllDiagnostics()) {
16771 }
16773 // Since the body is valid, issue any analysis-based warnings that are
16774 // enabled.
16775 ActivePolicy = &WP;
16776 }
16777
16778 if (!IsInstantiation && FD &&
16779 (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) &&
16780 !FD->isInvalidDecl() &&
16782 FD->setInvalidDecl();
16783
16784 if (FD && FD->hasAttr<NakedAttr>()) {
16785 for (const Stmt *S : Body->children()) {
16786 // Allow local register variables without initializer as they don't
16787 // require prologue.
16788 bool RegisterVariables = false;
16789 if (auto *DS = dyn_cast<DeclStmt>(S)) {
16790 for (const auto *Decl : DS->decls()) {
16791 if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
16792 RegisterVariables =
16793 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
16794 if (!RegisterVariables)
16795 break;
16796 }
16797 }
16798 }
16799 if (RegisterVariables)
16800 continue;
16801 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
16802 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
16803 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
16804 FD->setInvalidDecl();
16805 break;
16806 }
16807 }
16808 }
16809
16810 assert(ExprCleanupObjects.size() ==
16811 ExprEvalContexts.back().NumCleanupObjects &&
16812 "Leftover temporaries in function");
16813 assert(!Cleanup.exprNeedsCleanups() &&
16814 "Unaccounted cleanups in function");
16815 assert(MaybeODRUseExprs.empty() &&
16816 "Leftover expressions for odr-use checking");
16817 }
16818 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
16819 // the declaration context below. Otherwise, we're unable to transform
16820 // 'this' expressions when transforming immediate context functions.
16821
16822 if (FD)
16824
16825 if (!IsInstantiation)
16827
16828 if (!RetainFunctionScopeInfo)
16829 PopFunctionScopeInfo(ActivePolicy, dcl);
16830 // If any errors have occurred, clear out any temporaries that may have
16831 // been leftover. This ensures that these temporaries won't be picked up for
16832 // deletion in some later function.
16835 }
16836
16837 if (FD && (LangOpts.isTargetDevice() || LangOpts.CUDA ||
16838 (LangOpts.OpenMP && !LangOpts.OMPTargetTriples.empty()))) {
16839 auto ES = getEmissionStatus(FD);
16843 }
16844
16845 if (FD && !FD->isDeleted())
16846 checkTypeSupport(FD->getType(), FD->getLocation(), FD);
16847
16848 return dcl;
16849}
16850
16851/// When we finish delayed parsing of an attribute, we must attach it to the
16852/// relevant Decl.
16854 ParsedAttributes &Attrs) {
16855 // Always attach attributes to the underlying decl.
16856 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
16857 D = TD->getTemplatedDecl();
16858 ProcessDeclAttributeList(S, D, Attrs);
16859 ProcessAPINotes(D);
16860
16861 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
16862 if (Method->isStatic())
16864}
16865
16867 IdentifierInfo &II, Scope *S) {
16868 // It is not valid to implicitly define a function in C23.
16869 assert(LangOpts.implicitFunctionsAllowed() &&
16870 "Implicit function declarations aren't allowed in this language mode");
16871
16872 // Find the scope in which the identifier is injected and the corresponding
16873 // DeclContext.
16874 // FIXME: C89 does not say what happens if there is no enclosing block scope.
16875 // In that case, we inject the declaration into the translation unit scope
16876 // instead.
16877 Scope *BlockScope = S;
16878 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
16879 BlockScope = BlockScope->getParent();
16880
16881 // Loop until we find a DeclContext that is either a function/method or the
16882 // translation unit, which are the only two valid places to implicitly define
16883 // a function. This avoids accidentally defining the function within a tag
16884 // declaration, for example.
16885 Scope *ContextScope = BlockScope;
16886 while (!ContextScope->getEntity() ||
16887 (!ContextScope->getEntity()->isFunctionOrMethod() &&
16888 !ContextScope->getEntity()->isTranslationUnit()))
16889 ContextScope = ContextScope->getParent();
16890 ContextRAII SavedContext(*this, ContextScope->getEntity());
16891
16892 // Before we produce a declaration for an implicitly defined
16893 // function, see whether there was a locally-scoped declaration of
16894 // this name as a function or variable. If so, use that
16895 // (non-visible) declaration, and complain about it.
16896 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
16897 if (ExternCPrev) {
16898 // We still need to inject the function into the enclosing block scope so
16899 // that later (non-call) uses can see it.
16900 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
16901
16902 // C89 footnote 38:
16903 // If in fact it is not defined as having type "function returning int",
16904 // the behavior is undefined.
16905 if (!isa<FunctionDecl>(ExternCPrev) ||
16906 !Context.typesAreCompatible(
16907 cast<FunctionDecl>(ExternCPrev)->getType(),
16908 Context.getFunctionNoProtoType(Context.IntTy))) {
16909 Diag(Loc, diag::ext_use_out_of_scope_declaration)
16910 << ExternCPrev << !getLangOpts().C99;
16911 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
16912 return ExternCPrev;
16913 }
16914 }
16915
16916 // Extension in C99 (defaults to error). Legal in C89, but warn about it.
16917 unsigned diag_id;
16918 if (II.getName().starts_with("__builtin_"))
16919 diag_id = diag::warn_builtin_unknown;
16920 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
16921 else if (getLangOpts().C99)
16922 diag_id = diag::ext_implicit_function_decl_c99;
16923 else
16924 diag_id = diag::warn_implicit_function_decl;
16925
16926 TypoCorrection Corrected;
16927 // Because typo correction is expensive, only do it if the implicit
16928 // function declaration is going to be treated as an error.
16929 //
16930 // Perform the correction before issuing the main diagnostic, as some
16931 // consumers use typo-correction callbacks to enhance the main diagnostic.
16932 if (S && !ExternCPrev &&
16933 (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {
16935 Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
16936 S, nullptr, CCC, CorrectTypoKind::NonError);
16937 }
16938
16939 Diag(Loc, diag_id) << &II;
16940 if (Corrected) {
16941 // If the correction is going to suggest an implicitly defined function,
16942 // skip the correction as not being a particularly good idea.
16943 bool Diagnose = true;
16944 if (const auto *D = Corrected.getCorrectionDecl())
16945 Diagnose = !D->isImplicit();
16946 if (Diagnose)
16947 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
16948 /*ErrorRecovery*/ false);
16949 }
16950
16951 // If we found a prior declaration of this function, don't bother building
16952 // another one. We've already pushed that one into scope, so there's nothing
16953 // more to do.
16954 if (ExternCPrev)
16955 return ExternCPrev;
16956
16957 // Set a Declarator for the implicit definition: int foo();
16958 const char *Dummy;
16959 AttributeFactory attrFactory;
16960 DeclSpec DS(attrFactory);
16961 unsigned DiagID;
16962 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
16963 Context.getPrintingPolicy());
16964 (void)Error; // Silence warning.
16965 assert(!Error && "Error setting up implicit decl!");
16966 SourceLocation NoLoc;
16968 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
16969 /*IsAmbiguous=*/false,
16970 /*LParenLoc=*/NoLoc,
16971 /*Params=*/nullptr,
16972 /*NumParams=*/0,
16973 /*EllipsisLoc=*/NoLoc,
16974 /*RParenLoc=*/NoLoc,
16975 /*RefQualifierIsLvalueRef=*/true,
16976 /*RefQualifierLoc=*/NoLoc,
16977 /*MutableLoc=*/NoLoc, EST_None,
16978 /*ESpecRange=*/SourceRange(),
16979 /*Exceptions=*/nullptr,
16980 /*ExceptionRanges=*/nullptr,
16981 /*NumExceptions=*/0,
16982 /*NoexceptExpr=*/nullptr,
16983 /*ExceptionSpecTokens=*/nullptr,
16984 /*DeclsInPrototype=*/{}, Loc, Loc,
16985 D),
16986 std::move(DS.getAttributes()), SourceLocation());
16987 D.SetIdentifier(&II, Loc);
16988
16989 // Insert this function into the enclosing block scope.
16990 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
16991 FD->setImplicit();
16992
16994
16995 return FD;
16996}
16997
16999 FunctionDecl *FD) {
17000 if (FD->isInvalidDecl())
17001 return;
17002
17003 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
17004 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
17005 return;
17006
17007 UnsignedOrNone AlignmentParam = std::nullopt;
17008 bool IsNothrow = false;
17009 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
17010 return;
17011
17012 // C++2a [basic.stc.dynamic.allocation]p4:
17013 // An allocation function that has a non-throwing exception specification
17014 // indicates failure by returning a null pointer value. Any other allocation
17015 // function never returns a null pointer value and indicates failure only by
17016 // throwing an exception [...]
17017 //
17018 // However, -fcheck-new invalidates this possible assumption, so don't add
17019 // NonNull when that is enabled.
17020 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&
17021 !getLangOpts().CheckNew)
17022 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
17023
17024 // C++2a [basic.stc.dynamic.allocation]p2:
17025 // An allocation function attempts to allocate the requested amount of
17026 // storage. [...] If the request succeeds, the value returned by a
17027 // replaceable allocation function is a [...] pointer value p0 different
17028 // from any previously returned value p1 [...]
17029 //
17030 // However, this particular information is being added in codegen,
17031 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
17032
17033 // C++2a [basic.stc.dynamic.allocation]p2:
17034 // An allocation function attempts to allocate the requested amount of
17035 // storage. If it is successful, it returns the address of the start of a
17036 // block of storage whose length in bytes is at least as large as the
17037 // requested size.
17038 if (!FD->hasAttr<AllocSizeAttr>()) {
17039 FD->addAttr(AllocSizeAttr::CreateImplicit(
17040 Context, /*ElemSizeParam=*/ParamIdx(1, FD),
17041 /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
17042 }
17043
17044 // C++2a [basic.stc.dynamic.allocation]p3:
17045 // For an allocation function [...], the pointer returned on a successful
17046 // call shall represent the address of storage that is aligned as follows:
17047 // (3.1) If the allocation function takes an argument of type
17048 // std​::​align_­val_­t, the storage will have the alignment
17049 // specified by the value of this argument.
17050 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
17051 FD->addAttr(AllocAlignAttr::CreateImplicit(
17052 Context, ParamIdx(*AlignmentParam, FD), FD->getLocation()));
17053 }
17054
17055 // FIXME:
17056 // C++2a [basic.stc.dynamic.allocation]p3:
17057 // For an allocation function [...], the pointer returned on a successful
17058 // call shall represent the address of storage that is aligned as follows:
17059 // (3.2) Otherwise, if the allocation function is named operator new[],
17060 // the storage is aligned for any object that does not have
17061 // new-extended alignment ([basic.align]) and is no larger than the
17062 // requested size.
17063 // (3.3) Otherwise, the storage is aligned for any object that does not
17064 // have new-extended alignment and is of the requested size.
17065}
17066
17068 if (FD->isInvalidDecl())
17069 return;
17070
17071 // If this is a built-in function, map its builtin attributes to
17072 // actual attributes.
17073 if (unsigned BuiltinID = FD->getBuiltinID()) {
17074 // Handle printf-formatting attributes.
17075 unsigned FormatIdx;
17076 bool HasVAListArg;
17077 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
17078 if (!FD->hasAttr<FormatAttr>()) {
17079 const char *fmt = "printf";
17080 unsigned int NumParams = FD->getNumParams();
17081 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
17082 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
17083 fmt = "NSString";
17084 FD->addAttr(FormatAttr::CreateImplicit(Context,
17085 &Context.Idents.get(fmt),
17086 FormatIdx+1,
17087 HasVAListArg ? 0 : FormatIdx+2,
17088 FD->getLocation()));
17089 }
17090 }
17091 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
17092 HasVAListArg)) {
17093 if (!FD->hasAttr<FormatAttr>())
17094 FD->addAttr(FormatAttr::CreateImplicit(Context,
17095 &Context.Idents.get("scanf"),
17096 FormatIdx+1,
17097 HasVAListArg ? 0 : FormatIdx+2,
17098 FD->getLocation()));
17099 }
17100
17101 // Handle automatically recognized callbacks.
17102 SmallVector<int, 4> Encoding;
17103 if (!FD->hasAttr<CallbackAttr>() &&
17104 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
17105 FD->addAttr(CallbackAttr::CreateImplicit(
17106 Context, Encoding.data(), Encoding.size(), FD->getLocation()));
17107
17108 // Mark const if we don't care about errno and/or floating point exceptions
17109 // that are the only thing preventing the function from being const. This
17110 // allows IRgen to use LLVM intrinsics for such functions.
17111 bool NoExceptions =
17113 bool ConstWithoutErrnoAndExceptions =
17114 Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(BuiltinID);
17115 bool ConstWithoutExceptions =
17116 Context.BuiltinInfo.isConstWithoutExceptions(BuiltinID);
17117 if (!FD->hasAttr<ConstAttr>() &&
17118 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
17119 (!ConstWithoutErrnoAndExceptions ||
17120 (!getLangOpts().MathErrno && NoExceptions)) &&
17121 (!ConstWithoutExceptions || NoExceptions))
17122 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
17123
17124 // We make "fma" on GNU or Windows const because we know it does not set
17125 // errno in those environments even though it could set errno based on the
17126 // C standard.
17127 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
17128 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
17129 !FD->hasAttr<ConstAttr>()) {
17130 switch (BuiltinID) {
17131 case Builtin::BI__builtin_fma:
17132 case Builtin::BI__builtin_fmaf:
17133 case Builtin::BI__builtin_fmal:
17134 case Builtin::BIfma:
17135 case Builtin::BIfmaf:
17136 case Builtin::BIfmal:
17137 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
17138 break;
17139 default:
17140 break;
17141 }
17142 }
17143
17144 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
17145 !FD->hasAttr<ReturnsTwiceAttr>())
17146 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
17147 FD->getLocation()));
17148 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
17149 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
17150 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
17151 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
17152 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
17153 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
17154 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
17155 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
17156 // Add the appropriate attribute, depending on the CUDA compilation mode
17157 // and which target the builtin belongs to. For example, during host
17158 // compilation, aux builtins are __device__, while the rest are __host__.
17159 if (getLangOpts().CUDAIsDevice !=
17160 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
17161 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
17162 else
17163 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
17164 }
17165
17166 // Add known guaranteed alignment for allocation functions.
17167 switch (BuiltinID) {
17168 case Builtin::BImemalign:
17169 case Builtin::BIaligned_alloc:
17170 if (!FD->hasAttr<AllocAlignAttr>())
17171 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
17172 FD->getLocation()));
17173 break;
17174 default:
17175 break;
17176 }
17177
17178 // Add allocsize attribute for allocation functions.
17179 switch (BuiltinID) {
17180 case Builtin::BIcalloc:
17181 FD->addAttr(AllocSizeAttr::CreateImplicit(
17182 Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
17183 break;
17184 case Builtin::BImemalign:
17185 case Builtin::BIaligned_alloc:
17186 case Builtin::BIrealloc:
17187 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
17188 ParamIdx(), FD->getLocation()));
17189 break;
17190 case Builtin::BImalloc:
17191 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
17192 ParamIdx(), FD->getLocation()));
17193 break;
17194 default:
17195 break;
17196 }
17197 }
17198
17203
17204 // If C++ exceptions are enabled but we are told extern "C" functions cannot
17205 // throw, add an implicit nothrow attribute to any extern "C" function we come
17206 // across.
17207 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
17208 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
17209 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
17210 if (!FPT || FPT->getExceptionSpecType() == EST_None)
17211 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
17212 }
17213
17214 IdentifierInfo *Name = FD->getIdentifier();
17215 if (!Name)
17216 return;
17219 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
17221 // Okay: this could be a libc/libm/Objective-C function we know
17222 // about.
17223 } else
17224 return;
17225
17226 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
17227 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
17228 // target-specific builtins, perhaps?
17229 if (!FD->hasAttr<FormatAttr>())
17230 FD->addAttr(FormatAttr::CreateImplicit(Context,
17231 &Context.Idents.get("printf"), 2,
17232 Name->isStr("vasprintf") ? 0 : 3,
17233 FD->getLocation()));
17234 }
17235
17236 if (Name->isStr("__CFStringMakeConstantString")) {
17237 // We already have a __builtin___CFStringMakeConstantString,
17238 // but builds that use -fno-constant-cfstrings don't go through that.
17239 if (!FD->hasAttr<FormatArgAttr>())
17240 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
17241 FD->getLocation()));
17242 }
17243}
17244
17246 TypeSourceInfo *TInfo) {
17247 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
17248 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
17249
17250 if (!TInfo) {
17251 assert(D.isInvalidType() && "no declarator info for valid type");
17252 TInfo = Context.getTrivialTypeSourceInfo(T);
17253 }
17254
17255 // Scope manipulation handled by caller.
17256 TypedefDecl *NewTD =
17258 D.getIdentifierLoc(), D.getIdentifier(), TInfo);
17259
17260 // Bail out immediately if we have an invalid declaration.
17261 if (D.isInvalidType()) {
17262 NewTD->setInvalidDecl();
17263 return NewTD;
17264 }
17265
17267 if (CurContext->isFunctionOrMethod())
17268 Diag(NewTD->getLocation(), diag::err_module_private_local)
17269 << 2 << NewTD
17273 else
17274 NewTD->setModulePrivate();
17275 }
17276
17277 // C++ [dcl.typedef]p8:
17278 // If the typedef declaration defines an unnamed class (or
17279 // enum), the first typedef-name declared by the declaration
17280 // to be that class type (or enum type) is used to denote the
17281 // class type (or enum type) for linkage purposes only.
17282 // We need to check whether the type was declared in the declaration.
17283 switch (D.getDeclSpec().getTypeSpecType()) {
17284 case TST_enum:
17285 case TST_struct:
17286 case TST_interface:
17287 case TST_union:
17288 case TST_class: {
17289 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
17290 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
17291 break;
17292 }
17293
17294 default:
17295 break;
17296 }
17297
17298 return NewTD;
17299}
17300
17302 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
17303 QualType T = TI->getType();
17304
17305 if (T->isDependentType())
17306 return false;
17307
17308 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17309 // integral type; any cv-qualification is ignored.
17310 // C23 6.7.3.3p5: The underlying type of the enumeration is the unqualified,
17311 // non-atomic version of the type specified by the type specifiers in the
17312 // specifier qualifier list.
17313 // Because of how odd C's rule is, we'll let the user know that operations
17314 // involving the enumeration type will be non-atomic.
17315 if (T->isAtomicType())
17316 Diag(UnderlyingLoc, diag::warn_atomic_stripped_in_enum);
17317
17318 Qualifiers Q = T.getQualifiers();
17319 std::optional<unsigned> QualSelect;
17320 if (Q.hasConst() && Q.hasVolatile())
17321 QualSelect = diag::CVQualList::Both;
17322 else if (Q.hasConst())
17323 QualSelect = diag::CVQualList::Const;
17324 else if (Q.hasVolatile())
17325 QualSelect = diag::CVQualList::Volatile;
17326
17327 if (QualSelect)
17328 Diag(UnderlyingLoc, diag::warn_cv_stripped_in_enum) << *QualSelect;
17329
17330 T = T.getAtomicUnqualifiedType();
17331
17332 // This doesn't use 'isIntegralType' despite the error message mentioning
17333 // integral type because isIntegralType would also allow enum types in C.
17334 if (const BuiltinType *BT = T->getAs<BuiltinType>())
17335 if (BT->isInteger())
17336 return false;
17337
17338 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying)
17339 << T << T->isBitIntType();
17340}
17341
17343 QualType EnumUnderlyingTy, bool IsFixed,
17344 const EnumDecl *Prev) {
17345 if (IsScoped != Prev->isScoped()) {
17346 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
17347 << Prev->isScoped();
17348 Diag(Prev->getLocation(), diag::note_previous_declaration);
17349 return true;
17350 }
17351
17352 if (IsFixed && Prev->isFixed()) {
17353 if (!EnumUnderlyingTy->isDependentType() &&
17354 !Prev->getIntegerType()->isDependentType() &&
17355 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
17356 Prev->getIntegerType())) {
17357 // TODO: Highlight the underlying type of the redeclaration.
17358 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
17359 << EnumUnderlyingTy << Prev->getIntegerType();
17360 Diag(Prev->getLocation(), diag::note_previous_declaration)
17361 << Prev->getIntegerTypeRange();
17362 return true;
17363 }
17364 } else if (IsFixed != Prev->isFixed()) {
17365 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
17366 << Prev->isFixed();
17367 Diag(Prev->getLocation(), diag::note_previous_declaration);
17368 return true;
17369 }
17370
17371 return false;
17372}
17373
17374/// Get diagnostic %select index for tag kind for
17375/// redeclaration diagnostic message.
17376/// WARNING: Indexes apply to particular diagnostics only!
17377///
17378/// \returns diagnostic %select index.
17380 switch (Tag) {
17382 return 0;
17384 return 1;
17385 case TagTypeKind::Class:
17386 return 2;
17387 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
17388 }
17389}
17390
17391/// Determine if tag kind is a class-key compatible with
17392/// class for redeclaration (class, struct, or __interface).
17393///
17394/// \returns true iff the tag kind is compatible.
17396{
17397 return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class ||
17399}
17400
17402 if (isa<TypedefDecl>(PrevDecl))
17403 return NonTagKind::Typedef;
17404 else if (isa<TypeAliasDecl>(PrevDecl))
17405 return NonTagKind::TypeAlias;
17406 else if (isa<ClassTemplateDecl>(PrevDecl))
17407 return NonTagKind::Template;
17408 else if (isa<TypeAliasTemplateDecl>(PrevDecl))
17410 else if (isa<TemplateTemplateParmDecl>(PrevDecl))
17412 switch (TTK) {
17415 case TagTypeKind::Class:
17416 return getLangOpts().CPlusPlus ? NonTagKind::NonClass
17418 case TagTypeKind::Union:
17419 return NonTagKind::NonUnion;
17420 case TagTypeKind::Enum:
17421 return NonTagKind::NonEnum;
17422 }
17423 llvm_unreachable("invalid TTK");
17424}
17425
17427 TagTypeKind NewTag, bool isDefinition,
17428 SourceLocation NewTagLoc,
17429 const IdentifierInfo *Name) {
17430 // C++ [dcl.type.elab]p3:
17431 // The class-key or enum keyword present in the
17432 // elaborated-type-specifier shall agree in kind with the
17433 // declaration to which the name in the elaborated-type-specifier
17434 // refers. This rule also applies to the form of
17435 // elaborated-type-specifier that declares a class-name or
17436 // friend class since it can be construed as referring to the
17437 // definition of the class. Thus, in any
17438 // elaborated-type-specifier, the enum keyword shall be used to
17439 // refer to an enumeration (7.2), the union class-key shall be
17440 // used to refer to a union (clause 9), and either the class or
17441 // struct class-key shall be used to refer to a class (clause 9)
17442 // declared using the class or struct class-key.
17443 TagTypeKind OldTag = Previous->getTagKind();
17444 if (OldTag != NewTag &&
17446 return false;
17447
17448 // Tags are compatible, but we might still want to warn on mismatched tags.
17449 // Non-class tags can't be mismatched at this point.
17451 return true;
17452
17453 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
17454 // by our warning analysis. We don't want to warn about mismatches with (eg)
17455 // declarations in system headers that are designed to be specialized, but if
17456 // a user asks us to warn, we should warn if their code contains mismatched
17457 // declarations.
17458 auto IsIgnoredLoc = [&](SourceLocation Loc) {
17459 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
17460 Loc);
17461 };
17462 if (IsIgnoredLoc(NewTagLoc))
17463 return true;
17464
17465 auto IsIgnored = [&](const TagDecl *Tag) {
17466 return IsIgnoredLoc(Tag->getLocation());
17467 };
17468 while (IsIgnored(Previous)) {
17469 Previous = Previous->getPreviousDecl();
17470 if (!Previous)
17471 return true;
17472 OldTag = Previous->getTagKind();
17473 }
17474
17475 bool isTemplate = false;
17476 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
17477 isTemplate = Record->getDescribedClassTemplate();
17478
17480 if (OldTag != NewTag) {
17481 // In a template instantiation, do not offer fix-its for tag mismatches
17482 // since they usually mess up the template instead of fixing the problem.
17483 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
17485 << getRedeclDiagFromTagKind(OldTag);
17486 // FIXME: Note previous location?
17487 }
17488 return true;
17489 }
17490
17491 if (isDefinition) {
17492 // On definitions, check all previous tags and issue a fix-it for each
17493 // one that doesn't match the current tag.
17494 if (Previous->getDefinition()) {
17495 // Don't suggest fix-its for redefinitions.
17496 return true;
17497 }
17498
17499 bool previousMismatch = false;
17500 for (const TagDecl *I : Previous->redecls()) {
17501 if (I->getTagKind() != NewTag) {
17502 // Ignore previous declarations for which the warning was disabled.
17503 if (IsIgnored(I))
17504 continue;
17505
17506 if (!previousMismatch) {
17507 previousMismatch = true;
17508 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
17510 << getRedeclDiagFromTagKind(I->getTagKind());
17511 }
17512 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
17514 << FixItHint::CreateReplacement(I->getInnerLocStart(),
17516 }
17517 }
17518 return true;
17519 }
17520
17521 // Identify the prevailing tag kind: this is the kind of the definition (if
17522 // there is a non-ignored definition), or otherwise the kind of the prior
17523 // (non-ignored) declaration.
17524 const TagDecl *PrevDef = Previous->getDefinition();
17525 if (PrevDef && IsIgnored(PrevDef))
17526 PrevDef = nullptr;
17527 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
17528 if (Redecl->getTagKind() != NewTag) {
17529 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
17531 << getRedeclDiagFromTagKind(OldTag);
17532 Diag(Redecl->getLocation(), diag::note_previous_use);
17533
17534 // If there is a previous definition, suggest a fix-it.
17535 if (PrevDef) {
17536 Diag(NewTagLoc, diag::note_struct_class_suggestion)
17540 }
17541 }
17542
17543 return true;
17544}
17545
17546/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
17547/// from an outer enclosing namespace or file scope inside a friend declaration.
17548/// This should provide the commented out code in the following snippet:
17549/// namespace N {
17550/// struct X;
17551/// namespace M {
17552/// struct Y { friend struct /*N::*/ X; };
17553/// }
17554/// }
17556 SourceLocation NameLoc) {
17557 // While the decl is in a namespace, do repeated lookup of that name and see
17558 // if we get the same namespace back. If we do not, continue until
17559 // translation unit scope, at which point we have a fully qualified NNS.
17562 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
17563 // This tag should be declared in a namespace, which can only be enclosed by
17564 // other namespaces. Bail if there's an anonymous namespace in the chain.
17565 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
17566 if (!Namespace || Namespace->isAnonymousNamespace())
17567 return FixItHint();
17568 IdentifierInfo *II = Namespace->getIdentifier();
17569 Namespaces.push_back(II);
17570 NamedDecl *Lookup = SemaRef.LookupSingleName(
17571 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
17572 if (Lookup == Namespace)
17573 break;
17574 }
17575
17576 // Once we have all the namespaces, reverse them to go outermost first, and
17577 // build an NNS.
17578 SmallString<64> Insertion;
17579 llvm::raw_svector_ostream OS(Insertion);
17580 if (DC->isTranslationUnit())
17581 OS << "::";
17582 std::reverse(Namespaces.begin(), Namespaces.end());
17583 for (auto *II : Namespaces)
17584 OS << II->getName() << "::";
17585 return FixItHint::CreateInsertion(NameLoc, Insertion);
17586}
17587
17588/// Determine whether a tag originally declared in context \p OldDC can
17589/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
17590/// found a declaration in \p OldDC as a previous decl, perhaps through a
17591/// using-declaration).
17593 DeclContext *NewDC) {
17594 OldDC = OldDC->getRedeclContext();
17595 NewDC = NewDC->getRedeclContext();
17596
17597 if (OldDC->Equals(NewDC))
17598 return true;
17599
17600 // In MSVC mode, we allow a redeclaration if the contexts are related (either
17601 // encloses the other).
17602 if (S.getLangOpts().MSVCCompat &&
17603 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
17604 return true;
17605
17606 return false;
17607}
17608
17610Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
17611 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17612 const ParsedAttributesView &Attrs, AccessSpecifier AS,
17613 SourceLocation ModulePrivateLoc,
17614 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
17615 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
17616 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
17617 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
17618 OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
17619 // If this is not a definition, it must have a name.
17620 IdentifierInfo *OrigName = Name;
17621 assert((Name != nullptr || TUK == TagUseKind::Definition) &&
17622 "Nameless record must be a definition!");
17623 assert(TemplateParameterLists.size() == 0 || TUK != TagUseKind::Reference);
17624
17625 OwnedDecl = false;
17627 bool ScopedEnum = ScopedEnumKWLoc.isValid();
17628
17629 // FIXME: Check member specializations more carefully.
17630 bool isMemberSpecialization = false;
17631 bool IsInjectedClassName = false;
17632 bool Invalid = false;
17633
17634 // We only need to do this matching if we have template parameters
17635 // or a scope specifier, which also conveniently avoids this work
17636 // for non-C++ cases.
17637 if (TemplateParameterLists.size() > 0 ||
17638 (SS.isNotEmpty() && TUK != TagUseKind::Reference)) {
17639 TemplateParameterList *TemplateParams =
17641 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
17642 TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);
17643
17644 // C++23 [dcl.type.elab] p2:
17645 // If an elaborated-type-specifier is the sole constituent of a
17646 // declaration, the declaration is ill-formed unless it is an explicit
17647 // specialization, an explicit instantiation or it has one of the
17648 // following forms: [...]
17649 // C++23 [dcl.enum] p1:
17650 // If the enum-head-name of an opaque-enum-declaration contains a
17651 // nested-name-specifier, the declaration shall be an explicit
17652 // specialization.
17653 //
17654 // FIXME: Class template partial specializations can be forward declared
17655 // per CWG2213, but the resolution failed to allow qualified forward
17656 // declarations. This is almost certainly unintentional, so we allow them.
17657 if (TUK == TagUseKind::Declaration && SS.isNotEmpty() &&
17658 !isMemberSpecialization)
17659 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
17661
17662 if (TemplateParams) {
17663 if (Kind == TagTypeKind::Enum) {
17664 Diag(KWLoc, diag::err_enum_template);
17665 return true;
17666 }
17667
17668 if (TemplateParams->size() > 0) {
17669 // This is a declaration or definition of a class template (which may
17670 // be a member of another template).
17671
17672 if (Invalid)
17673 return true;
17674
17675 OwnedDecl = false;
17677 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
17678 AS, ModulePrivateLoc,
17679 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
17680 TemplateParameterLists.data(), SkipBody);
17681 return Result.get();
17682 } else {
17683 // The "template<>" header is extraneous.
17684 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
17685 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
17686 isMemberSpecialization = true;
17687 }
17688 }
17689
17690 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
17691 CheckTemplateDeclScope(S, TemplateParameterLists.back()))
17692 return true;
17693 }
17694
17695 if (TUK == TagUseKind::Friend && Kind == TagTypeKind::Enum) {
17696 // C++23 [dcl.type.elab]p4:
17697 // If an elaborated-type-specifier appears with the friend specifier as
17698 // an entire member-declaration, the member-declaration shall have one
17699 // of the following forms:
17700 // friend class-key nested-name-specifier(opt) identifier ;
17701 // friend class-key simple-template-id ;
17702 // friend class-key nested-name-specifier template(opt)
17703 // simple-template-id ;
17704 //
17705 // Since enum is not a class-key, so declarations like "friend enum E;"
17706 // are ill-formed. Although CWG2363 reaffirms that such declarations are
17707 // invalid, most implementations accept so we issue a pedantic warning.
17708 Diag(KWLoc, diag::ext_enum_friend) << FixItHint::CreateRemoval(
17709 ScopedEnum ? SourceRange(KWLoc, ScopedEnumKWLoc) : KWLoc);
17710 assert(ScopedEnum || !ScopedEnumUsesClassTag);
17711 Diag(KWLoc, diag::note_enum_friend)
17712 << (ScopedEnum + ScopedEnumUsesClassTag);
17713 }
17714
17715 // Figure out the underlying type if this a enum declaration. We need to do
17716 // this early, because it's needed to detect if this is an incompatible
17717 // redeclaration.
17718 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
17719 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
17720
17721 if (Kind == TagTypeKind::Enum) {
17722 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
17723 // No underlying type explicitly specified, or we failed to parse the
17724 // type, default to int.
17725 EnumUnderlying = Context.IntTy.getTypePtr();
17726 } else if (UnderlyingType.get()) {
17727 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17728 // integral type; any cv-qualification is ignored.
17729 // C23 6.7.3.3p5: The underlying type of the enumeration is the
17730 // unqualified, non-atomic version of the type specified by the type
17731 // specifiers in the specifier qualifier list.
17732 TypeSourceInfo *TI = nullptr;
17733 GetTypeFromParser(UnderlyingType.get(), &TI);
17734 EnumUnderlying = TI;
17735
17737 // Recover by falling back to int.
17738 EnumUnderlying = Context.IntTy.getTypePtr();
17739
17742 EnumUnderlying = Context.IntTy.getTypePtr();
17743
17744 // If the underlying type is atomic, we need to adjust the type before
17745 // continuing. This only happens in the case we stored a TypeSourceInfo
17746 // into EnumUnderlying because the other cases are error recovery up to
17747 // this point. But because it's not possible to gin up a TypeSourceInfo
17748 // for a non-atomic type from an atomic one, we'll store into the Type
17749 // field instead. FIXME: it would be nice to have an easy way to get a
17750 // derived TypeSourceInfo which strips qualifiers including the weird
17751 // ones like _Atomic where it forms a different type.
17752 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying);
17753 TI && TI->getType()->isAtomicType())
17754 EnumUnderlying = TI->getType().getAtomicUnqualifiedType().getTypePtr();
17755
17756 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
17757 // For MSVC ABI compatibility, unfixed enums must use an underlying type
17758 // of 'int'. However, if this is an unfixed forward declaration, don't set
17759 // the underlying type unless the user enables -fms-compatibility. This
17760 // makes unfixed forward declared enums incomplete and is more conforming.
17761 if (TUK == TagUseKind::Definition || getLangOpts().MSVCCompat)
17762 EnumUnderlying = Context.IntTy.getTypePtr();
17763 }
17764 }
17765
17766 DeclContext *SearchDC = CurContext;
17767 DeclContext *DC = CurContext;
17768 bool isStdBadAlloc = false;
17769 bool isStdAlignValT = false;
17770
17772 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference)
17774
17775 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
17776 /// implemented asks for structural equivalence checking, the returned decl
17777 /// here is passed back to the parser, allowing the tag body to be parsed.
17778 auto createTagFromNewDecl = [&]() -> TagDecl * {
17779 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
17780 // If there is an identifier, use the location of the identifier as the
17781 // location of the decl, otherwise use the location of the struct/union
17782 // keyword.
17783 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
17784 TagDecl *New = nullptr;
17785
17786 if (Kind == TagTypeKind::Enum) {
17787 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
17788 ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
17789 // If this is an undefined enum, bail.
17790 if (TUK != TagUseKind::Definition && !Invalid)
17791 return nullptr;
17792 if (EnumUnderlying) {
17794 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying))
17796 else
17797 ED->setIntegerType(QualType(cast<const Type *>(EnumUnderlying), 0));
17798 QualType EnumTy = ED->getIntegerType();
17799 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
17800 ? Context.getPromotedIntegerType(EnumTy)
17801 : EnumTy);
17802 }
17803 } else { // struct/union
17804 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17805 nullptr);
17806 }
17807
17808 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
17809 // Add alignment attributes if necessary; these attributes are checked
17810 // when the ASTContext lays out the structure.
17811 //
17812 // It is important for implementing the correct semantics that this
17813 // happen here (in ActOnTag). The #pragma pack stack is
17814 // maintained as a result of parser callbacks which can occur at
17815 // many points during the parsing of a struct declaration (because
17816 // the #pragma tokens are effectively skipped over during the
17817 // parsing of the struct).
17818 if (TUK == TagUseKind::Definition &&
17819 (!SkipBody || !SkipBody->ShouldSkip)) {
17820 if (LangOpts.HLSL)
17821 RD->addAttr(PackedAttr::CreateImplicit(Context));
17824 }
17825 }
17826 New->setLexicalDeclContext(CurContext);
17827 return New;
17828 };
17829
17830 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
17831 if (Name && SS.isNotEmpty()) {
17832 // We have a nested-name tag ('struct foo::bar').
17833
17834 // Check for invalid 'foo::'.
17835 if (SS.isInvalid()) {
17836 Name = nullptr;
17837 goto CreateNewDecl;
17838 }
17839
17840 // If this is a friend or a reference to a class in a dependent
17841 // context, don't try to make a decl for it.
17842 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
17843 DC = computeDeclContext(SS, false);
17844 if (!DC) {
17845 IsDependent = true;
17846 return true;
17847 }
17848 } else {
17849 DC = computeDeclContext(SS, true);
17850 if (!DC) {
17851 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
17852 << SS.getRange();
17853 return true;
17854 }
17855 }
17856
17857 if (RequireCompleteDeclContext(SS, DC))
17858 return true;
17859
17860 SearchDC = DC;
17861 // Look-up name inside 'foo::'.
17863
17864 if (Previous.isAmbiguous())
17865 return true;
17866
17867 if (Previous.empty()) {
17868 // Name lookup did not find anything. However, if the
17869 // nested-name-specifier refers to the current instantiation,
17870 // and that current instantiation has any dependent base
17871 // classes, we might find something at instantiation time: treat
17872 // this as a dependent elaborated-type-specifier.
17873 // But this only makes any sense for reference-like lookups.
17874 if (Previous.wasNotFoundInCurrentInstantiation() &&
17875 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)) {
17876 IsDependent = true;
17877 return true;
17878 }
17879
17880 // A tag 'foo::bar' must already exist.
17881 Diag(NameLoc, diag::err_not_tag_in_scope)
17882 << Kind << Name << DC << SS.getRange();
17883 Name = nullptr;
17884 Invalid = true;
17885 goto CreateNewDecl;
17886 }
17887 } else if (Name) {
17888 // C++14 [class.mem]p14:
17889 // If T is the name of a class, then each of the following shall have a
17890 // name different from T:
17891 // -- every member of class T that is itself a type
17892 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
17893 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
17894 return true;
17895
17896 // If this is a named struct, check to see if there was a previous forward
17897 // declaration or definition.
17898 // FIXME: We're looking into outer scopes here, even when we
17899 // shouldn't be. Doing so can result in ambiguities that we
17900 // shouldn't be diagnosing.
17901 LookupName(Previous, S);
17902
17903 // When declaring or defining a tag, ignore ambiguities introduced
17904 // by types using'ed into this scope.
17905 if (Previous.isAmbiguous() &&
17907 LookupResult::Filter F = Previous.makeFilter();
17908 while (F.hasNext()) {
17909 NamedDecl *ND = F.next();
17910 if (!ND->getDeclContext()->getRedeclContext()->Equals(
17911 SearchDC->getRedeclContext()))
17912 F.erase();
17913 }
17914 F.done();
17915 }
17916
17917 // C++11 [namespace.memdef]p3:
17918 // If the name in a friend declaration is neither qualified nor
17919 // a template-id and the declaration is a function or an
17920 // elaborated-type-specifier, the lookup to determine whether
17921 // the entity has been previously declared shall not consider
17922 // any scopes outside the innermost enclosing namespace.
17923 //
17924 // MSVC doesn't implement the above rule for types, so a friend tag
17925 // declaration may be a redeclaration of a type declared in an enclosing
17926 // scope. They do implement this rule for friend functions.
17927 //
17928 // Does it matter that this should be by scope instead of by
17929 // semantic context?
17930 if (!Previous.empty() && TUK == TagUseKind::Friend) {
17931 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
17932 LookupResult::Filter F = Previous.makeFilter();
17933 bool FriendSawTagOutsideEnclosingNamespace = false;
17934 while (F.hasNext()) {
17935 NamedDecl *ND = F.next();
17937 if (DC->isFileContext() &&
17938 !EnclosingNS->Encloses(ND->getDeclContext())) {
17939 if (getLangOpts().MSVCCompat)
17940 FriendSawTagOutsideEnclosingNamespace = true;
17941 else
17942 F.erase();
17943 }
17944 }
17945 F.done();
17946
17947 // Diagnose this MSVC extension in the easy case where lookup would have
17948 // unambiguously found something outside the enclosing namespace.
17949 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
17950 NamedDecl *ND = Previous.getFoundDecl();
17951 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
17952 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
17953 }
17954 }
17955
17956 // Note: there used to be some attempt at recovery here.
17957 if (Previous.isAmbiguous())
17958 return true;
17959
17960 if (!getLangOpts().CPlusPlus && TUK != TagUseKind::Reference) {
17961 // FIXME: This makes sure that we ignore the contexts associated
17962 // with C structs, unions, and enums when looking for a matching
17963 // tag declaration or definition. See the similar lookup tweak
17964 // in Sema::LookupName; is there a better way to deal with this?
17966 SearchDC = SearchDC->getParent();
17967 } else if (getLangOpts().CPlusPlus) {
17968 // Inside ObjCContainer want to keep it as a lexical decl context but go
17969 // past it (most often to TranslationUnit) to find the semantic decl
17970 // context.
17971 while (isa<ObjCContainerDecl>(SearchDC))
17972 SearchDC = SearchDC->getParent();
17973 }
17974 } else if (getLangOpts().CPlusPlus) {
17975 // Don't use ObjCContainerDecl as the semantic decl context for anonymous
17976 // TagDecl the same way as we skip it for named TagDecl.
17977 while (isa<ObjCContainerDecl>(SearchDC))
17978 SearchDC = SearchDC->getParent();
17979 }
17980
17981 if (Previous.isSingleResult() &&
17982 Previous.getFoundDecl()->isTemplateParameter()) {
17983 // Maybe we will complain about the shadowed template parameter.
17984 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
17985 // Just pretend that we didn't see the previous declaration.
17986 Previous.clear();
17987 }
17988
17989 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
17990 DC->Equals(getStdNamespace())) {
17991 if (Name->isStr("bad_alloc")) {
17992 // This is a declaration of or a reference to "std::bad_alloc".
17993 isStdBadAlloc = true;
17994
17995 // If std::bad_alloc has been implicitly declared (but made invisible to
17996 // name lookup), fill in this implicit declaration as the previous
17997 // declaration, so that the declarations get chained appropriately.
17998 if (Previous.empty() && StdBadAlloc)
17999 Previous.addDecl(getStdBadAlloc());
18000 } else if (Name->isStr("align_val_t")) {
18001 isStdAlignValT = true;
18002 if (Previous.empty() && StdAlignValT)
18003 Previous.addDecl(getStdAlignValT());
18004 }
18005 }
18006
18007 // If we didn't find a previous declaration, and this is a reference
18008 // (or friend reference), move to the correct scope. In C++, we
18009 // also need to do a redeclaration lookup there, just in case
18010 // there's a shadow friend decl.
18011 if (Name && Previous.empty() &&
18012 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
18013 IsTemplateParamOrArg)) {
18014 if (Invalid) goto CreateNewDecl;
18015 assert(SS.isEmpty());
18016
18017 if (TUK == TagUseKind::Reference || IsTemplateParamOrArg) {
18018 // C++ [basic.scope.pdecl]p5:
18019 // -- for an elaborated-type-specifier of the form
18020 //
18021 // class-key identifier
18022 //
18023 // if the elaborated-type-specifier is used in the
18024 // decl-specifier-seq or parameter-declaration-clause of a
18025 // function defined in namespace scope, the identifier is
18026 // declared as a class-name in the namespace that contains
18027 // the declaration; otherwise, except as a friend
18028 // declaration, the identifier is declared in the smallest
18029 // non-class, non-function-prototype scope that contains the
18030 // declaration.
18031 //
18032 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
18033 // C structs and unions.
18034 //
18035 // It is an error in C++ to declare (rather than define) an enum
18036 // type, including via an elaborated type specifier. We'll
18037 // diagnose that later; for now, declare the enum in the same
18038 // scope as we would have picked for any other tag type.
18039 //
18040 // GNU C also supports this behavior as part of its incomplete
18041 // enum types extension, while GNU C++ does not.
18042 //
18043 // Find the context where we'll be declaring the tag.
18044 // FIXME: We would like to maintain the current DeclContext as the
18045 // lexical context,
18046 SearchDC = getTagInjectionContext(SearchDC);
18047
18048 // Find the scope where we'll be declaring the tag.
18050 } else {
18051 assert(TUK == TagUseKind::Friend);
18052 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(SearchDC);
18053
18054 // C++ [namespace.memdef]p3:
18055 // If a friend declaration in a non-local class first declares a
18056 // class or function, the friend class or function is a member of
18057 // the innermost enclosing namespace.
18058 SearchDC = RD->isLocalClass() ? RD->isLocalClass()
18059 : SearchDC->getEnclosingNamespaceContext();
18060 }
18061
18062 // In C++, we need to do a redeclaration lookup to properly
18063 // diagnose some problems.
18064 // FIXME: redeclaration lookup is also used (with and without C++) to find a
18065 // hidden declaration so that we don't get ambiguity errors when using a
18066 // type declared by an elaborated-type-specifier. In C that is not correct
18067 // and we should instead merge compatible types found by lookup.
18068 if (getLangOpts().CPlusPlus) {
18069 // FIXME: This can perform qualified lookups into function contexts,
18070 // which are meaningless.
18071 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18072 LookupQualifiedName(Previous, SearchDC);
18073 } else {
18074 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18075 LookupName(Previous, S);
18076 }
18077 }
18078
18079 // If we have a known previous declaration to use, then use it.
18080 if (Previous.empty() && SkipBody && SkipBody->Previous)
18081 Previous.addDecl(SkipBody->Previous);
18082
18083 if (!Previous.empty()) {
18084 NamedDecl *PrevDecl = Previous.getFoundDecl();
18085 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
18086
18087 // It's okay to have a tag decl in the same scope as a typedef
18088 // which hides a tag decl in the same scope. Finding this
18089 // with a redeclaration lookup can only actually happen in C++.
18090 //
18091 // This is also okay for elaborated-type-specifiers, which is
18092 // technically forbidden by the current standard but which is
18093 // okay according to the likely resolution of an open issue;
18094 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
18095 if (getLangOpts().CPlusPlus) {
18096 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
18097 if (TagDecl *Tag = TD->getUnderlyingType()->getAsTagDecl()) {
18098 if (Tag->getDeclName() == Name &&
18099 Tag->getDeclContext()->getRedeclContext()
18100 ->Equals(TD->getDeclContext()->getRedeclContext())) {
18101 PrevDecl = Tag;
18102 Previous.clear();
18103 Previous.addDecl(Tag);
18104 Previous.resolveKind();
18105 }
18106 }
18107 } else if (auto *RD = dyn_cast<CXXRecordDecl>(PrevDecl);
18108 TUK == TagUseKind::Reference && RD &&
18109 RD->isInjectedClassName()) {
18110 // If lookup found the injected class name, the previous declaration is
18111 // the class being injected into.
18112 PrevDecl = cast<TagDecl>(RD->getDeclContext());
18113 Previous.clear();
18114 Previous.addDecl(PrevDecl);
18115 Previous.resolveKind();
18116 IsInjectedClassName = true;
18117 }
18118 }
18119
18120 // If this is a redeclaration of a using shadow declaration, it must
18121 // declare a tag in the same context. In MSVC mode, we allow a
18122 // redefinition if either context is within the other.
18123 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
18124 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
18125 if (SS.isEmpty() && TUK != TagUseKind::Reference &&
18126 TUK != TagUseKind::Friend &&
18127 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
18128 !(OldTag && isAcceptableTagRedeclContext(
18129 *this, OldTag->getDeclContext(), SearchDC))) {
18130 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
18131 Diag(Shadow->getTargetDecl()->getLocation(),
18132 diag::note_using_decl_target);
18133 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
18134 << 0;
18135 // Recover by ignoring the old declaration.
18136 Previous.clear();
18137 goto CreateNewDecl;
18138 }
18139 }
18140
18141 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
18142 // If this is a use of a previous tag, or if the tag is already declared
18143 // in the same scope (so that the definition/declaration completes or
18144 // rementions the tag), reuse the decl.
18145 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
18146 isDeclInScope(DirectPrevDecl, SearchDC, S,
18147 SS.isNotEmpty() || isMemberSpecialization)) {
18148 // Make sure that this wasn't declared as an enum and now used as a
18149 // struct or something similar.
18150 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
18151 TUK == TagUseKind::Definition, KWLoc,
18152 Name)) {
18153 bool SafeToContinue =
18154 (PrevTagDecl->getTagKind() != TagTypeKind::Enum &&
18155 Kind != TagTypeKind::Enum);
18156 if (SafeToContinue)
18157 Diag(KWLoc, diag::err_use_with_wrong_tag)
18158 << Name
18160 PrevTagDecl->getKindName());
18161 else
18162 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
18163 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
18164
18165 if (SafeToContinue)
18166 Kind = PrevTagDecl->getTagKind();
18167 else {
18168 // Recover by making this an anonymous redefinition.
18169 Name = nullptr;
18170 Previous.clear();
18171 Invalid = true;
18172 }
18173 }
18174
18175 if (Kind == TagTypeKind::Enum &&
18176 PrevTagDecl->getTagKind() == TagTypeKind::Enum) {
18177 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
18178 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)
18179 return PrevTagDecl;
18180
18181 QualType EnumUnderlyingTy;
18182 if (TypeSourceInfo *TI =
18183 dyn_cast_if_present<TypeSourceInfo *>(EnumUnderlying))
18184 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
18185 else if (const Type *T =
18186 dyn_cast_if_present<const Type *>(EnumUnderlying))
18187 EnumUnderlyingTy = QualType(T, 0);
18188
18189 // All conflicts with previous declarations are recovered by
18190 // returning the previous declaration, unless this is a definition,
18191 // in which case we want the caller to bail out.
18192 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
18193 ScopedEnum, EnumUnderlyingTy,
18194 IsFixed, PrevEnum))
18195 return TUK == TagUseKind::Declaration ? PrevTagDecl : nullptr;
18196 }
18197
18198 // C++11 [class.mem]p1:
18199 // A member shall not be declared twice in the member-specification,
18200 // except that a nested class or member class template can be declared
18201 // and then later defined.
18202 if (TUK == TagUseKind::Declaration && PrevDecl->isCXXClassMember() &&
18203 S->isDeclScope(PrevDecl)) {
18204 Diag(NameLoc, diag::ext_member_redeclared);
18205 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
18206 }
18207
18208 if (!Invalid) {
18209 // If this is a use, just return the declaration we found, unless
18210 // we have attributes.
18211 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18212 if (!Attrs.empty()) {
18213 // FIXME: Diagnose these attributes. For now, we create a new
18214 // declaration to hold them.
18215 } else if (TUK == TagUseKind::Reference &&
18216 (PrevTagDecl->getFriendObjectKind() ==
18218 PrevDecl->getOwningModule() != getCurrentModule()) &&
18219 SS.isEmpty()) {
18220 // This declaration is a reference to an existing entity, but
18221 // has different visibility from that entity: it either makes
18222 // a friend visible or it makes a type visible in a new module.
18223 // In either case, create a new declaration. We only do this if
18224 // the declaration would have meant the same thing if no prior
18225 // declaration were found, that is, if it was found in the same
18226 // scope where we would have injected a declaration.
18227 if (!getTagInjectionContext(CurContext)->getRedeclContext()
18228 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
18229 return PrevTagDecl;
18230 // This is in the injected scope, create a new declaration in
18231 // that scope.
18233 } else {
18234 return PrevTagDecl;
18235 }
18236 }
18237
18238 // Diagnose attempts to redefine a tag.
18239 if (TUK == TagUseKind::Definition) {
18240 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
18241 // If the type is currently being defined, complain
18242 // about a nested redefinition.
18243 if (Def->isBeingDefined()) {
18244 Diag(NameLoc, diag::err_nested_redefinition) << Name;
18245 Diag(PrevTagDecl->getLocation(),
18246 diag::note_previous_definition);
18247 Name = nullptr;
18248 Previous.clear();
18249 Invalid = true;
18250 } else {
18251 // If we're defining a specialization and the previous
18252 // definition is from an implicit instantiation, don't emit an
18253 // error here; we'll catch this in the general case below.
18254 bool IsExplicitSpecializationAfterInstantiation = false;
18255 if (isMemberSpecialization) {
18256 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
18257 IsExplicitSpecializationAfterInstantiation =
18258 RD->getTemplateSpecializationKind() !=
18260 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
18261 IsExplicitSpecializationAfterInstantiation =
18262 ED->getTemplateSpecializationKind() !=
18264 }
18265
18266 // Note that clang allows ODR-like semantics for ObjC/C, i.e.,
18267 // do not keep more that one definition around (merge them).
18268 // However, ensure the decl passes the structural compatibility
18269 // check in C11 6.2.7/1 (or 6.1.2.6/1 in C89).
18270 NamedDecl *Hidden = nullptr;
18271 bool HiddenDefVisible = false;
18272 if (SkipBody &&
18273 (isRedefinitionAllowedFor(Def, &Hidden, HiddenDefVisible) ||
18274 getLangOpts().C23)) {
18275 // There is a definition of this tag, but it is not visible.
18276 // We explicitly make use of C++'s one definition rule here,
18277 // and assume that this definition is identical to the hidden
18278 // one we already have. Make the existing definition visible
18279 // and use it in place of this one.
18280 if (!getLangOpts().CPlusPlus) {
18281 // Postpone making the old definition visible until after we
18282 // complete parsing the new one and do the structural
18283 // comparison.
18284 SkipBody->CheckSameAsPrevious = true;
18285 SkipBody->New = createTagFromNewDecl();
18286 SkipBody->Previous = Def;
18287
18288 ProcessDeclAttributeList(S, SkipBody->New, Attrs);
18289 return Def;
18290 }
18291
18292 SkipBody->ShouldSkip = true;
18293 SkipBody->Previous = Def;
18294 if (!HiddenDefVisible && Hidden)
18296 // Carry on and handle it like a normal definition. We'll
18297 // skip starting the definition later.
18298
18299 } else if (!IsExplicitSpecializationAfterInstantiation) {
18300 // A redeclaration in function prototype scope in C isn't
18301 // visible elsewhere, so merely issue a warning.
18302 if (!getLangOpts().CPlusPlus &&
18304 Diag(NameLoc, diag::warn_redefinition_in_param_list)
18305 << Name;
18306 else
18307 Diag(NameLoc, diag::err_redefinition) << Name;
18309 NameLoc.isValid() ? NameLoc : KWLoc);
18310 // If this is a redefinition, recover by making this
18311 // struct be anonymous, which will make any later
18312 // references get the previous definition.
18313 Name = nullptr;
18314 Previous.clear();
18315 Invalid = true;
18316 }
18317 }
18318 }
18319
18320 // Okay, this is definition of a previously declared or referenced
18321 // tag. We're going to create a new Decl for it.
18322 }
18323
18324 // Okay, we're going to make a redeclaration. If this is some kind
18325 // of reference, make sure we build the redeclaration in the same DC
18326 // as the original, and ignore the current access specifier.
18327 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
18328 SearchDC = PrevTagDecl->getDeclContext();
18329 AS = AS_none;
18330 }
18331 }
18332 // If we get here we have (another) forward declaration or we
18333 // have a definition. Just create a new decl.
18334
18335 } else {
18336 // If we get here, this is a definition of a new tag type in a nested
18337 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
18338 // new decl/type. We set PrevDecl to NULL so that the entities
18339 // have distinct types.
18340 Previous.clear();
18341 }
18342 // If we get here, we're going to create a new Decl. If PrevDecl
18343 // is non-NULL, it's a definition of the tag declared by
18344 // PrevDecl. If it's NULL, we have a new definition.
18345
18346 // Otherwise, PrevDecl is not a tag, but was found with tag
18347 // lookup. This is only actually possible in C++, where a few
18348 // things like templates still live in the tag namespace.
18349 } else {
18350 // Use a better diagnostic if an elaborated-type-specifier
18351 // found the wrong kind of type on the first
18352 // (non-redeclaration) lookup.
18353 if ((TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) &&
18354 !Previous.isForRedeclaration()) {
18355 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
18356 Diag(NameLoc, diag::err_tag_reference_non_tag)
18357 << PrevDecl << NTK << Kind;
18358 Diag(PrevDecl->getLocation(), diag::note_declared_at);
18359 Invalid = true;
18360
18361 // Otherwise, only diagnose if the declaration is in scope.
18362 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
18363 SS.isNotEmpty() || isMemberSpecialization)) {
18364 // do nothing
18365
18366 // Diagnose implicit declarations introduced by elaborated types.
18367 } else if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18368 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
18369 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
18370 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
18371 Invalid = true;
18372
18373 // Otherwise it's a declaration. Call out a particularly common
18374 // case here.
18375 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
18376 unsigned Kind = 0;
18377 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
18378 Diag(NameLoc, diag::err_tag_definition_of_typedef)
18379 << Name << Kind << TND->getUnderlyingType();
18380 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
18381 Invalid = true;
18382
18383 // Otherwise, diagnose.
18384 } else {
18385 // The tag name clashes with something else in the target scope,
18386 // issue an error and recover by making this tag be anonymous.
18387 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
18388 notePreviousDefinition(PrevDecl, NameLoc);
18389 Name = nullptr;
18390 Invalid = true;
18391 }
18392
18393 // The existing declaration isn't relevant to us; we're in a
18394 // new scope, so clear out the previous declaration.
18395 Previous.clear();
18396 }
18397 }
18398
18399CreateNewDecl:
18400
18401 TagDecl *PrevDecl = nullptr;
18402 if (Previous.isSingleResult())
18403 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
18404
18405 // If there is an identifier, use the location of the identifier as the
18406 // location of the decl, otherwise use the location of the struct/union
18407 // keyword.
18408 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
18409
18410 // Otherwise, create a new declaration. If there is a previous
18411 // declaration of the same entity, the two will be linked via
18412 // PrevDecl.
18413 TagDecl *New;
18414
18415 if (Kind == TagTypeKind::Enum) {
18416 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18417 // enum X { A, B, C } D; D should chain to X.
18418 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
18419 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
18420 ScopedEnumUsesClassTag, IsFixed);
18421
18422 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
18424
18425 // If this is an undefined enum, warn.
18426 if (TUK != TagUseKind::Definition && !Invalid) {
18427 TagDecl *Def;
18428 if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
18429 // C++0x: 7.2p2: opaque-enum-declaration.
18430 // Conflicts are diagnosed above. Do nothing.
18431 }
18432 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
18433 Diag(Loc, diag::ext_forward_ref_enum_def)
18434 << New;
18435 Diag(Def->getLocation(), diag::note_previous_definition);
18436 } else {
18437 unsigned DiagID = diag::ext_forward_ref_enum;
18438 if (getLangOpts().MSVCCompat)
18439 DiagID = diag::ext_ms_forward_ref_enum;
18440 else if (getLangOpts().CPlusPlus)
18441 DiagID = diag::err_forward_ref_enum;
18442 Diag(Loc, DiagID);
18443 }
18444 }
18445
18446 if (EnumUnderlying) {
18448 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying))
18450 else
18451 ED->setIntegerType(QualType(cast<const Type *>(EnumUnderlying), 0));
18452 QualType EnumTy = ED->getIntegerType();
18453 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
18454 ? Context.getPromotedIntegerType(EnumTy)
18455 : EnumTy);
18456 assert(ED->isComplete() && "enum with type should be complete");
18457 }
18458 } else {
18459 // struct/union/class
18460
18461 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18462 // struct X { int A; } D; D should chain to X.
18463 if (getLangOpts().CPlusPlus) {
18464 // FIXME: Look for a way to use RecordDecl for simple structs.
18465 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
18466 cast_or_null<CXXRecordDecl>(PrevDecl));
18467
18468 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
18470 } else
18471 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
18472 cast_or_null<RecordDecl>(PrevDecl));
18473 }
18474
18475 // Only C23 and later allow defining new types in 'offsetof()'.
18476 if (OOK != OffsetOfKind::Outside && TUK == TagUseKind::Definition &&
18478 Diag(New->getLocation(), diag::ext_type_defined_in_offsetof)
18479 << (OOK == OffsetOfKind::Macro) << New->getSourceRange();
18480
18481 // C++11 [dcl.type]p3:
18482 // A type-specifier-seq shall not define a class or enumeration [...].
18483 if (!Invalid && getLangOpts().CPlusPlus &&
18484 (IsTypeSpecifier || IsTemplateParamOrArg) &&
18485 TUK == TagUseKind::Definition) {
18486 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
18487 << Context.getCanonicalTagType(New);
18488 Invalid = true;
18489 }
18490
18492 DC->getDeclKind() == Decl::Enum) {
18493 Diag(New->getLocation(), diag::err_type_defined_in_enum)
18494 << Context.getCanonicalTagType(New);
18495 Invalid = true;
18496 }
18497
18498 // Maybe add qualifier info.
18499 if (SS.isNotEmpty()) {
18500 if (SS.isSet()) {
18501 // If this is either a declaration or a definition, check the
18502 // nested-name-specifier against the current context.
18503 if ((TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration) &&
18504 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
18505 /*TemplateId=*/nullptr,
18506 isMemberSpecialization))
18507 Invalid = true;
18508
18509 New->setQualifierInfo(SS.getWithLocInContext(Context));
18510 if (TemplateParameterLists.size() > 0) {
18511 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
18512 }
18513 }
18514 else
18515 Invalid = true;
18516 }
18517
18518 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
18519 // Add alignment attributes if necessary; these attributes are checked when
18520 // the ASTContext lays out the structure.
18521 //
18522 // It is important for implementing the correct semantics that this
18523 // happen here (in ActOnTag). The #pragma pack stack is
18524 // maintained as a result of parser callbacks which can occur at
18525 // many points during the parsing of a struct declaration (because
18526 // the #pragma tokens are effectively skipped over during the
18527 // parsing of the struct).
18528 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
18529 if (LangOpts.HLSL)
18530 RD->addAttr(PackedAttr::CreateImplicit(Context));
18533 }
18534 }
18535
18536 if (ModulePrivateLoc.isValid()) {
18537 if (isMemberSpecialization)
18538 Diag(New->getLocation(), diag::err_module_private_specialization)
18539 << 2
18540 << FixItHint::CreateRemoval(ModulePrivateLoc);
18541 // __module_private__ does not apply to local classes. However, we only
18542 // diagnose this as an error when the declaration specifiers are
18543 // freestanding. Here, we just ignore the __module_private__.
18544 else if (!SearchDC->isFunctionOrMethod())
18545 New->setModulePrivate();
18546 }
18547
18548 // If this is a specialization of a member class (of a class template),
18549 // check the specialization.
18550 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
18551 Invalid = true;
18552
18553 // If we're declaring or defining a tag in function prototype scope in C,
18554 // note that this type can only be used within the function and add it to
18555 // the list of decls to inject into the function definition scope. However,
18556 // in C23 and later, while the type is only visible within the function, the
18557 // function can be called with a compatible type defined in the same TU, so
18558 // we silence the diagnostic in C23 and up. This matches the behavior of GCC.
18559 if ((Name || Kind == TagTypeKind::Enum) &&
18560 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
18561 if (getLangOpts().CPlusPlus) {
18562 // C++ [dcl.fct]p6:
18563 // Types shall not be defined in return or parameter types.
18564 if (TUK == TagUseKind::Definition && !IsTypeSpecifier) {
18565 Diag(Loc, diag::err_type_defined_in_param_type)
18566 << Name;
18567 Invalid = true;
18568 }
18569 if (TUK == TagUseKind::Declaration)
18570 Invalid = true;
18571 } else if (!PrevDecl) {
18572 // In C23 mode, if the declaration is complete, we do not want to
18573 // diagnose.
18574 if (!getLangOpts().C23 || TUK != TagUseKind::Definition)
18575 Diag(Loc, diag::warn_decl_in_param_list)
18576 << Context.getCanonicalTagType(New);
18577 }
18578 }
18579
18580 if (Invalid)
18581 New->setInvalidDecl();
18582
18583 // Set the lexical context. If the tag has a C++ scope specifier, the
18584 // lexical context will be different from the semantic context.
18585 New->setLexicalDeclContext(CurContext);
18586
18587 // Mark this as a friend decl if applicable.
18588 // In Microsoft mode, a friend declaration also acts as a forward
18589 // declaration so we always pass true to setObjectOfFriendDecl to make
18590 // the tag name visible.
18591 if (TUK == TagUseKind::Friend)
18592 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
18593
18594 // Set the access specifier.
18595 if (!Invalid && SearchDC->isRecord())
18596 SetMemberAccessSpecifier(New, PrevDecl, AS);
18597
18598 if (PrevDecl)
18600
18601 if (TUK == TagUseKind::Definition) {
18602 if (!SkipBody || !SkipBody->ShouldSkip) {
18603 New->startDefinition();
18604 } else {
18605 New->setCompleteDefinition();
18606 New->demoteThisDefinitionToDeclaration();
18607 }
18608 }
18609
18610 ProcessDeclAttributeList(S, New, Attrs);
18612
18613 // If this has an identifier, add it to the scope stack.
18614 if (TUK == TagUseKind::Friend || IsInjectedClassName) {
18615 // We might be replacing an existing declaration in the lookup tables;
18616 // if so, borrow its access specifier.
18617 if (PrevDecl)
18618 New->setAccess(PrevDecl->getAccess());
18619
18620 DeclContext *DC = New->getDeclContext()->getRedeclContext();
18622 if (Name) // can be null along some error paths
18623 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18624 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
18625 } else if (Name) {
18626 S = getNonFieldDeclScope(S);
18627 PushOnScopeChains(New, S, true);
18628 } else {
18629 CurContext->addDecl(New);
18630 }
18631
18632 // If this is the C FILE type, notify the AST context.
18633 if (IdentifierInfo *II = New->getIdentifier())
18634 if (!New->isInvalidDecl() &&
18635 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
18636 II->isStr("FILE"))
18637 Context.setFILEDecl(New);
18638
18639 if (PrevDecl)
18640 mergeDeclAttributes(New, PrevDecl);
18641
18642 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) {
18645 }
18646
18647 // If there's a #pragma GCC visibility in scope, set the visibility of this
18648 // record.
18650
18651 // If this is not a definition, process API notes for it now.
18652 if (TUK != TagUseKind::Definition)
18654
18655 if (isMemberSpecialization && !New->isInvalidDecl())
18657
18658 OwnedDecl = true;
18659 // In C++, don't return an invalid declaration. We can't recover well from
18660 // the cases where we make the type anonymous.
18661 if (Invalid && getLangOpts().CPlusPlus) {
18662 if (New->isBeingDefined())
18663 if (auto RD = dyn_cast<RecordDecl>(New))
18664 RD->completeDefinition();
18665 return true;
18666 } else if (SkipBody && SkipBody->ShouldSkip) {
18667 return SkipBody->Previous;
18668 } else {
18669 return New;
18670 }
18671}
18672
18675 TagDecl *Tag = cast<TagDecl>(TagD);
18676
18677 // Enter the tag context.
18678 PushDeclContext(S, Tag);
18679
18681
18682 // If there's a #pragma GCC visibility in scope, set the visibility of this
18683 // record.
18685}
18686
18688 SkipBodyInfo &SkipBody) {
18689 if (!hasStructuralCompatLayout(Prev, SkipBody.New))
18690 return false;
18691
18692 // Make the previous decl visible.
18694 CleanupMergedEnum(S, SkipBody.New);
18695 return true;
18696}
18697
18699 Scope *S, Decl *TagD, SourceLocation FinalLoc, bool IsFinalSpelledSealed,
18700 bool IsAbstract, SourceLocation TriviallyRelocatable,
18701 SourceLocation Replaceable, SourceLocation LBraceLoc) {
18704
18705 FieldCollector->StartClass();
18706
18707 if (!Record->getIdentifier())
18708 return;
18709
18710 if (IsAbstract)
18711 Record->markAbstract();
18712
18713 if (FinalLoc.isValid()) {
18714 Record->addAttr(FinalAttr::Create(Context, FinalLoc,
18715 IsFinalSpelledSealed
18716 ? FinalAttr::Keyword_sealed
18717 : FinalAttr::Keyword_final));
18718 }
18719
18720 if (TriviallyRelocatable.isValid())
18721 Record->addAttr(
18722 TriviallyRelocatableAttr::Create(Context, TriviallyRelocatable));
18723
18724 if (Replaceable.isValid())
18725 Record->addAttr(ReplaceableAttr::Create(Context, Replaceable));
18726
18727 // C++ [class]p2:
18728 // [...] The class-name is also inserted into the scope of the
18729 // class itself; this is known as the injected-class-name. For
18730 // purposes of access checking, the injected-class-name is treated
18731 // as if it were a public member name.
18732 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
18733 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
18734 Record->getLocation(), Record->getIdentifier());
18735 InjectedClassName->setImplicit();
18736 InjectedClassName->setAccess(AS_public);
18737 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
18738 InjectedClassName->setDescribedClassTemplate(Template);
18739
18740 PushOnScopeChains(InjectedClassName, S);
18741 assert(InjectedClassName->isInjectedClassName() &&
18742 "Broken injected-class-name");
18743}
18744
18746 SourceRange BraceRange) {
18748 TagDecl *Tag = cast<TagDecl>(TagD);
18749 Tag->setBraceRange(BraceRange);
18750
18751 // Make sure we "complete" the definition even it is invalid.
18752 if (Tag->isBeingDefined()) {
18753 assert(Tag->isInvalidDecl() && "We should already have completed it");
18754 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
18755 RD->completeDefinition();
18756 }
18757
18758 if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
18759 FieldCollector->FinishClass();
18760 if (RD->hasAttr<SYCLSpecialClassAttr>()) {
18761 auto *Def = RD->getDefinition();
18762 assert(Def && "The record is expected to have a completed definition");
18763 unsigned NumInitMethods = 0;
18764 for (auto *Method : Def->methods()) {
18765 if (!Method->getIdentifier())
18766 continue;
18767 if (Method->getName() == "__init")
18768 NumInitMethods++;
18769 }
18770 if (NumInitMethods > 1 || !Def->hasInitMethod())
18771 Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
18772 }
18773
18774 // If we're defining a dynamic class in a module interface unit, we always
18775 // need to produce the vtable for it, even if the vtable is not used in the
18776 // current TU.
18777 //
18778 // The case where the current class is not dynamic is handled in
18779 // MarkVTableUsed.
18780 if (getCurrentModule() && getCurrentModule()->isInterfaceOrPartition())
18781 MarkVTableUsed(RD->getLocation(), RD, /*DefinitionRequired=*/true);
18782 }
18783
18784 // Exit this scope of this tag's definition.
18786
18787 if (getCurLexicalContext()->isObjCContainer() &&
18788 Tag->getDeclContext()->isFileContext())
18789 Tag->setTopLevelDeclInObjCContainer();
18790
18791 // Notify the consumer that we've defined a tag.
18792 if (!Tag->isInvalidDecl())
18793 Consumer.HandleTagDeclDefinition(Tag);
18794
18795 // Clangs implementation of #pragma align(packed) differs in bitfield layout
18796 // from XLs and instead matches the XL #pragma pack(1) behavior.
18797 if (Context.getTargetInfo().getTriple().isOSAIX() &&
18798 AlignPackStack.hasValue()) {
18799 AlignPackInfo APInfo = AlignPackStack.CurrentValue;
18800 // Only diagnose #pragma align(packed).
18801 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
18802 return;
18803 const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
18804 if (!RD)
18805 return;
18806 // Only warn if there is at least 1 bitfield member.
18807 if (llvm::any_of(RD->fields(),
18808 [](const FieldDecl *FD) { return FD->isBitField(); }))
18809 Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
18810 }
18811}
18812
18815 TagDecl *Tag = cast<TagDecl>(TagD);
18816 Tag->setInvalidDecl();
18817
18818 // Make sure we "complete" the definition even it is invalid.
18819 if (Tag->isBeingDefined()) {
18820 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
18821 RD->completeDefinition();
18822 }
18823
18824 // We're undoing ActOnTagStartDefinition here, not
18825 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
18826 // the FieldCollector.
18827
18829}
18830
18831// Note that FieldName may be null for anonymous bitfields.
18833 const IdentifierInfo *FieldName,
18834 QualType FieldTy, bool IsMsStruct,
18835 Expr *BitWidth) {
18836 assert(BitWidth);
18837 if (BitWidth->containsErrors())
18838 return ExprError();
18839
18840 // C99 6.7.2.1p4 - verify the field type.
18841 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
18842 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
18843 // Handle incomplete and sizeless types with a specific error.
18844 if (RequireCompleteSizedType(FieldLoc, FieldTy,
18845 diag::err_field_incomplete_or_sizeless))
18846 return ExprError();
18847 if (FieldName)
18848 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
18849 << FieldName << FieldTy << BitWidth->getSourceRange();
18850 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
18851 << FieldTy << BitWidth->getSourceRange();
18853 return ExprError();
18854
18855 // If the bit-width is type- or value-dependent, don't try to check
18856 // it now.
18857 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
18858 return BitWidth;
18859
18860 llvm::APSInt Value;
18861 ExprResult ICE =
18863 if (ICE.isInvalid())
18864 return ICE;
18865 BitWidth = ICE.get();
18866
18867 // Zero-width bitfield is ok for anonymous field.
18868 if (Value == 0 && FieldName)
18869 return Diag(FieldLoc, diag::err_bitfield_has_zero_width)
18870 << FieldName << BitWidth->getSourceRange();
18871
18872 if (Value.isSigned() && Value.isNegative()) {
18873 if (FieldName)
18874 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
18875 << FieldName << toString(Value, 10);
18876 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
18877 << toString(Value, 10);
18878 }
18879
18880 // The size of the bit-field must not exceed our maximum permitted object
18881 // size.
18882 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
18883 return Diag(FieldLoc, diag::err_bitfield_too_wide)
18884 << !FieldName << FieldName << toString(Value, 10);
18885 }
18886
18887 if (!FieldTy->isDependentType()) {
18888 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
18889 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
18890 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
18891
18892 // Over-wide bitfields are an error in C or when using the MSVC bitfield
18893 // ABI.
18894 bool CStdConstraintViolation =
18895 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
18896 bool MSBitfieldViolation =
18897 Value.ugt(TypeStorageSize) &&
18898 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
18899 if (CStdConstraintViolation || MSBitfieldViolation) {
18900 unsigned DiagWidth =
18901 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
18902 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
18903 << (bool)FieldName << FieldName << toString(Value, 10)
18904 << !CStdConstraintViolation << DiagWidth;
18905 }
18906
18907 // Warn on types where the user might conceivably expect to get all
18908 // specified bits as value bits: that's all integral types other than
18909 // 'bool'.
18910 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
18911 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
18912 << FieldName << toString(Value, 10)
18913 << (unsigned)TypeWidth;
18914 }
18915 }
18916
18917 if (isa<ConstantExpr>(BitWidth))
18918 return BitWidth;
18919 return ConstantExpr::Create(getASTContext(), BitWidth, APValue{Value});
18920}
18921
18923 Declarator &D, Expr *BitfieldWidth) {
18924 FieldDecl *Res = HandleField(S, cast_if_present<RecordDecl>(TagD), DeclStart,
18925 D, BitfieldWidth,
18926 /*InitStyle=*/ICIS_NoInit, AS_public);
18927 return Res;
18928}
18929
18931 SourceLocation DeclStart,
18932 Declarator &D, Expr *BitWidth,
18933 InClassInitStyle InitStyle,
18934 AccessSpecifier AS) {
18935 if (D.isDecompositionDeclarator()) {
18937 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
18938 << Decomp.getSourceRange();
18939 return nullptr;
18940 }
18941
18942 const IdentifierInfo *II = D.getIdentifier();
18943 SourceLocation Loc = DeclStart;
18944 if (II) Loc = D.getIdentifierLoc();
18945
18947 QualType T = TInfo->getType();
18948 if (getLangOpts().CPlusPlus) {
18950
18953 D.setInvalidType();
18954 T = Context.IntTy;
18955 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
18956 }
18957 }
18958
18960
18962 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
18963 << getLangOpts().CPlusPlus17;
18966 diag::err_invalid_thread)
18968
18969 // Check to see if this name was declared as a member previously
18970 NamedDecl *PrevDecl = nullptr;
18971 LookupResult Previous(*this, II, Loc, LookupMemberName,
18973 LookupName(Previous, S);
18974 switch (Previous.getResultKind()) {
18977 PrevDecl = Previous.getAsSingle<NamedDecl>();
18978 break;
18979
18981 PrevDecl = Previous.getRepresentativeDecl();
18982 break;
18983
18987 break;
18988 }
18989 Previous.suppressDiagnostics();
18990
18991 if (PrevDecl && PrevDecl->isTemplateParameter()) {
18992 // Maybe we will complain about the shadowed template parameter.
18994 // Just pretend that we didn't see the previous declaration.
18995 PrevDecl = nullptr;
18996 }
18997
18998 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
18999 PrevDecl = nullptr;
19000
19001 bool Mutable
19002 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
19003 SourceLocation TSSL = D.getBeginLoc();
19004 FieldDecl *NewFD
19005 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
19006 TSSL, AS, PrevDecl, &D);
19007
19008 if (NewFD->isInvalidDecl())
19009 Record->setInvalidDecl();
19010
19012 NewFD->setModulePrivate();
19013
19014 if (NewFD->isInvalidDecl() && PrevDecl) {
19015 // Don't introduce NewFD into scope; there's already something
19016 // with the same name in the same scope.
19017 } else if (II) {
19018 PushOnScopeChains(NewFD, S);
19019 } else
19020 Record->addDecl(NewFD);
19021
19022 return NewFD;
19023}
19024
19026 TypeSourceInfo *TInfo,
19028 bool Mutable, Expr *BitWidth,
19029 InClassInitStyle InitStyle,
19030 SourceLocation TSSL,
19031 AccessSpecifier AS, NamedDecl *PrevDecl,
19032 Declarator *D) {
19033 const IdentifierInfo *II = Name.getAsIdentifierInfo();
19034 bool InvalidDecl = false;
19035 if (D) InvalidDecl = D->isInvalidType();
19036
19037 // If we receive a broken type, recover by assuming 'int' and
19038 // marking this declaration as invalid.
19039 if (T.isNull() || T->containsErrors()) {
19040 InvalidDecl = true;
19041 T = Context.IntTy;
19042 }
19043
19044 QualType EltTy = Context.getBaseElementType(T);
19045 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
19046 bool isIncomplete =
19047 LangOpts.HLSL // HLSL allows sizeless builtin types
19048 ? RequireCompleteType(Loc, EltTy, diag::err_incomplete_type)
19049 : RequireCompleteSizedType(Loc, EltTy,
19050 diag::err_field_incomplete_or_sizeless);
19051 if (isIncomplete) {
19052 // Fields of incomplete type force their record to be invalid.
19053 Record->setInvalidDecl();
19054 InvalidDecl = true;
19055 } else {
19056 NamedDecl *Def;
19057 EltTy->isIncompleteType(&Def);
19058 if (Def && Def->isInvalidDecl()) {
19059 Record->setInvalidDecl();
19060 InvalidDecl = true;
19061 }
19062 }
19063 }
19064
19065 // TR 18037 does not allow fields to be declared with address space
19066 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
19067 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
19068 Diag(Loc, diag::err_field_with_address_space);
19069 Record->setInvalidDecl();
19070 InvalidDecl = true;
19071 }
19072
19073 if (LangOpts.OpenCL) {
19074 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
19075 // used as structure or union field: image, sampler, event or block types.
19076 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
19077 T->isBlockPointerType()) {
19078 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
19079 Record->setInvalidDecl();
19080 InvalidDecl = true;
19081 }
19082 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
19083 // is enabled.
19084 if (BitWidth && !getOpenCLOptions().isAvailableOption(
19085 "__cl_clang_bitfields", LangOpts)) {
19086 Diag(Loc, diag::err_opencl_bitfields);
19087 InvalidDecl = true;
19088 }
19089 }
19090
19091 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
19092 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
19093 T.hasQualifiers()) {
19094 InvalidDecl = true;
19095 Diag(Loc, diag::err_anon_bitfield_qualifiers);
19096 }
19097
19098 // C99 6.7.2.1p8: A member of a structure or union may have any type other
19099 // than a variably modified type.
19100 if (!InvalidDecl && T->isVariablyModifiedType()) {
19102 TInfo, T, Loc, diag::err_typecheck_field_variable_size))
19103 InvalidDecl = true;
19104 }
19105
19106 // Fields can not have abstract class types
19107 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
19108 diag::err_abstract_type_in_decl,
19110 InvalidDecl = true;
19111
19112 if (InvalidDecl)
19113 BitWidth = nullptr;
19114 // If this is declared as a bit-field, check the bit-field.
19115 if (BitWidth) {
19116 BitWidth =
19117 VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get();
19118 if (!BitWidth) {
19119 InvalidDecl = true;
19120 BitWidth = nullptr;
19121 }
19122 }
19123
19124 // Check that 'mutable' is consistent with the type of the declaration.
19125 if (!InvalidDecl && Mutable) {
19126 unsigned DiagID = 0;
19127 if (T->isReferenceType())
19128 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
19129 : diag::err_mutable_reference;
19130 else if (T.isConstQualified())
19131 DiagID = diag::err_mutable_const;
19132
19133 if (DiagID) {
19134 SourceLocation ErrLoc = Loc;
19135 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
19136 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
19137 Diag(ErrLoc, DiagID);
19138 if (DiagID != diag::ext_mutable_reference) {
19139 Mutable = false;
19140 InvalidDecl = true;
19141 }
19142 }
19143 }
19144
19145 // C++11 [class.union]p8 (DR1460):
19146 // At most one variant member of a union may have a
19147 // brace-or-equal-initializer.
19148 if (InitStyle != ICIS_NoInit)
19150
19151 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
19152 BitWidth, Mutable, InitStyle);
19153 if (InvalidDecl)
19154 NewFD->setInvalidDecl();
19155
19156 if (!InvalidDecl)
19158
19159 if (PrevDecl && !isa<TagDecl>(PrevDecl) &&
19160 !PrevDecl->isPlaceholderVar(getLangOpts())) {
19161 Diag(Loc, diag::err_duplicate_member) << II;
19162 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
19163 NewFD->setInvalidDecl();
19164 }
19165
19166 if (!InvalidDecl && getLangOpts().CPlusPlus) {
19167 if (Record->isUnion()) {
19168 if (const auto *RD = EltTy->getAsCXXRecordDecl();
19169 RD && (RD->isBeingDefined() || RD->isCompleteDefinition())) {
19170
19171 // C++ [class.union]p1: An object of a class with a non-trivial
19172 // constructor, a non-trivial copy constructor, a non-trivial
19173 // destructor, or a non-trivial copy assignment operator
19174 // cannot be a member of a union, nor can an array of such
19175 // objects.
19176 if (CheckNontrivialField(NewFD))
19177 NewFD->setInvalidDecl();
19178 }
19179
19180 // C++ [class.union]p1: If a union contains a member of reference type,
19181 // the program is ill-formed, except when compiling with MSVC extensions
19182 // enabled.
19183 if (EltTy->isReferenceType()) {
19184 const bool HaveMSExt =
19185 getLangOpts().MicrosoftExt &&
19187
19188 Diag(NewFD->getLocation(),
19189 HaveMSExt ? diag::ext_union_member_of_reference_type
19190 : diag::err_union_member_of_reference_type)
19191 << NewFD->getDeclName() << EltTy;
19192 if (!HaveMSExt)
19193 NewFD->setInvalidDecl();
19194 }
19195 }
19196 }
19197
19198 // FIXME: We need to pass in the attributes given an AST
19199 // representation, not a parser representation.
19200 if (D) {
19201 // FIXME: The current scope is almost... but not entirely... correct here.
19202 ProcessDeclAttributes(getCurScope(), NewFD, *D);
19203
19204 if (NewFD->hasAttrs())
19206 }
19207
19208 // In auto-retain/release, infer strong retension for fields of
19209 // retainable type.
19210 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewFD))
19211 NewFD->setInvalidDecl();
19212
19213 if (T.isObjCGCWeak())
19214 Diag(Loc, diag::warn_attribute_weak_on_field);
19215
19216 // PPC MMA non-pointer types are not allowed as field types.
19217 if (Context.getTargetInfo().getTriple().isPPC64() &&
19218 PPC().CheckPPCMMAType(T, NewFD->getLocation()))
19219 NewFD->setInvalidDecl();
19220
19221 NewFD->setAccess(AS);
19222 return NewFD;
19223}
19224
19226 assert(FD);
19227 assert(getLangOpts().CPlusPlus && "valid check only for C++");
19228
19229 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
19230 return false;
19231
19232 QualType EltTy = Context.getBaseElementType(FD->getType());
19233 if (const auto *RDecl = EltTy->getAsCXXRecordDecl();
19234 RDecl && (RDecl->isBeingDefined() || RDecl->isCompleteDefinition())) {
19235 // We check for copy constructors before constructors
19236 // because otherwise we'll never get complaints about
19237 // copy constructors.
19238
19240 // We're required to check for any non-trivial constructors. Since the
19241 // implicit default constructor is suppressed if there are any
19242 // user-declared constructors, we just need to check that there is a
19243 // trivial default constructor and a trivial copy constructor. (We don't
19244 // worry about move constructors here, since this is a C++98 check.)
19245 if (RDecl->hasNonTrivialCopyConstructor())
19247 else if (!RDecl->hasTrivialDefaultConstructor())
19249 else if (RDecl->hasNonTrivialCopyAssignment())
19251 else if (RDecl->hasNonTrivialDestructor())
19253
19254 if (member != CXXSpecialMemberKind::Invalid) {
19255 if (!getLangOpts().CPlusPlus11 && getLangOpts().ObjCAutoRefCount &&
19256 RDecl->hasObjectMember()) {
19257 // Objective-C++ ARC: it is an error to have a non-trivial field of
19258 // a union. However, system headers in Objective-C programs
19259 // occasionally have Objective-C lifetime objects within unions,
19260 // and rather than cause the program to fail, we make those
19261 // members unavailable.
19262 SourceLocation Loc = FD->getLocation();
19263 if (getSourceManager().isInSystemHeader(Loc)) {
19264 if (!FD->hasAttr<UnavailableAttr>())
19265 FD->addAttr(UnavailableAttr::CreateImplicit(
19266 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
19267 return false;
19268 }
19269 }
19270
19271 Diag(FD->getLocation(),
19273 ? diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member
19274 : diag::err_illegal_union_or_anon_struct_member)
19275 << FD->getParent()->isUnion() << FD->getDeclName() << member;
19276 DiagnoseNontrivial(RDecl, member);
19277 return !getLangOpts().CPlusPlus11;
19278 }
19279 }
19280
19281 return false;
19282}
19283
19285 SmallVectorImpl<Decl *> &AllIvarDecls) {
19286 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
19287 return;
19288
19289 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
19290 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
19291
19292 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField())
19293 return;
19294 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
19295 if (!ID) {
19296 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
19297 if (!CD->IsClassExtension())
19298 return;
19299 }
19300 // No need to add this to end of @implementation.
19301 else
19302 return;
19303 }
19304 // All conditions are met. Add a new bitfield to the tail end of ivars.
19305 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
19306 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
19307 Expr *BitWidth =
19308 ConstantExpr::Create(Context, BW, APValue(llvm::APSInt(Zero)));
19309
19310 Ivar = ObjCIvarDecl::Create(
19311 Context, cast<ObjCContainerDecl>(CurContext), DeclLoc, DeclLoc, nullptr,
19312 Context.CharTy, Context.getTrivialTypeSourceInfo(Context.CharTy, DeclLoc),
19313 ObjCIvarDecl::Private, BitWidth, true);
19314 AllIvarDecls.push_back(Ivar);
19315}
19316
19317/// [class.dtor]p4:
19318/// At the end of the definition of a class, overload resolution is
19319/// performed among the prospective destructors declared in that class with
19320/// an empty argument list to select the destructor for the class, also
19321/// known as the selected destructor.
19322///
19323/// We do the overload resolution here, then mark the selected constructor in the AST.
19324/// Later CXXRecordDecl::getDestructor() will return the selected constructor.
19326 if (!Record->hasUserDeclaredDestructor()) {
19327 return;
19328 }
19329
19330 SourceLocation Loc = Record->getLocation();
19332
19333 for (auto *Decl : Record->decls()) {
19334 if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {
19335 if (DD->isInvalidDecl())
19336 continue;
19337 S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},
19338 OCS);
19339 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
19340 }
19341 }
19342
19343 if (OCS.empty()) {
19344 return;
19345 }
19347 unsigned Msg = 0;
19348 OverloadCandidateDisplayKind DisplayKind;
19349
19350 switch (OCS.BestViableFunction(S, Loc, Best)) {
19351 case OR_Success:
19352 case OR_Deleted:
19353 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function));
19354 break;
19355
19356 case OR_Ambiguous:
19357 Msg = diag::err_ambiguous_destructor;
19358 DisplayKind = OCD_AmbiguousCandidates;
19359 break;
19360
19362 Msg = diag::err_no_viable_destructor;
19363 DisplayKind = OCD_AllCandidates;
19364 break;
19365 }
19366
19367 if (Msg) {
19368 // OpenCL have got their own thing going with destructors. It's slightly broken,
19369 // but we allow it.
19370 if (!S.LangOpts.OpenCL) {
19371 PartialDiagnostic Diag = S.PDiag(Msg) << Record;
19372 OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {});
19373 Record->setInvalidDecl();
19374 }
19375 // It's a bit hacky: At this point we've raised an error but we want the
19376 // rest of the compiler to continue somehow working. However almost
19377 // everything we'll try to do with the class will depend on there being a
19378 // destructor. So let's pretend the first one is selected and hope for the
19379 // best.
19380 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function));
19381 }
19382}
19383
19384/// [class.mem.special]p5
19385/// Two special member functions are of the same kind if:
19386/// - they are both default constructors,
19387/// - they are both copy or move constructors with the same first parameter
19388/// type, or
19389/// - they are both copy or move assignment operators with the same first
19390/// parameter type and the same cv-qualifiers and ref-qualifier, if any.
19392 CXXMethodDecl *M1,
19393 CXXMethodDecl *M2,
19395 // We don't want to compare templates to non-templates: See
19396 // https://github.com/llvm/llvm-project/issues/59206
19398 return bool(M1->getDescribedFunctionTemplate()) ==
19400 // FIXME: better resolve CWG
19401 // https://cplusplus.github.io/CWG/issues/2787.html
19402 if (!Context.hasSameType(M1->getNonObjectParameter(0)->getType(),
19403 M2->getNonObjectParameter(0)->getType()))
19404 return false;
19405 if (!Context.hasSameType(M1->getFunctionObjectParameterReferenceType(),
19407 return false;
19408
19409 return true;
19410}
19411
19412/// [class.mem.special]p6:
19413/// An eligible special member function is a special member function for which:
19414/// - the function is not deleted,
19415/// - the associated constraints, if any, are satisfied, and
19416/// - no special member function of the same kind whose associated constraints
19417/// [CWG2595], if any, are satisfied is more constrained.
19421 SmallVector<bool, 4> SatisfactionStatus;
19422
19423 for (CXXMethodDecl *Method : Methods) {
19424 if (!Method->getTrailingRequiresClause())
19425 SatisfactionStatus.push_back(true);
19426 else {
19427 ConstraintSatisfaction Satisfaction;
19428 if (S.CheckFunctionConstraints(Method, Satisfaction))
19429 SatisfactionStatus.push_back(false);
19430 else
19431 SatisfactionStatus.push_back(Satisfaction.IsSatisfied);
19432 }
19433 }
19434
19435 for (size_t i = 0; i < Methods.size(); i++) {
19436 if (!SatisfactionStatus[i])
19437 continue;
19438 CXXMethodDecl *Method = Methods[i];
19439 CXXMethodDecl *OrigMethod = Method;
19440 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
19441 OrigMethod = cast<CXXMethodDecl>(MF);
19442
19444 bool AnotherMethodIsMoreConstrained = false;
19445 for (size_t j = 0; j < Methods.size(); j++) {
19446 if (i == j || !SatisfactionStatus[j])
19447 continue;
19448 CXXMethodDecl *OtherMethod = Methods[j];
19449 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
19450 OtherMethod = cast<CXXMethodDecl>(MF);
19451
19452 if (!AreSpecialMemberFunctionsSameKind(S.Context, OrigMethod, OtherMethod,
19453 CSM))
19454 continue;
19455
19457 if (!Other)
19458 continue;
19459 if (!Orig) {
19460 AnotherMethodIsMoreConstrained = true;
19461 break;
19462 }
19463 if (S.IsAtLeastAsConstrained(OtherMethod, {Other}, OrigMethod, {Orig},
19464 AnotherMethodIsMoreConstrained)) {
19465 // There was an error with the constraints comparison. Exit the loop
19466 // and don't consider this function eligible.
19467 AnotherMethodIsMoreConstrained = true;
19468 }
19469 if (AnotherMethodIsMoreConstrained)
19470 break;
19471 }
19472 // FIXME: Do not consider deleted methods as eligible after implementing
19473 // DR1734 and DR1496.
19474 if (!AnotherMethodIsMoreConstrained) {
19475 Method->setIneligibleOrNotSelected(false);
19476 Record->addedEligibleSpecialMemberFunction(Method,
19477 1 << llvm::to_underlying(CSM));
19478 }
19479 }
19480}
19481
19484 SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
19485 SmallVector<CXXMethodDecl *, 4> CopyConstructors;
19486 SmallVector<CXXMethodDecl *, 4> MoveConstructors;
19487 SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
19488 SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
19489
19490 for (auto *Decl : Record->decls()) {
19491 auto *MD = dyn_cast<CXXMethodDecl>(Decl);
19492 if (!MD) {
19493 auto *FTD = dyn_cast<FunctionTemplateDecl>(Decl);
19494 if (FTD)
19495 MD = dyn_cast<CXXMethodDecl>(FTD->getTemplatedDecl());
19496 }
19497 if (!MD)
19498 continue;
19499 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
19500 if (CD->isInvalidDecl())
19501 continue;
19502 if (CD->isDefaultConstructor())
19503 DefaultConstructors.push_back(MD);
19504 else if (CD->isCopyConstructor())
19505 CopyConstructors.push_back(MD);
19506 else if (CD->isMoveConstructor())
19507 MoveConstructors.push_back(MD);
19508 } else if (MD->isCopyAssignmentOperator()) {
19509 CopyAssignmentOperators.push_back(MD);
19510 } else if (MD->isMoveAssignmentOperator()) {
19511 MoveAssignmentOperators.push_back(MD);
19512 }
19513 }
19514
19515 SetEligibleMethods(S, Record, DefaultConstructors,
19517 SetEligibleMethods(S, Record, CopyConstructors,
19519 SetEligibleMethods(S, Record, MoveConstructors,
19521 SetEligibleMethods(S, Record, CopyAssignmentOperators,
19523 SetEligibleMethods(S, Record, MoveAssignmentOperators,
19525}
19526
19527bool Sema::EntirelyFunctionPointers(const RecordDecl *Record) {
19528 // Check to see if a FieldDecl is a pointer to a function.
19529 auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
19530 const FieldDecl *FD = dyn_cast<FieldDecl>(D);
19531 if (!FD) {
19532 // Check whether this is a forward declaration that was inserted by
19533 // Clang. This happens when a non-forward declared / defined type is
19534 // used, e.g.:
19535 //
19536 // struct foo {
19537 // struct bar *(*f)();
19538 // struct bar *(*g)();
19539 // };
19540 //
19541 // "struct bar" shows up in the decl AST as a "RecordDecl" with an
19542 // incomplete definition.
19543 if (const auto *TD = dyn_cast<TagDecl>(D))
19544 return !TD->isCompleteDefinition();
19545 return false;
19546 }
19547 QualType FieldType = FD->getType().getDesugaredType(Context);
19548 if (isa<PointerType>(FieldType)) {
19549 QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();
19550 return PointeeType.getDesugaredType(Context)->isFunctionType();
19551 }
19552 // If a member is a struct entirely of function pointers, that counts too.
19553 if (const auto *Record = FieldType->getAsRecordDecl();
19554 Record && Record->isStruct() && EntirelyFunctionPointers(Record))
19555 return true;
19556 return false;
19557 };
19558
19559 return llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl);
19560}
19561
19562void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
19563 ArrayRef<Decl *> Fields, SourceLocation LBrac,
19564 SourceLocation RBrac,
19565 const ParsedAttributesView &Attrs) {
19566 assert(EnclosingDecl && "missing record or interface decl");
19567
19568 // If this is an Objective-C @implementation or category and we have
19569 // new fields here we should reset the layout of the interface since
19570 // it will now change.
19571 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
19572 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
19573 switch (DC->getKind()) {
19574 default: break;
19575 case Decl::ObjCCategory:
19576 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
19577 break;
19578 case Decl::ObjCImplementation:
19579 Context.
19580 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
19581 break;
19582 }
19583 }
19584
19585 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
19586 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
19587
19588 // Start counting up the number of named members; make sure to include
19589 // members of anonymous structs and unions in the total.
19590 unsigned NumNamedMembers = 0;
19591 if (Record) {
19592 for (const auto *I : Record->decls()) {
19593 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
19594 if (IFD->getDeclName())
19595 ++NumNamedMembers;
19596 }
19597 }
19598
19599 // Verify that all the fields are okay.
19601 const FieldDecl *PreviousField = nullptr;
19602 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
19603 i != end; PreviousField = cast<FieldDecl>(*i), ++i) {
19604 FieldDecl *FD = cast<FieldDecl>(*i);
19605
19606 // Get the type for the field.
19607 const Type *FDTy = FD->getType().getTypePtr();
19608
19609 if (!FD->isAnonymousStructOrUnion()) {
19610 // Remember all fields written by the user.
19611 RecFields.push_back(FD);
19612 }
19613
19614 // If the field is already invalid for some reason, don't emit more
19615 // diagnostics about it.
19616 if (FD->isInvalidDecl()) {
19617 EnclosingDecl->setInvalidDecl();
19618 continue;
19619 }
19620
19621 // C99 6.7.2.1p2:
19622 // A structure or union shall not contain a member with
19623 // incomplete or function type (hence, a structure shall not
19624 // contain an instance of itself, but may contain a pointer to
19625 // an instance of itself), except that the last member of a
19626 // structure with more than one named member may have incomplete
19627 // array type; such a structure (and any union containing,
19628 // possibly recursively, a member that is such a structure)
19629 // shall not be a member of a structure or an element of an
19630 // array.
19631 bool IsLastField = (i + 1 == Fields.end());
19632 if (FDTy->isFunctionType()) {
19633 // Field declared as a function.
19634 Diag(FD->getLocation(), diag::err_field_declared_as_function)
19635 << FD->getDeclName();
19636 FD->setInvalidDecl();
19637 EnclosingDecl->setInvalidDecl();
19638 continue;
19639 } else if (FDTy->isIncompleteArrayType() &&
19640 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
19641 if (Record) {
19642 // Flexible array member.
19643 // Microsoft and g++ is more permissive regarding flexible array.
19644 // It will accept flexible array in union and also
19645 // as the sole element of a struct/class.
19646 unsigned DiagID = 0;
19647 if (!Record->isUnion() && !IsLastField) {
19648 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
19649 << FD->getDeclName() << FD->getType() << Record->getTagKind();
19650 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
19651 FD->setInvalidDecl();
19652 EnclosingDecl->setInvalidDecl();
19653 continue;
19654 } else if (Record->isUnion())
19655 DiagID = getLangOpts().MicrosoftExt
19656 ? diag::ext_flexible_array_union_ms
19657 : diag::ext_flexible_array_union_gnu;
19658 else if (NumNamedMembers < 1)
19659 DiagID = getLangOpts().MicrosoftExt
19660 ? diag::ext_flexible_array_empty_aggregate_ms
19661 : diag::ext_flexible_array_empty_aggregate_gnu;
19662
19663 if (DiagID)
19664 Diag(FD->getLocation(), DiagID)
19665 << FD->getDeclName() << Record->getTagKind();
19666 // While the layout of types that contain virtual bases is not specified
19667 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
19668 // virtual bases after the derived members. This would make a flexible
19669 // array member declared at the end of an object not adjacent to the end
19670 // of the type.
19671 if (CXXRecord && CXXRecord->getNumVBases() != 0)
19672 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
19673 << FD->getDeclName() << Record->getTagKind();
19674 if (!getLangOpts().C99)
19675 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
19676 << FD->getDeclName() << Record->getTagKind();
19677
19678 // If the element type has a non-trivial destructor, we would not
19679 // implicitly destroy the elements, so disallow it for now.
19680 //
19681 // FIXME: GCC allows this. We should probably either implicitly delete
19682 // the destructor of the containing class, or just allow this.
19683 QualType BaseElem = Context.getBaseElementType(FD->getType());
19684 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
19685 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
19686 << FD->getDeclName() << FD->getType();
19687 FD->setInvalidDecl();
19688 EnclosingDecl->setInvalidDecl();
19689 continue;
19690 }
19691 // Okay, we have a legal flexible array member at the end of the struct.
19692 Record->setHasFlexibleArrayMember(true);
19693 } else {
19694 // In ObjCContainerDecl ivars with incomplete array type are accepted,
19695 // unless they are followed by another ivar. That check is done
19696 // elsewhere, after synthesized ivars are known.
19697 }
19698 } else if (!FDTy->isDependentType() &&
19699 (LangOpts.HLSL // HLSL allows sizeless builtin types
19701 diag::err_incomplete_type)
19703 FD->getLocation(), FD->getType(),
19704 diag::err_field_incomplete_or_sizeless))) {
19705 // Incomplete type
19706 FD->setInvalidDecl();
19707 EnclosingDecl->setInvalidDecl();
19708 continue;
19709 } else if (const auto *RD = FDTy->getAsRecordDecl()) {
19710 if (Record && RD->hasFlexibleArrayMember()) {
19711 // A type which contains a flexible array member is considered to be a
19712 // flexible array member.
19713 Record->setHasFlexibleArrayMember(true);
19714 if (!Record->isUnion()) {
19715 // If this is a struct/class and this is not the last element, reject
19716 // it. Note that GCC supports variable sized arrays in the middle of
19717 // structures.
19718 if (!IsLastField)
19719 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
19720 << FD->getDeclName() << FD->getType();
19721 else {
19722 // We support flexible arrays at the end of structs in
19723 // other structs as an extension.
19724 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
19725 << FD->getDeclName();
19726 }
19727 }
19728 }
19729 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
19731 diag::err_abstract_type_in_decl,
19733 // Ivars can not have abstract class types
19734 FD->setInvalidDecl();
19735 }
19736 if (Record && RD->hasObjectMember())
19737 Record->setHasObjectMember(true);
19738 if (Record && RD->hasVolatileMember())
19739 Record->setHasVolatileMember(true);
19740 } else if (FDTy->isObjCObjectType()) {
19741 /// A field cannot be an Objective-c object
19742 Diag(FD->getLocation(), diag::err_statically_allocated_object)
19744 QualType T = Context.getObjCObjectPointerType(FD->getType());
19745 FD->setType(T);
19746 } else if (Record && Record->isUnion() &&
19748 getSourceManager().isInSystemHeader(FD->getLocation()) &&
19749 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
19751 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
19752 // For backward compatibility, fields of C unions declared in system
19753 // headers that have non-trivial ObjC ownership qualifications are marked
19754 // as unavailable unless the qualifier is explicit and __strong. This can
19755 // break ABI compatibility between programs compiled with ARC and MRR, but
19756 // is a better option than rejecting programs using those unions under
19757 // ARC.
19758 FD->addAttr(UnavailableAttr::CreateImplicit(
19759 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
19760 FD->getLocation()));
19761 } else if (getLangOpts().ObjC &&
19762 getLangOpts().getGC() != LangOptions::NonGC && Record &&
19763 !Record->hasObjectMember()) {
19764 if (FD->getType()->isObjCObjectPointerType() ||
19765 FD->getType().isObjCGCStrong())
19766 Record->setHasObjectMember(true);
19767 else if (Context.getAsArrayType(FD->getType())) {
19768 QualType BaseType = Context.getBaseElementType(FD->getType());
19769 if (const auto *RD = BaseType->getAsRecordDecl();
19770 RD && RD->hasObjectMember())
19771 Record->setHasObjectMember(true);
19772 else if (BaseType->isObjCObjectPointerType() ||
19773 BaseType.isObjCGCStrong())
19774 Record->setHasObjectMember(true);
19775 }
19776 }
19777
19778 if (Record && !getLangOpts().CPlusPlus &&
19779 !shouldIgnoreForRecordTriviality(FD)) {
19780 QualType FT = FD->getType();
19782 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
19784 Record->isUnion())
19785 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
19786 }
19789 Record->setNonTrivialToPrimitiveCopy(true);
19790 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
19791 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
19792 }
19793 if (FD->hasAttr<ExplicitInitAttr>())
19794 Record->setHasUninitializedExplicitInitFields(true);
19795 if (FT.isDestructedType()) {
19796 Record->setNonTrivialToPrimitiveDestroy(true);
19797 Record->setParamDestroyedInCallee(true);
19798 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
19799 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
19800 }
19801
19802 if (const auto *RD = FT->getAsRecordDecl()) {
19803 if (RD->getArgPassingRestrictions() ==
19805 Record->setArgPassingRestrictions(
19807 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) {
19808 Record->setArgPassingRestrictions(
19810 } else if (PointerAuthQualifier Q = FT.getPointerAuth();
19811 Q && Q.isAddressDiscriminated()) {
19812 Record->setArgPassingRestrictions(
19814 Record->setNonTrivialToPrimitiveCopy(true);
19815 }
19816 }
19817
19818 if (Record && FD->getType().isVolatileQualified())
19819 Record->setHasVolatileMember(true);
19820 bool ReportMSBitfieldStoragePacking =
19821 Record && PreviousField &&
19822 !Diags.isIgnored(diag::warn_ms_bitfield_mismatched_storage_packing,
19823 Record->getLocation());
19824 auto IsNonDependentBitField = [](const FieldDecl *FD) {
19825 return FD->isBitField() && !FD->getType()->isDependentType();
19826 };
19827
19828 if (ReportMSBitfieldStoragePacking && IsNonDependentBitField(FD) &&
19829 IsNonDependentBitField(PreviousField)) {
19830 CharUnits FDStorageSize = Context.getTypeSizeInChars(FD->getType());
19831 CharUnits PreviousFieldStorageSize =
19832 Context.getTypeSizeInChars(PreviousField->getType());
19833 if (FDStorageSize != PreviousFieldStorageSize) {
19834 Diag(FD->getLocation(),
19835 diag::warn_ms_bitfield_mismatched_storage_packing)
19836 << FD << FD->getType() << FDStorageSize.getQuantity()
19837 << PreviousFieldStorageSize.getQuantity();
19838 Diag(PreviousField->getLocation(),
19839 diag::note_ms_bitfield_mismatched_storage_size_previous)
19840 << PreviousField << PreviousField->getType();
19841 }
19842 }
19843 // Keep track of the number of named members.
19844 if (FD->getIdentifier())
19845 ++NumNamedMembers;
19846 }
19847
19848 // Okay, we successfully defined 'Record'.
19849 if (Record) {
19850 bool Completed = false;
19851 if (S) {
19852 Scope *Parent = S->getParent();
19853 if (Parent && Parent->isTypeAliasScope() &&
19854 Parent->isTemplateParamScope())
19855 Record->setInvalidDecl();
19856 }
19857
19858 if (CXXRecord) {
19859 if (!CXXRecord->isInvalidDecl()) {
19860 // Set access bits correctly on the directly-declared conversions.
19862 I = CXXRecord->conversion_begin(),
19863 E = CXXRecord->conversion_end(); I != E; ++I)
19864 I.setAccess((*I)->getAccess());
19865 }
19866
19867 // Add any implicitly-declared members to this class.
19869
19870 if (!CXXRecord->isDependentType()) {
19871 if (!CXXRecord->isInvalidDecl()) {
19872 // If we have virtual base classes, we may end up finding multiple
19873 // final overriders for a given virtual function. Check for this
19874 // problem now.
19875 if (CXXRecord->getNumVBases()) {
19876 CXXFinalOverriderMap FinalOverriders;
19877 CXXRecord->getFinalOverriders(FinalOverriders);
19878
19879 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
19880 MEnd = FinalOverriders.end();
19881 M != MEnd; ++M) {
19882 for (OverridingMethods::iterator SO = M->second.begin(),
19883 SOEnd = M->second.end();
19884 SO != SOEnd; ++SO) {
19885 assert(SO->second.size() > 0 &&
19886 "Virtual function without overriding functions?");
19887 if (SO->second.size() == 1)
19888 continue;
19889
19890 // C++ [class.virtual]p2:
19891 // In a derived class, if a virtual member function of a base
19892 // class subobject has more than one final overrider the
19893 // program is ill-formed.
19894 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
19895 << (const NamedDecl *)M->first << Record;
19896 Diag(M->first->getLocation(),
19897 diag::note_overridden_virtual_function);
19899 OM = SO->second.begin(),
19900 OMEnd = SO->second.end();
19901 OM != OMEnd; ++OM)
19902 Diag(OM->Method->getLocation(), diag::note_final_overrider)
19903 << (const NamedDecl *)M->first << OM->Method->getParent();
19904
19905 Record->setInvalidDecl();
19906 }
19907 }
19908 CXXRecord->completeDefinition(&FinalOverriders);
19909 Completed = true;
19910 }
19911 }
19912 ComputeSelectedDestructor(*this, CXXRecord);
19914 }
19915 }
19916
19917 if (!Completed)
19918 Record->completeDefinition();
19919
19920 // Handle attributes before checking the layout.
19922
19923 // Maybe randomize the record's decls. We automatically randomize a record
19924 // of function pointers, unless it has the "no_randomize_layout" attribute.
19925 if (!getLangOpts().CPlusPlus && !getLangOpts().RandstructSeed.empty() &&
19926 !Record->isRandomized() && !Record->isUnion() &&
19927 (Record->hasAttr<RandomizeLayoutAttr>() ||
19928 (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
19929 EntirelyFunctionPointers(Record)))) {
19930 SmallVector<Decl *, 32> NewDeclOrdering;
19932 NewDeclOrdering))
19933 Record->reorderDecls(NewDeclOrdering);
19934 }
19935
19936 // We may have deferred checking for a deleted destructor. Check now.
19937 if (CXXRecord) {
19938 auto *Dtor = CXXRecord->getDestructor();
19939 if (Dtor && Dtor->isImplicit() &&
19941 CXXRecord->setImplicitDestructorIsDeleted();
19942 SetDeclDeleted(Dtor, CXXRecord->getLocation());
19943 }
19944 }
19945
19946 if (Record->hasAttrs()) {
19948
19949 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
19951 IA->getRange(), IA->getBestCase(),
19952 IA->getInheritanceModel());
19953 }
19954
19955 // Check if the structure/union declaration is a type that can have zero
19956 // size in C. For C this is a language extension, for C++ it may cause
19957 // compatibility problems.
19958 bool CheckForZeroSize;
19959 if (!getLangOpts().CPlusPlus) {
19960 CheckForZeroSize = true;
19961 } else {
19962 // For C++ filter out types that cannot be referenced in C code.
19964 CheckForZeroSize =
19965 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
19966 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
19967 CXXRecord->isCLike();
19968 }
19969 if (CheckForZeroSize) {
19970 bool ZeroSize = true;
19971 bool IsEmpty = true;
19972 unsigned NonBitFields = 0;
19973 for (RecordDecl::field_iterator I = Record->field_begin(),
19974 E = Record->field_end();
19975 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
19976 IsEmpty = false;
19977 if (I->isUnnamedBitField()) {
19978 if (!I->isZeroLengthBitField())
19979 ZeroSize = false;
19980 } else {
19981 ++NonBitFields;
19982 QualType FieldType = I->getType();
19983 if (FieldType->isIncompleteType() ||
19984 !Context.getTypeSizeInChars(FieldType).isZero())
19985 ZeroSize = false;
19986 }
19987 }
19988
19989 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
19990 // allowed in C++, but warn if its declaration is inside
19991 // extern "C" block.
19992 if (ZeroSize) {
19993 Diag(RecLoc, getLangOpts().CPlusPlus ?
19994 diag::warn_zero_size_struct_union_in_extern_c :
19995 diag::warn_zero_size_struct_union_compat)
19996 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
19997 }
19998
19999 // Structs without named members are extension in C (C99 6.7.2.1p7),
20000 // but are accepted by GCC. In C2y, this became implementation-defined
20001 // (C2y 6.7.3.2p10).
20002 if (NonBitFields == 0 && !getLangOpts().CPlusPlus && !getLangOpts().C2y) {
20003 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union
20004 : diag::ext_no_named_members_in_struct_union)
20005 << Record->isUnion();
20006 }
20007 }
20008 } else {
20009 ObjCIvarDecl **ClsFields =
20010 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
20011 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
20012 ID->setEndOfDefinitionLoc(RBrac);
20013 // Add ivar's to class's DeclContext.
20014 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
20015 ClsFields[i]->setLexicalDeclContext(ID);
20016 ID->addDecl(ClsFields[i]);
20017 }
20018 // Must enforce the rule that ivars in the base classes may not be
20019 // duplicates.
20020 if (ID->getSuperClass())
20021 ObjC().DiagnoseDuplicateIvars(ID, ID->getSuperClass());
20022 } else if (ObjCImplementationDecl *IMPDecl =
20023 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
20024 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
20025 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
20026 // Ivar declared in @implementation never belongs to the implementation.
20027 // Only it is in implementation's lexical context.
20028 ClsFields[I]->setLexicalDeclContext(IMPDecl);
20029 ObjC().CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(),
20030 RBrac);
20031 IMPDecl->setIvarLBraceLoc(LBrac);
20032 IMPDecl->setIvarRBraceLoc(RBrac);
20033 } else if (ObjCCategoryDecl *CDecl =
20034 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
20035 // case of ivars in class extension; all other cases have been
20036 // reported as errors elsewhere.
20037 // FIXME. Class extension does not have a LocEnd field.
20038 // CDecl->setLocEnd(RBrac);
20039 // Add ivar's to class extension's DeclContext.
20040 // Diagnose redeclaration of private ivars.
20041 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
20042 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
20043 if (IDecl) {
20044 if (const ObjCIvarDecl *ClsIvar =
20045 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
20046 Diag(ClsFields[i]->getLocation(),
20047 diag::err_duplicate_ivar_declaration);
20048 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
20049 continue;
20050 }
20051 for (const auto *Ext : IDecl->known_extensions()) {
20052 if (const ObjCIvarDecl *ClsExtIvar
20053 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
20054 Diag(ClsFields[i]->getLocation(),
20055 diag::err_duplicate_ivar_declaration);
20056 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
20057 continue;
20058 }
20059 }
20060 }
20061 ClsFields[i]->setLexicalDeclContext(CDecl);
20062 CDecl->addDecl(ClsFields[i]);
20063 }
20064 CDecl->setIvarLBraceLoc(LBrac);
20065 CDecl->setIvarRBraceLoc(RBrac);
20066 }
20067 }
20069}
20070
20071// Given an integral type, return the next larger integral type
20072// (or a NULL type of no such type exists).
20074 // FIXME: Int128/UInt128 support, which also needs to be introduced into
20075 // enum checking below.
20076 assert((T->isIntegralType(Context) ||
20077 T->isEnumeralType()) && "Integral type required!");
20078 const unsigned NumTypes = 4;
20079 QualType SignedIntegralTypes[NumTypes] = {
20080 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
20081 };
20082 QualType UnsignedIntegralTypes[NumTypes] = {
20083 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
20084 Context.UnsignedLongLongTy
20085 };
20086
20087 unsigned BitWidth = Context.getTypeSize(T);
20088 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
20089 : UnsignedIntegralTypes;
20090 for (unsigned I = 0; I != NumTypes; ++I)
20091 if (Context.getTypeSize(Types[I]) > BitWidth)
20092 return Types[I];
20093
20094 return QualType();
20095}
20096
20098 EnumConstantDecl *LastEnumConst,
20099 SourceLocation IdLoc,
20100 IdentifierInfo *Id,
20101 Expr *Val) {
20102 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
20103 llvm::APSInt EnumVal(IntWidth);
20104 QualType EltTy;
20105
20107 Val = nullptr;
20108
20109 if (Val)
20110 Val = DefaultLvalueConversion(Val).get();
20111
20112 if (Val) {
20113 if (Enum->isDependentType() || Val->isTypeDependent() ||
20114 Val->containsErrors())
20115 EltTy = Context.DependentTy;
20116 else {
20117 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
20118 // underlying type, but do allow it in all other contexts.
20119 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
20120 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
20121 // constant-expression in the enumerator-definition shall be a converted
20122 // constant expression of the underlying type.
20123 EltTy = Enum->getIntegerType();
20125 Val, EltTy, EnumVal, CCEKind::Enumerator);
20126 if (Converted.isInvalid())
20127 Val = nullptr;
20128 else
20129 Val = Converted.get();
20130 } else if (!Val->isValueDependent() &&
20131 !(Val = VerifyIntegerConstantExpression(Val, &EnumVal,
20133 .get())) {
20134 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
20135 } else {
20136 if (Enum->isComplete()) {
20137 EltTy = Enum->getIntegerType();
20138
20139 // In Obj-C and Microsoft mode, require the enumeration value to be
20140 // representable in the underlying type of the enumeration. In C++11,
20141 // we perform a non-narrowing conversion as part of converted constant
20142 // expression checking.
20143 if (!Context.isRepresentableIntegerValue(EnumVal, EltTy)) {
20144 if (Context.getTargetInfo()
20145 .getTriple()
20146 .isWindowsMSVCEnvironment()) {
20147 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
20148 } else {
20149 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
20150 }
20151 }
20152
20153 // Cast to the underlying type.
20154 Val = ImpCastExprToType(Val, EltTy,
20155 EltTy->isBooleanType() ? CK_IntegralToBoolean
20156 : CK_IntegralCast)
20157 .get();
20158 } else if (getLangOpts().CPlusPlus) {
20159 // C++11 [dcl.enum]p5:
20160 // If the underlying type is not fixed, the type of each enumerator
20161 // is the type of its initializing value:
20162 // - If an initializer is specified for an enumerator, the
20163 // initializing value has the same type as the expression.
20164 EltTy = Val->getType();
20165 } else {
20166 // C99 6.7.2.2p2:
20167 // The expression that defines the value of an enumeration constant
20168 // shall be an integer constant expression that has a value
20169 // representable as an int.
20170
20171 // Complain if the value is not representable in an int.
20172 if (!Context.isRepresentableIntegerValue(EnumVal, Context.IntTy)) {
20173 Diag(IdLoc, getLangOpts().C23
20174 ? diag::warn_c17_compat_enum_value_not_int
20175 : diag::ext_c23_enum_value_not_int)
20176 << 0 << toString(EnumVal, 10) << Val->getSourceRange()
20177 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
20178 } else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
20179 // Force the type of the expression to 'int'.
20180 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
20181 }
20182 EltTy = Val->getType();
20183 }
20184 }
20185 }
20186 }
20187
20188 if (!Val) {
20189 if (Enum->isDependentType())
20190 EltTy = Context.DependentTy;
20191 else if (!LastEnumConst) {
20192 // C++0x [dcl.enum]p5:
20193 // If the underlying type is not fixed, the type of each enumerator
20194 // is the type of its initializing value:
20195 // - If no initializer is specified for the first enumerator, the
20196 // initializing value has an unspecified integral type.
20197 //
20198 // GCC uses 'int' for its unspecified integral type, as does
20199 // C99 6.7.2.2p3.
20200 if (Enum->isFixed()) {
20201 EltTy = Enum->getIntegerType();
20202 }
20203 else {
20204 EltTy = Context.IntTy;
20205 }
20206 } else {
20207 // Assign the last value + 1.
20208 EnumVal = LastEnumConst->getInitVal();
20209 ++EnumVal;
20210 EltTy = LastEnumConst->getType();
20211
20212 // Check for overflow on increment.
20213 if (EnumVal < LastEnumConst->getInitVal()) {
20214 // C++0x [dcl.enum]p5:
20215 // If the underlying type is not fixed, the type of each enumerator
20216 // is the type of its initializing value:
20217 //
20218 // - Otherwise the type of the initializing value is the same as
20219 // the type of the initializing value of the preceding enumerator
20220 // unless the incremented value is not representable in that type,
20221 // in which case the type is an unspecified integral type
20222 // sufficient to contain the incremented value. If no such type
20223 // exists, the program is ill-formed.
20225 if (T.isNull() || Enum->isFixed()) {
20226 // There is no integral type larger enough to represent this
20227 // value. Complain, then allow the value to wrap around.
20228 EnumVal = LastEnumConst->getInitVal();
20229 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
20230 ++EnumVal;
20231 if (Enum->isFixed())
20232 // When the underlying type is fixed, this is ill-formed.
20233 Diag(IdLoc, diag::err_enumerator_wrapped)
20234 << toString(EnumVal, 10)
20235 << EltTy;
20236 else
20237 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
20238 << toString(EnumVal, 10);
20239 } else {
20240 EltTy = T;
20241 }
20242
20243 // Retrieve the last enumerator's value, extent that type to the
20244 // type that is supposed to be large enough to represent the incremented
20245 // value, then increment.
20246 EnumVal = LastEnumConst->getInitVal();
20247 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20248 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
20249 ++EnumVal;
20250
20251 // If we're not in C++, diagnose the overflow of enumerator values,
20252 // which in C99 means that the enumerator value is not representable in
20253 // an int (C99 6.7.2.2p2). However C23 permits enumerator values that
20254 // are representable in some larger integral type and we allow it in
20255 // older language modes as an extension.
20256 // Exclude fixed enumerators since they are diagnosed with an error for
20257 // this case.
20258 if (!getLangOpts().CPlusPlus && !T.isNull() && !Enum->isFixed())
20259 Diag(IdLoc, getLangOpts().C23
20260 ? diag::warn_c17_compat_enum_value_not_int
20261 : diag::ext_c23_enum_value_not_int)
20262 << 1 << toString(EnumVal, 10) << 1;
20263 } else if (!getLangOpts().CPlusPlus && !EltTy->isDependentType() &&
20264 !Context.isRepresentableIntegerValue(EnumVal, EltTy)) {
20265 // Enforce C99 6.7.2.2p2 even when we compute the next value.
20266 Diag(IdLoc, getLangOpts().C23 ? diag::warn_c17_compat_enum_value_not_int
20267 : diag::ext_c23_enum_value_not_int)
20268 << 1 << toString(EnumVal, 10) << 1;
20269 }
20270 }
20271 }
20272
20273 if (!EltTy->isDependentType()) {
20274 // Make the enumerator value match the signedness and size of the
20275 // enumerator's type.
20276 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
20277 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20278 }
20279
20280 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
20281 Val, EnumVal);
20282}
20283
20285 SourceLocation IILoc) {
20286 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
20288 return SkipBodyInfo();
20289
20290 // We have an anonymous enum definition. Look up the first enumerator to
20291 // determine if we should merge the definition with an existing one and
20292 // skip the body.
20293 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
20295 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
20296 if (!PrevECD)
20297 return SkipBodyInfo();
20298
20299 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
20300 NamedDecl *Hidden;
20301 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
20303 Skip.Previous = Hidden;
20304 return Skip;
20305 }
20306
20307 return SkipBodyInfo();
20308}
20309
20310Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
20311 SourceLocation IdLoc, IdentifierInfo *Id,
20312 const ParsedAttributesView &Attrs,
20313 SourceLocation EqualLoc, Expr *Val,
20314 SkipBodyInfo *SkipBody) {
20315 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
20316 EnumConstantDecl *LastEnumConst =
20317 cast_or_null<EnumConstantDecl>(lastEnumConst);
20318
20319 // The scope passed in may not be a decl scope. Zip up the scope tree until
20320 // we find one that is.
20321 S = getNonFieldDeclScope(S);
20322
20323 // Verify that there isn't already something declared with this name in this
20324 // scope.
20325 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName,
20327 LookupName(R, S);
20328 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
20329
20330 if (PrevDecl && PrevDecl->isTemplateParameter()) {
20331 // Maybe we will complain about the shadowed template parameter.
20332 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
20333 // Just pretend that we didn't see the previous declaration.
20334 PrevDecl = nullptr;
20335 }
20336
20337 // C++ [class.mem]p15:
20338 // If T is the name of a class, then each of the following shall have a name
20339 // different from T:
20340 // - every enumerator of every member of class T that is an unscoped
20341 // enumerated type
20342 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped() &&
20344 DeclarationNameInfo(Id, IdLoc)))
20345 return nullptr;
20346
20348 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
20349 if (!New)
20350 return nullptr;
20351
20352 if (PrevDecl && (!SkipBody || !SkipBody->CheckSameAsPrevious)) {
20353 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
20354 // Check for other kinds of shadowing not already handled.
20355 CheckShadow(New, PrevDecl, R);
20356 }
20357
20358 // When in C++, we may get a TagDecl with the same name; in this case the
20359 // enum constant will 'hide' the tag.
20360 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
20361 "Received TagDecl when not in C++!");
20362 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
20363 if (isa<EnumConstantDecl>(PrevDecl))
20364 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
20365 else
20366 Diag(IdLoc, diag::err_redefinition) << Id;
20367 notePreviousDefinition(PrevDecl, IdLoc);
20368 return nullptr;
20369 }
20370 }
20371
20372 // Process attributes.
20373 ProcessDeclAttributeList(S, New, Attrs);
20376
20377 // Register this decl in the current scope stack.
20378 New->setAccess(TheEnumDecl->getAccess());
20380
20382
20383 return New;
20384}
20385
20386// Returns true when the enum initial expression does not trigger the
20387// duplicate enum warning. A few common cases are exempted as follows:
20388// Element2 = Element1
20389// Element2 = Element1 + 1
20390// Element2 = Element1 - 1
20391// Where Element2 and Element1 are from the same enum.
20393 Expr *InitExpr = ECD->getInitExpr();
20394 if (!InitExpr)
20395 return true;
20396 InitExpr = InitExpr->IgnoreImpCasts();
20397
20398 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
20399 if (!BO->isAdditiveOp())
20400 return true;
20401 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
20402 if (!IL)
20403 return true;
20404 if (IL->getValue() != 1)
20405 return true;
20406
20407 InitExpr = BO->getLHS();
20408 }
20409
20410 // This checks if the elements are from the same enum.
20411 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
20412 if (!DRE)
20413 return true;
20414
20415 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
20416 if (!EnumConstant)
20417 return true;
20418
20420 Enum)
20421 return true;
20422
20423 return false;
20424}
20425
20426// Emits a warning when an element is implicitly set a value that
20427// a previous element has already been set to.
20429 EnumDecl *Enum, QualType EnumType) {
20430 // Avoid anonymous enums
20431 if (!Enum->getIdentifier())
20432 return;
20433
20434 // Only check for small enums.
20435 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
20436 return;
20437
20438 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
20439 return;
20440
20441 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
20442 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
20443
20444 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
20445
20446 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
20447 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
20448
20449 // Use int64_t as a key to avoid needing special handling for map keys.
20450 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
20451 llvm::APSInt Val = D->getInitVal();
20452 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
20453 };
20454
20455 DuplicatesVector DupVector;
20456 ValueToVectorMap EnumMap;
20457
20458 // Populate the EnumMap with all values represented by enum constants without
20459 // an initializer.
20460 for (auto *Element : Elements) {
20461 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
20462
20463 // Null EnumConstantDecl means a previous diagnostic has been emitted for
20464 // this constant. Skip this enum since it may be ill-formed.
20465 if (!ECD) {
20466 return;
20467 }
20468
20469 // Constants with initializers are handled in the next loop.
20470 if (ECD->getInitExpr())
20471 continue;
20472
20473 // Duplicate values are handled in the next loop.
20474 EnumMap.insert({EnumConstantToKey(ECD), ECD});
20475 }
20476
20477 if (EnumMap.size() == 0)
20478 return;
20479
20480 // Create vectors for any values that has duplicates.
20481 for (auto *Element : Elements) {
20482 // The last loop returned if any constant was null.
20484 if (!ValidDuplicateEnum(ECD, Enum))
20485 continue;
20486
20487 auto Iter = EnumMap.find(EnumConstantToKey(ECD));
20488 if (Iter == EnumMap.end())
20489 continue;
20490
20491 DeclOrVector& Entry = Iter->second;
20492 if (EnumConstantDecl *D = dyn_cast<EnumConstantDecl *>(Entry)) {
20493 // Ensure constants are different.
20494 if (D == ECD)
20495 continue;
20496
20497 // Create new vector and push values onto it.
20498 auto Vec = std::make_unique<ECDVector>();
20499 Vec->push_back(D);
20500 Vec->push_back(ECD);
20501
20502 // Update entry to point to the duplicates vector.
20503 Entry = Vec.get();
20504
20505 // Store the vector somewhere we can consult later for quick emission of
20506 // diagnostics.
20507 DupVector.emplace_back(std::move(Vec));
20508 continue;
20509 }
20510
20511 ECDVector *Vec = cast<ECDVector *>(Entry);
20512 // Make sure constants are not added more than once.
20513 if (*Vec->begin() == ECD)
20514 continue;
20515
20516 Vec->push_back(ECD);
20517 }
20518
20519 // Emit diagnostics.
20520 for (const auto &Vec : DupVector) {
20521 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
20522
20523 // Emit warning for one enum constant.
20524 auto *FirstECD = Vec->front();
20525 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
20526 << FirstECD << toString(FirstECD->getInitVal(), 10)
20527 << FirstECD->getSourceRange();
20528
20529 // Emit one note for each of the remaining enum constants with
20530 // the same value.
20531 for (auto *ECD : llvm::drop_begin(*Vec))
20532 S.Diag(ECD->getLocation(), diag::note_duplicate_element)
20533 << ECD << toString(ECD->getInitVal(), 10)
20534 << ECD->getSourceRange();
20535 }
20536}
20537
20538bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
20539 bool AllowMask) const {
20540 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
20541 assert(ED->isCompleteDefinition() && "expected enum definition");
20542
20543 auto R = FlagBitsCache.try_emplace(ED);
20544 llvm::APInt &FlagBits = R.first->second;
20545
20546 if (R.second) {
20547 for (auto *E : ED->enumerators()) {
20548 const auto &EVal = E->getInitVal();
20549 // Only single-bit enumerators introduce new flag values.
20550 if (EVal.isPowerOf2())
20551 FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal;
20552 }
20553 }
20554
20555 // A value is in a flag enum if either its bits are a subset of the enum's
20556 // flag bits (the first condition) or we are allowing masks and the same is
20557 // true of its complement (the second condition). When masks are allowed, we
20558 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
20559 //
20560 // While it's true that any value could be used as a mask, the assumption is
20561 // that a mask will have all of the insignificant bits set. Anything else is
20562 // likely a logic error.
20563 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
20564 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
20565}
20566
20568 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
20569 const ParsedAttributesView &Attrs) {
20570 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
20571 CanQualType EnumType = Context.getCanonicalTagType(Enum);
20572
20573 ProcessDeclAttributeList(S, Enum, Attrs);
20575
20576 if (Enum->isDependentType()) {
20577 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
20578 EnumConstantDecl *ECD =
20579 cast_or_null<EnumConstantDecl>(Elements[i]);
20580 if (!ECD) continue;
20581
20582 ECD->setType(EnumType);
20583 }
20584
20585 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
20586 return;
20587 }
20588
20589 // Verify that all the values are okay, compute the size of the values, and
20590 // reverse the list.
20591 unsigned NumNegativeBits = 0;
20592 unsigned NumPositiveBits = 0;
20593 bool MembersRepresentableByInt =
20594 Context.computeEnumBits(Elements, NumNegativeBits, NumPositiveBits);
20595
20596 // Figure out the type that should be used for this enum.
20597 QualType BestType;
20598 unsigned BestWidth;
20599
20600 // C++0x N3000 [conv.prom]p3:
20601 // An rvalue of an unscoped enumeration type whose underlying
20602 // type is not fixed can be converted to an rvalue of the first
20603 // of the following types that can represent all the values of
20604 // the enumeration: int, unsigned int, long int, unsigned long
20605 // int, long long int, or unsigned long long int.
20606 // C99 6.4.4.3p2:
20607 // An identifier declared as an enumeration constant has type int.
20608 // The C99 rule is modified by C23.
20609 QualType BestPromotionType;
20610
20611 bool Packed = Enum->hasAttr<PackedAttr>();
20612 // -fshort-enums is the equivalent to specifying the packed attribute on all
20613 // enum definitions.
20614 if (LangOpts.ShortEnums)
20615 Packed = true;
20616
20617 // If the enum already has a type because it is fixed or dictated by the
20618 // target, promote that type instead of analyzing the enumerators.
20619 if (Enum->isComplete()) {
20620 BestType = Enum->getIntegerType();
20621 if (Context.isPromotableIntegerType(BestType))
20622 BestPromotionType = Context.getPromotedIntegerType(BestType);
20623 else
20624 BestPromotionType = BestType;
20625
20626 BestWidth = Context.getIntWidth(BestType);
20627 } else {
20628 bool EnumTooLarge = Context.computeBestEnumTypes(
20629 Packed, NumNegativeBits, NumPositiveBits, BestType, BestPromotionType);
20630 BestWidth = Context.getIntWidth(BestType);
20631 if (EnumTooLarge)
20632 Diag(Enum->getLocation(), diag::ext_enum_too_large);
20633 }
20634
20635 // Loop over all of the enumerator constants, changing their types to match
20636 // the type of the enum if needed.
20637 for (auto *D : Elements) {
20638 auto *ECD = cast_or_null<EnumConstantDecl>(D);
20639 if (!ECD) continue; // Already issued a diagnostic.
20640
20641 // C99 says the enumerators have int type, but we allow, as an
20642 // extension, the enumerators to be larger than int size. If each
20643 // enumerator value fits in an int, type it as an int, otherwise type it the
20644 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
20645 // that X has type 'int', not 'unsigned'.
20646
20647 // Determine whether the value fits into an int.
20648 llvm::APSInt InitVal = ECD->getInitVal();
20649
20650 // If it fits into an integer type, force it. Otherwise force it to match
20651 // the enum decl type.
20652 QualType NewTy;
20653 unsigned NewWidth;
20654 bool NewSign;
20655 if (!getLangOpts().CPlusPlus && !Enum->isFixed() &&
20656 MembersRepresentableByInt) {
20657 // C23 6.7.3.3.3p15:
20658 // The enumeration member type for an enumerated type without fixed
20659 // underlying type upon completion is:
20660 // - int if all the values of the enumeration are representable as an
20661 // int; or,
20662 // - the enumerated type
20663 NewTy = Context.IntTy;
20664 NewWidth = Context.getTargetInfo().getIntWidth();
20665 NewSign = true;
20666 } else if (ECD->getType() == BestType) {
20667 // Already the right type!
20668 if (getLangOpts().CPlusPlus)
20669 // C++ [dcl.enum]p4: Following the closing brace of an
20670 // enum-specifier, each enumerator has the type of its
20671 // enumeration.
20672 ECD->setType(EnumType);
20673 continue;
20674 } else {
20675 NewTy = BestType;
20676 NewWidth = BestWidth;
20677 NewSign = BestType->isSignedIntegerOrEnumerationType();
20678 }
20679
20680 // Adjust the APSInt value.
20681 InitVal = InitVal.extOrTrunc(NewWidth);
20682 InitVal.setIsSigned(NewSign);
20683 ECD->setInitVal(Context, InitVal);
20684
20685 // Adjust the Expr initializer and type.
20686 if (ECD->getInitExpr() &&
20687 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
20688 ECD->setInitExpr(ImplicitCastExpr::Create(
20689 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
20690 /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
20691 if (getLangOpts().CPlusPlus)
20692 // C++ [dcl.enum]p4: Following the closing brace of an
20693 // enum-specifier, each enumerator has the type of its
20694 // enumeration.
20695 ECD->setType(EnumType);
20696 else
20697 ECD->setType(NewTy);
20698 }
20699
20700 Enum->completeDefinition(BestType, BestPromotionType,
20701 NumPositiveBits, NumNegativeBits);
20702
20703 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
20704
20705 if (Enum->isClosedFlag()) {
20706 for (Decl *D : Elements) {
20707 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
20708 if (!ECD) continue; // Already issued a diagnostic.
20709
20710 llvm::APSInt InitVal = ECD->getInitVal();
20711 if (InitVal != 0 && !InitVal.isPowerOf2() &&
20712 !IsValueInFlagEnum(Enum, InitVal, true))
20713 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
20714 << ECD << Enum;
20715 }
20716 }
20717
20718 // Now that the enum type is defined, ensure it's not been underaligned.
20719 if (Enum->hasAttrs())
20721}
20722
20724 SourceLocation EndLoc) {
20725
20727 FileScopeAsmDecl::Create(Context, CurContext, expr, StartLoc, EndLoc);
20728 CurContext->addDecl(New);
20729 return New;
20730}
20731
20733 auto *New = TopLevelStmtDecl::Create(Context, /*Statement=*/nullptr);
20734 CurContext->addDecl(New);
20735 PushDeclContext(S, New);
20737 PushCompoundScope(false);
20738 return New;
20739}
20740
20742 if (Statement)
20743 D->setStmt(Statement);
20747}
20748
20750 IdentifierInfo* AliasName,
20751 SourceLocation PragmaLoc,
20752 SourceLocation NameLoc,
20753 SourceLocation AliasNameLoc) {
20754 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
20756 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
20758 AsmLabelAttr *Attr =
20759 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), Info);
20760
20761 // If a declaration that:
20762 // 1) declares a function or a variable
20763 // 2) has external linkage
20764 // already exists, add a label attribute to it.
20765 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
20766 if (isDeclExternC(PrevDecl))
20767 PrevDecl->addAttr(Attr);
20768 else
20769 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
20770 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
20771 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
20772 } else
20773 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
20774}
20775
20777 SourceLocation PragmaLoc,
20778 SourceLocation NameLoc) {
20779 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
20780
20781 if (PrevDecl) {
20782 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
20783 } else {
20784 (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
20785 }
20786}
20787
20789 IdentifierInfo* AliasName,
20790 SourceLocation PragmaLoc,
20791 SourceLocation NameLoc,
20792 SourceLocation AliasNameLoc) {
20793 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
20795 WeakInfo W = WeakInfo(Name, NameLoc);
20796
20797 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
20798 if (!PrevDecl->hasAttr<AliasAttr>())
20799 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
20801 } else {
20802 (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
20803 }
20804}
20805
20807 bool Final) {
20808 assert(FD && "Expected non-null FunctionDecl");
20809
20810 // SYCL functions can be template, so we check if they have appropriate
20811 // attribute prior to checking if it is a template.
20812 if (LangOpts.SYCLIsDevice && FD->hasAttr<DeviceKernelAttr>())
20814
20815 // Templates are emitted when they're instantiated.
20816 if (FD->isDependentContext())
20818
20819 // Check whether this function is an externally visible definition.
20820 auto IsEmittedForExternalSymbol = [this, FD]() {
20821 // We have to check the GVA linkage of the function's *definition* -- if we
20822 // only have a declaration, we don't know whether or not the function will
20823 // be emitted, because (say) the definition could include "inline".
20824 const FunctionDecl *Def = FD->getDefinition();
20825
20826 // We can't compute linkage when we skip function bodies.
20827 return Def && !Def->hasSkippedBody() &&
20829 getASTContext().GetGVALinkageForFunction(Def));
20830 };
20831
20832 if (LangOpts.OpenMPIsTargetDevice) {
20833 // In OpenMP device mode we will not emit host only functions, or functions
20834 // we don't need due to their linkage.
20835 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20836 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20837 // DevTy may be changed later by
20838 // #pragma omp declare target to(*) device_type(*).
20839 // Therefore DevTy having no value does not imply host. The emission status
20840 // will be checked again at the end of compilation unit with Final = true.
20841 if (DevTy)
20842 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
20844 // If we have an explicit value for the device type, or we are in a target
20845 // declare context, we need to emit all extern and used symbols.
20846 if (OpenMP().isInOpenMPDeclareTargetContext() || DevTy)
20847 if (IsEmittedForExternalSymbol())
20849 // Device mode only emits what it must, if it wasn't tagged yet and needed,
20850 // we'll omit it.
20851 if (Final)
20853 } else if (LangOpts.OpenMP > 45) {
20854 // In OpenMP host compilation prior to 5.0 everything was an emitted host
20855 // function. In 5.0, no_host was introduced which might cause a function to
20856 // be omitted.
20857 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20858 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20859 if (DevTy)
20860 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
20862 }
20863
20864 if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
20866
20867 if (LangOpts.CUDA) {
20868 // When compiling for device, host functions are never emitted. Similarly,
20869 // when compiling for host, device and global functions are never emitted.
20870 // (Technically, we do emit a host-side stub for global functions, but this
20871 // doesn't count for our purposes here.)
20873 if (LangOpts.CUDAIsDevice && T == CUDAFunctionTarget::Host)
20875 if (!LangOpts.CUDAIsDevice &&
20878
20879 if (IsEmittedForExternalSymbol())
20881
20882 // If FD is a virtual destructor of an explicit instantiation
20883 // of a template class, return Emitted.
20884 if (auto *Destructor = dyn_cast<CXXDestructorDecl>(FD)) {
20885 if (Destructor->isVirtual()) {
20886 if (auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(
20887 Destructor->getParent())) {
20889 Spec->getTemplateSpecializationKind();
20893 }
20894 }
20895 }
20896 }
20897
20898 // Otherwise, the function is known-emitted if it's in our set of
20899 // known-emitted functions.
20901}
20902
20904 // Host-side references to a __global__ function refer to the stub, so the
20905 // function itself is never emitted and therefore should not be marked.
20906 // If we have host fn calls kernel fn calls host+device, the HD function
20907 // does not get instantiated on the host. We model this by omitting at the
20908 // call to the kernel from the callgraph. This ensures that, when compiling
20909 // for host, only HD functions actually called from the host get marked as
20910 // known-emitted.
20911 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
20913}
20914
20916 bool &Visible) {
20917 Visible = hasVisibleDefinition(D, Suggested);
20918 // The redefinition of D in the **current** TU is allowed if D is invisible or
20919 // D is defined in the global module of other module units. We didn't check if
20920 // it is in global module as, we'll check the redefinition in named module
20921 // later with better diagnostic message.
20922 return D->isInAnotherModuleUnit() || !Visible;
20923}
Defines the clang::ASTContext interface.
This file provides some common utility functions for processing Lambda related AST Constructs.
Defines enum values for all the target-independent builtin functions.
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
This file defines the classes used to store parsed information about declaration-specifiers and decla...
Defines the C++ template declaration subclasses.
static bool isDeclExternC(const T &D)
Definition Decl.cpp:2229
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
static bool hasDefinition(const ObjCObjectPointerType *ObjPtr)
Defines the clang::Expr interface and subclasses for C++ expressions.
TokenType getType() const
Returns the token's type, e.g.
FormatToken * Previous
The previous token in the unwrapped line.
FormatToken * Next
The next token in the unwrapped line.
static const Decl * getCanonicalDecl(const Decl *D)
static const GlobalDecl isTemplate(GlobalDecl GD, const TemplateArgumentList *&TemplateArgs)
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Architecture Architecture
Definition MachO.h:27
llvm::MachO::Record Record
Definition MachO.h:31
static bool isExternC(const NamedDecl *ND)
Definition Mangle.cpp:74
#define SM(sm)
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
Defines the clang::Preprocessor interface.
RedeclarationKind
Specifies whether (or how) name lookup is being performed for a redeclaration (vs.
@ NotForRedeclaration
The lookup is a reference to this name that is not for the purpose of redeclaring the name.
@ ForExternalRedeclaration
The lookup results will be used for redeclaration of a name with external linkage; non-visible lookup...
@ ForVisibleRedeclaration
The lookup results will be used for redeclaration of a name, if an entity by that name already exists...
llvm::SmallVector< std::pair< const MemRegion *, SVal >, 4 > Bindings
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis functions specific to ARM.
static bool hasAttr(const Decl *D, bool IgnoreImplicitAttr)
Definition SemaCUDA.cpp:109
This file declares semantic analysis for CUDA constructs.
static void diagnoseImplicitlyRetainedSelf(Sema &S)
static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D)
static UnqualifiedTypeNameLookupResult lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, SourceLocation NameLoc, const CXXRecordDecl *RD)
Tries to perform unqualified lookup of the type decls in bases for dependent class.
Definition SemaDecl.cpp:175
static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, const FunctionDecl *&PossiblePrototype)
static bool isMainVar(DeclarationName Name, VarDecl *VD)
static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD)
static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, const IdentifierInfo &II, SourceLocation NameLoc)
Definition SemaDecl.cpp:230
static void mergeParamDeclTypes(ParmVarDecl *NewParam, const ParmVarDecl *OldParam, Sema &S)
static void checkHybridPatchableAttr(Sema &S, NamedDecl &ND)
static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, DeclaratorDecl *OldD)
If necessary, adjust the semantic declaration context for a qualified declaration to name the correct...
static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken)
Determine whether the given result set contains either a type name or.
Definition SemaDecl.cpp:830
static void FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL)
static bool AllowOverloadingOfFunction(const LookupResult &Previous, ASTContext &Context, const FunctionDecl *New)
Determine whether overloading is allowed for a new function declaration considering prior declaration...
static TypeSourceInfo * TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, ASTContext &Context, bool &SizeIsNegative, llvm::APSInt &Oversized)
Helper method to turn variable array types into constant array types in certain situations which woul...
static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, ASTContext::GetBuiltinTypeError Error)
static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D)
static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, ExpectedDecl *New)
Check whether a redeclaration of an entity introduced by a using-declaration is valid,...
static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, const DeclContext *OldDC)
Determine what kind of declaration we're shadowing.
static void checkIsValidOpenCLKernelParameter(Sema &S, Declarator &D, ParmVarDecl *Param, llvm::SmallPtrSetImpl< const Type * > &ValidTypes)
static void mergeParamDeclAttributes(ParmVarDecl *newDecl, const ParmVarDecl *oldDecl, Sema &S)
mergeParamDeclAttributes - Copy attributes from the old parameter to the new one.
static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc, QualType T)
static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
Check the validity of a mulitversion function declaration.
static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old)
Merge alignment attributes from Old to New, taking into account the special semantics of C11's _Align...
static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, LookupResult &Previous)
static void CheckConstPureAttributesUsage(Sema &S, FunctionDecl *NewFD)
static bool FindPossiblePrototype(const FunctionDecl *FD, const FunctionDecl *&PossiblePrototype)
static bool MultiVersionTypesCompatible(FunctionDecl *Old, FunctionDecl *New)
static NestedNameSpecifier synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC)
Definition SemaDecl.cpp:594
static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, FixItHint &Hint)
static void CheckExplicitObjectParameter(Sema &S, ParmVarDecl *P, SourceLocation ExplicitThisLoc)
static void checkLifetimeBoundAttr(Sema &S, NamedDecl &ND)
static void patchDefaultTargetVersion(FunctionDecl *From, FunctionDecl *To)
static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD)
Given that we are within the definition of the given function, will that definition behave like C99's...
static void CheckForDuplicateEnumValues(Sema &S, ArrayRef< Decl * > Elements, EnumDecl *Enum, QualType EnumType)
static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS)
static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old)
checkNewAttributesAfterDef - If we already have a definition, check that there are no new attributes ...
static bool isClassCompatTagKind(TagTypeKind Tag)
Determine if tag kind is a class-key compatible with class for redeclaration (class,...
static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, const FunctionDecl *B)
static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND)
static bool hasSimilarParameters(ASTContext &Context, FunctionDecl *Declaration, FunctionDecl *Definition, SmallVectorImpl< unsigned > &Params)
hasSimilarParameters - Determine whether the C++ functions Declaration and Definition have "nearly" m...
static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD)
Determine whether a class is C-like, according to the rules of C++ [dcl.typedef] for anonymous classe...
static unsigned propagateAttribute(ParmVarDecl *To, const ParmVarDecl *From, Sema &S)
static FunctionDecl * CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, DeclContext *DC, QualType &R, TypeSourceInfo *TInfo, StorageClass SC, bool &IsVirtualOkay)
static Scope * getTagInjectionScope(Scope *S, const LangOptions &LangOpts)
Find the Scope in which a tag is implicitly declared if we see an elaborated type specifier in the sp...
static bool methodHasName(const FunctionDecl *FD, StringRef Name)
static std::pair< diag::kind, SourceLocation > getNoteDiagForInvalidRedeclaration(const T *Old, const T *New)
static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, LookupResult &Previous)
Apply special rules for handling extern "C" declarations.
static bool DeclHasAttr(const Decl *D, const Attr *A)
DeclhasAttr - returns true if decl Declaration already has the target attribute.
static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty)
static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, const ConstInitAttr *CIAttr, bool AttrBeforeInit)
static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, const LookupResult &R)
static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, SourceLocation NameLoc)
Add a minimal nested name specifier fixit hint to allow lookup of a tag name from an outer enclosing ...
static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S, DeclContext *Owner, DeclarationName Name, SourceLocation NameLoc, bool IsUnion, StorageClass SC)
We are trying to inject an anonymous member into the given scope; check if there's an existing declar...
static bool checkGlobalOrExternCConflict(Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous)
Check for conflict between this global or extern "C" declaration and previous global or extern "C" de...
static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts, const NamedDecl *D)
static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD, unsigned BuiltinID)
Determine whether a declaration matches a known function in namespace std.
static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, RecordDecl *AnonRecord, AccessSpecifier AS, StorageClass SC, SmallVectorImpl< NamedDecl * > &Chaining)
InjectAnonymousStructOrUnionMembers - Inject the members of the anonymous struct or union AnonRecord ...
OpenCLParamType
@ InvalidAddrSpacePtrKernelParam
@ ValidKernelParam
@ InvalidKernelParam
@ RecordKernelParam
@ PtrKernelParam
@ PtrPtrKernelParam
static bool isFromSystemHeader(SourceManager &SM, const Decl *D)
Returns true if the declaration is declared in a system header or from a system macro.
static 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:613
static void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record)
[class.dtor]p4: At the end of the definition of a class, overload resolution is performed among the p...
static bool shouldConsiderLinkage(const VarDecl *VD)
static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record)
static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, const FunctionDecl *NewFD, bool CausesMV, MultiVersionKind MVKind)
static DeclContext * getTagInjectionContext(DeclContext *DC)
Find the DeclContext in which a tag is implicitly declared if we see an elaborated type specifier in ...
static bool EquivalentArrayTypes(QualType Old, QualType New, const ASTContext &Ctx)
static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New)
static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag)
Get diagnostic select index for tag kind for redeclaration diagnostic message.
static void checkInheritableAttr(Sema &S, NamedDecl &ND)
static void CheckPoppedLabel(LabelDecl *L, Sema &S, Sema::DiagReceiverTy DiagReceiver)
static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl *Old)
static NamedDecl * DiagnoseInvalidRedeclaration(Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S)
Generate diagnostics for an invalid function redeclaration.
static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, DeclarationName Name)
RebuildDeclaratorInCurrentInstantiation - Checks whether the given declarator needs to be rebuilt in ...
static void SetEligibleMethods(Sema &S, CXXRecordDecl *Record, ArrayRef< CXXMethodDecl * > Methods, CXXSpecialMemberKind CSM)
[class.mem.special]p6: An eligible special member function is a special member function for which:
static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc)
Definition SemaDecl.cpp:845
static bool hasParsedAttr(Scope *S, const Declarator &PD, ParsedAttr::Kind Kind)
ShadowedDeclKind
Enum describing the select options in diag::warn_decl_shadow.
@ SDK_StructuredBinding
@ SDK_Field
@ SDK_Global
@ SDK_Local
@ SDK_Typedef
@ SDK_StaticMember
@ SDK_Using
static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S)
static void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD)
static bool canRedefineFunction(const FunctionDecl *FD, const LangOptions &LangOpts)
canRedefineFunction - checks if a function can be redefined.
static void checkWeakAttr(Sema &S, NamedDecl &ND)
static void checkSelectAnyAttr(Sema &S, NamedDecl &ND)
static bool isImplicitInstantiation(NamedDecl *D)
static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT)
static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, SourceLocation DefaultInitLoc)
static bool isDefaultStdCall(FunctionDecl *FD, Sema &S)
static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD)
Returns true if there hasn't been any invalid type diagnosed.
static void RemoveUsingDecls(LookupResult &R)
Removes using shadow declarations not at class scope from the lookup results.
static void ComputeSpecialMemberFunctionsEligiblity(Sema &S, CXXRecordDecl *Record)
static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, MultiVersionKind MVKind)
static bool looksMutable(QualType T, const ASTContext &Ctx)
static bool isUsingDeclNotAtClassScope(NamedDecl *D)
static void propagateAttributes(ParmVarDecl *To, const ParmVarDecl *From, F &&propagator)
static const NamedDecl * getDefinition(const Decl *D)
static QualType TryToFixInvalidVariablyModifiedType(QualType T, ASTContext &Context, bool &SizeIsNegative, llvm::APSInt &Oversized)
Helper method to turn variable array types into constant array types in certain situations which woul...
static bool hasDeducedAuto(DeclaratorDecl *DD)
static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT)
static QualType getCoreType(QualType Ty)
static bool isMainFileLoc(const Sema &S, SourceLocation Loc)
static bool mergeDeclAttribute(Sema &S, NamedDecl *D, const InheritableAttr *Attr, AvailabilityMergeKind AMK)
static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD)
Check the target or target_version attribute of the function for MultiVersion validity.
static bool isOutOfScopePreviousDeclaration(NamedDecl *, DeclContext *, ASTContext &)
Determines whether the given declaration is an out-of-scope previous declaration.
static StorageClass StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS)
StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to a VarDecl::StorageClass.
static bool CheckMultiVersionAdditionalDecl(Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
Check the validity of a new function declaration being added to an existing multiversioned declaratio...
static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD)
Check the validity of a multiversion function declaration that is the first of its kind.
static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, NamedDecl *NewDecl, bool IsSpecialization, bool IsDefinition)
static bool checkNonMultiVersionCompatAttributes(Sema &S, const FunctionDecl *FD, const FunctionDecl *CausedFD, MultiVersionKind MVKind)
static void checkAliasAttr(Sema &S, NamedDecl &ND)
static void filterNonConflictingPreviousTypedefDecls(Sema &S, const TypedefNameDecl *Decl, LookupResult &Previous)
Typedef declarations don't have linkage, but they still denote the same entity if their types are the...
static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum)
static QualType getNextLargerIntegralType(ASTContext &Context, QualType T)
static void checkWeakRefAttr(Sema &S, NamedDecl &ND)
static bool isIncompleteDeclExternC(Sema &S, const T *D)
Determine whether a variable is extern "C" prior to attaching an initializer.
static bool isAttributeTargetADefinition(Decl *D)
static Attr * getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD)
Return a CodeSegAttr from a containing class.
static bool CheckDeclarationCausesMultiVersioning(Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D)
Check for this common pattern:
static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, DeclContext *NewDC)
Determine whether a tag originally declared in context OldDC can be redeclared with an unqualified na...
static bool isRecordType(QualType T)
This file declares semantic analysis for HLSL constructs.
This file declares semantic analysis for Objective-C.
This file declares semantic analysis for OpenACC constructs and clauses.
This file declares semantic analysis for OpenMP constructs and clauses.
This file declares semantic analysis functions specific to PowerPC.
This file declares semantic analysis functions specific to RISC-V.
This file declares semantic analysis for SYCL constructs.
This file declares semantic analysis functions specific to Swift.
This file declares semantic analysis functions specific to Wasm.
static CharSourceRange getRange(const CharSourceRange &EditRange, const SourceManager &SM, const LangOptions &LangOpts, bool IncludeMacroExpansion)
Defines the SourceManager interface.
static QualType getPointeeType(const MemRegion *R)
C Language Family Type Representation.
@ GE_None
No error.
@ GE_Missing_stdio
Missing a type from <stdio.h>
@ GE_Missing_type
Missing a type.
@ GE_Missing_ucontext
Missing a type from <ucontext.h>
@ GE_Missing_setjmp
Missing a type from <setjmp.h>
RAII object that pops an ExpressionEvaluationContext when exiting a function body.
ExitFunctionBodyRAII(Sema &S, bool IsLambda)
llvm::APInt getValue() const
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
virtual void AssignInheritanceModel(CXXRecordDecl *RD)
Callback invoked when an MSInheritanceAttr has been attached to a CXXRecordDecl.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:188
SourceManager & getSourceManager()
Definition ASTContext.h:798
TranslationUnitDecl * getTranslationUnitDecl() const
const ConstantArrayType * getAsConstantArrayType(QualType T) const
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType, const Attr *attr=nullptr) const
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
IdentifierTable & Idents
Definition ASTContext.h:737
const LangOptions & getLangOpts() const
Definition ASTContext.h:891
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
const VariableArrayType * getAsVariableArrayType(QualType T) const
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:856
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
CanQualType getCanonicalTagType(const TagDecl *TD) const
@ GE_Missing_type
Missing a type.
@ GE_Missing_setjmp
Missing a type from <setjmp.h>
unsigned getTypeAlign(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in bits.
bool isUnset() const
Definition Ownership.h:168
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
Represents a type which was implicitly adjusted by the semantic engine for arbitrary reasons.
Definition TypeBase.h:3489
Wrapper for source info for arrays.
Definition TypeLoc.h:1757
SourceLocation getLBracketLoc() const
Definition TypeLoc.h:1759
Expr * getSizeExpr() const
Definition TypeLoc.h:1779
TypeLoc getElementLoc() const
Definition TypeLoc.h:1787
SourceLocation getRBracketLoc() const
Definition TypeLoc.h:1767
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3720
QualType getElementType() const
Definition TypeBase.h:3732
Attr - This represents one attribute.
Definition Attr.h:44
attr::Kind getKind() const
Definition Attr.h:90
bool isInherited() const
Definition Attr.h:99
Attr * clone(ASTContext &C) const
void setImplicit(bool I)
Definition Attr.h:104
SourceLocation getLocation() const
Definition Attr.h:97
bool isStandardAttributeSyntax() const
The attribute is spelled [[]] in either C or C++ mode, including standard attributes spelled with a k...
A factory, from which one makes pools, from which one creates individual attributes which are dealloc...
Definition ParsedAttr.h:622
AttributeFactory & getFactory() const
Definition ParsedAttr.h:718
Type source information for an attributed type.
Definition TypeLoc.h:1017
TypeLoc getModifiedLoc() const
The modified type, which is generally canonically different from the attribute type.
Definition TypeLoc.h:1031
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression which will be evaluated if the condition evaluates to false; ...
Definition Expr.h:4441
Expr * getCond() const
getCond - Return the condition expression; this is defined in terms of the opaque value.
Definition Expr.h:4429
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:3972
Expr * getLHS() const
Definition Expr.h:4022
Expr * getRHS() const
Definition Expr.h:4024
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4113
A binding in a decomposition declaration.
Definition DeclCXX.h:4185
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4651
bool doesNotEscape() const
Definition Decl.h:4802
This class is used for builtin types like 'int'.
Definition TypeBase.h:3164
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
Definition Builtins.h:228
const char * getHeaderName(unsigned ID) const
If this is a library function that comes from a specific header, retrieve that header name.
Definition Builtins.h:375
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
Represents a base class of a C++ class.
Definition DeclCXX.h:146
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclCXX.h:194
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclCXX.h:195
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1692
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1612
Represents a C++ constructor within a class.
Definition DeclCXX.h:2604
bool isCopyConstructor(unsigned &TypeQuals) const
Whether this constructor is a copy constructor (C++ [class.copy]p2, which can be used to copy the cla...
Definition DeclCXX.cpp:3008
static CXXConstructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, ExplicitSpecifier ES, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, InheritedConstructor Inherited=InheritedConstructor(), const AssociatedConstraint &TrailingRequiresClause={})
Definition DeclCXX.cpp:2968
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2943
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:3170
static CXXDeductionGuideDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, ExplicitSpecifier ES, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, SourceLocation EndLocation, CXXConstructorDecl *Ctor=nullptr, DeductionCandidate Kind=DeductionCandidate::Normal, const AssociatedConstraint &TrailingRequiresClause={}, const CXXDeductionGuideDecl *SourceDG=nullptr, SourceDeductionGuideKind SK=SourceDeductionGuideKind::None)
Definition DeclCXX.cpp:2367
Represents a C++ destructor within a class.
Definition DeclCXX.h:2869
static CXXDestructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, const AssociatedConstraint &TrailingRequiresClause={})
Definition DeclCXX.cpp:3098
A mapping from each virtual member function to its set of final overriders.
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2129
bool isExplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An explicit object member function is a non-static member function with an explic...
Definition DeclCXX.cpp:2703
void addOverriddenMethod(const CXXMethodDecl *MD)
Definition DeclCXX.cpp:2755
bool isVirtual() const
Definition DeclCXX.h:2184
static CXXMethodDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin, bool isInline, ConstexprSpecKind ConstexprKind, SourceLocation EndLocation, const AssociatedConstraint &TrailingRequiresClause={})
Definition DeclCXX.cpp:2488
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition DeclCXX.cpp:2820
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2255
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition DeclCXX.cpp:2735
Qualifiers getMethodQualifiers() const
Definition DeclCXX.h:2290
bool isConst() const
Definition DeclCXX.h:2181
bool isStatic() const
Definition DeclCXX.cpp:2401
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition DeclCXX.cpp:2714
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2225
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr)
Definition DeclCXX.cpp:132
base_class_iterator bases_end()
Definition DeclCXX.h:617
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition DeclCXX.h:1366
const FunctionDecl * isLocalClass() const
If the class is a local class [class.local], returns the enclosing function declaration.
Definition DeclCXX.h:1554
base_class_range bases()
Definition DeclCXX.h:608
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition DeclCXX.h:602
bool lookupInBases(BaseMatchesCallback BaseMatches, CXXBasePaths &Paths, bool LookupInDependent=false) const
Look for entities within the base classes of this C++ class, transitively searching all base class su...
base_class_iterator bases_begin()
Definition DeclCXX.h:615
capture_const_range captures() const
Definition DeclCXX.h:1097
bool hasInClassInitializer() const
Whether this class has any in-class initializers for non-static data members (including those in anon...
Definition DeclCXX.h:1148
bool hasDefinition() const
Definition DeclCXX.h:561
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition DeclCXX.cpp:2042
bool isInjectedClassName() const
Determines whether this declaration represents the injected class name.
Definition DeclCXX.cpp:2146
LambdaCaptureDefault getLambdaCaptureDefault() const
Definition DeclCXX.h:1059
UnresolvedSetIterator conversion_iterator
Definition DeclCXX.h:1119
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition DeclCXX.cpp:2046
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:522
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:73
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition DeclSpec.h:180
char * location_data() const
Retrieve the data associated with the source-location information.
Definition DeclSpec.h:206
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:185
void MakeTrivial(ASTContext &Context, NestedNameSpecifier Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition DeclSpec.cpp:97
SourceRange getRange() const
Definition DeclSpec.h:79
SourceLocation getBeginLoc() const
Definition DeclSpec.h:83
bool isSet() const
Deprecated.
Definition DeclSpec.h:198
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition DeclSpec.h:94
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition DeclSpec.cpp:123
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition DeclSpec.h:183
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:178
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition DeclSpec.cpp:103
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3081
bool isCallToStdMove() const
Definition Expr.cpp:3619
Expr * getCallee()
Definition Expr.h:3024
arg_range arguments()
Definition Expr.h:3129
CastKind getCastKind() const
Definition Expr.h:3654
Expr * getSubExpr()
Definition Expr.h:3660
static CharSourceRange getCharRange(SourceRange R)
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
Declaration of a class template.
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3758
static unsigned getNumAddressingBits(const ASTContext &Context, QualType ElementType, const llvm::APInt &NumElements)
Determine the number of bits required to address a member of.
Definition Type.cpp:214
static unsigned getMaxSizeBits(const ASTContext &Context)
Determine the maximum number of active bits that an array's size can require, which limits the maximu...
Definition Type.cpp:254
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3814
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:346
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:37
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
DeclListNode::iterator iterator
Definition DeclBase.h:1392
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2238
bool isFileContext() const
Definition DeclBase.h:2180
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
DeclContextLookupResult lookup_result
Definition DeclBase.h:2577
bool isTransparentContext() const
isTransparentContext - Determines whether this context is a "transparent" context,...
Decl * getNonClosureAncestor()
Find the nearest non-closure ancestor of this context, i.e.
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
bool isClosure() const
Definition DeclBase.h:2142
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition DeclBase.h:2125
bool isNamespace() const
Definition DeclBase.h:2198
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
const BlockDecl * getInnermostBlockDecl() const
Return this DeclContext if it is a BlockDecl.
bool isTranslationUnit() const
Definition DeclBase.h:2185
bool isRecord() const
Definition DeclBase.h:2189
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
void removeDecl(Decl *D)
Removes a declaration from this context.
void addDecl(Decl *D)
Add the declaration D into this context.
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2373
bool isFunctionOrMethod() const
Definition DeclBase.h:2161
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
bool isExternCContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context semantically encloses the declaration context DC.
Decl::Kind getDeclKind() const
Definition DeclBase.h:2102
DeclContext * getNonTransparentContext()
Simple template class for restricting typo correction candidates to ones having a single Decl* of the...
static DeclGroupRef Create(ASTContext &C, Decl **Decls, unsigned NumDecls)
Definition DeclGroup.h:64
A reference to a declared variable, function, enum, etc.
Definition Expr.h: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:319
bool isInStdNamespace() const
Definition DeclBase.cpp:427
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclBase.h:435
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition DeclBase.h:1226
bool isFromGlobalModule() const
Whether this declaration comes from global module.
T * getAttr() const
Definition DeclBase.h:573
bool hasAttrs() const
Definition DeclBase.h:518
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:524
void addAttr(Attr *A)
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:593
void setAttrs(const AttrVec &Attrs)
Definition DeclBase.h:520
bool isUnavailable(std::string *Message=nullptr) const
Determine whether this declaration is marked 'unavailable'.
Definition DeclBase.h:771
bool isInNamedModule() const
Whether this declaration comes from a named module.
void setLocalExternDecl()
Changes the namespace of this declaration to reflect that it's a function-local extern declaration.
Definition DeclBase.h:1151
virtual bool isOutOfLine() const
Determine whether this declaration is declared out of line (outside its semantic context).
Definition Decl.cpp:99
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition DeclBase.cpp:156
void setTopLevelDeclInObjCContainer(bool V=true)
Definition DeclBase.h:638
bool isInIdentifierNamespace(unsigned NS) const
Definition DeclBase.h:893
@ FOK_Undeclared
A friend of a previously-undeclared entity.
Definition DeclBase.h:1219
@ FOK_None
Not a friend object.
Definition DeclBase.h:1217
@ FOK_Declared
A friend of a previously-declared entity.
Definition DeclBase.h:1218
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition DeclBase.cpp:286
bool isInExportDeclContext() const
Whether this declaration was exported in a lexical context.
bool isReferenced() const
Whether any declaration of this entity was referenced.
Definition DeclBase.cpp:578
bool isInAnotherModuleUnit() const
Whether this declaration comes from another module unit.
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:842
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:251
void dropAttrs()
@ OBJC_TQ_CSNullability
The nullability qualifier is set when the nullability of the result or parameter was expressed via a ...
Definition DeclBase.h:210
void setObjectOfFriendDecl(bool PerformFriendInjection=false)
Changes the namespace of this declaration to reflect that it's the object of a friend declaration.
Definition DeclBase.h:1180
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition DeclBase.h:2793
bool isInvalidDecl() const
Definition DeclBase.h:588
bool isLocalExternDecl() const
Determine whether this is a block-scope declaration with linkage.
Definition DeclBase.h:1169
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:559
void setAccess(AccessSpecifier AS)
Definition DeclBase.h:502
SourceLocation getLocation() const
Definition DeclBase.h:439
@ IDNS_Ordinary
Ordinary names.
Definition DeclBase.h:144
void setImplicit(bool I=true)
Definition DeclBase.h:594
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition DeclBase.cpp:553
DeclContext * getDeclContext()
Definition DeclBase.h:448
attr_range attrs() const
Definition DeclBase.h:535
AccessSpecifier getAccess() const
Definition DeclBase.h:507
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:431
void dropAttr()
Definition DeclBase.h:556
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition DeclBase.cpp:360
Module * getOwningModuleForLinkage() const
Get the module that owns this declaration for linkage purposes.
Definition Decl.cpp:1636
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:918
bool hasAttr() const
Definition DeclBase.h:577
void setNonMemberOperator()
Specifies that this declaration is a C++ overloaded non-member.
Definition DeclBase.h:1235
void setLexicalDeclContext(DeclContext *DC)
Definition DeclBase.cpp:364
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:978
Kind getKind() const
Definition DeclBase.h:442
The name of a declaration.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
bool isAnyOperatorNewOrDelete() const
bool isAnyOperatorDelete() const
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
QualType getCXXNameType() const
If this name is one of the C++ names (of a constructor, destructor, or conversion function),...
NameKind getNameKind() const
Determine what kind of name this is.
bool isEmpty() const
Evaluates true when this declaration name is empty.
bool isIdentifier() const
Predicate functions for querying what type of name this is.
Represents a ValueDecl that came out of a declarator.
Definition Decl.h:779
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition Decl.h:821
SourceLocation getOuterLocStart() const
Return start of source range taking into account any outer template declarations.
Definition Decl.cpp:2050
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2090
SourceLocation getTypeSpecStartLoc() const
Definition Decl.cpp:1988
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:830
const AssociatedConstraint & getTrailingRequiresClause() const
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition Decl.h:854
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition Decl.h:813
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition Decl.cpp:2000
NestedNameSpecifier getQualifier() const
Retrieve the nested-name-specifier that qualifies the name of this declaration, if it was present in ...
Definition Decl.h:836
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:808
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition Decl.cpp:2034
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1874
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition DeclSpec.h:2430
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition DeclSpec.h:2372
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2021
Expr * getAsmLabel() const
Definition DeclSpec.h:2676
FunctionDefinitionKind getFunctionDefinitionKind() const
Definition DeclSpec.h:2715
const ParsedAttributes & getAttributes() const
Definition DeclSpec.h:2657
void setRedeclaration(bool Val)
Definition DeclSpec.h:2738
SourceLocation getIdentifierLoc() const
Definition DeclSpec.h:2310
void SetIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Set the name of this declarator to be the given identifier.
Definition DeclSpec.h:2313
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclSpec.h:2058
Expr * getTrailingRequiresClause()
Sets a trailing requires clause for this declarator.
Definition DeclSpec.h:2607
void setInvalidType(bool Val=true)
Definition DeclSpec.h:2687
TemplateParameterList * getInventedTemplateParameterList() const
The template parameter list generated from the explicit template parameters along with any invented t...
Definition DeclSpec.h:2637
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition DeclSpec.h:2368
bool isRedeclaration() const
Definition DeclSpec.h:2739
const ParsedAttributesView & getDeclarationAttributes() const
Definition DeclSpec.h:2660
const DecompositionDeclarator & getDecompositionDeclarator() const
Definition DeclSpec.h:2042
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2057
bool isCtorOrDtor()
Returns true if this declares a constructor or a destructor.
Definition DeclSpec.cpp:410
bool isFunctionDefinition() const
Definition DeclSpec.h:2711
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition DeclSpec.h:2040
bool hasInitializer() const
Definition DeclSpec.h:2720
void setFunctionDefinitionKind(FunctionDefinitionKind Val)
Definition DeclSpec.h:2707
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition DeclSpec.h:2036
void takeAttributes(ParsedAttributes &attrs)
takeAttributes - Takes attributes from the given parsed-attributes set and add them to this declarato...
Definition DeclSpec.h:2650
void AddTypeInfo(const DeclaratorChunk &TI, ParsedAttributes &&attrs, SourceLocation EndLoc)
AddTypeInfo - Add a chunk to this declarator.
Definition DeclSpec.h:2327
bool isInvalidType() const
Definition DeclSpec.h:2688
bool isExplicitObjectMemberFunction()
Definition DeclSpec.cpp:398
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition DeclSpec.h:2056
bool isDecompositionDeclarator() const
Return whether this declarator is a decomposition declarator.
Definition DeclSpec.h:2300
bool isFirstDeclarationOfMember()
Returns true if this declares a real member and not a friend.
Definition DeclSpec.h:2723
bool isStaticMember()
Returns true if this declares a static member.
Definition DeclSpec.cpp:389
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition DeclSpec.h:2028
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition DeclSpec.h:2461
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2304
A decomposition declaration.
Definition DeclCXX.h:4249
static DecompositionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation LSquareLoc, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< BindingDecl * > Bindings)
Definition DeclCXX.cpp:3629
A parsed C++17 decomposition declarator of the form '[' identifier-list ']'.
Definition DeclSpec.h:1762
SourceRange getSourceRange() const
Definition DeclSpec.h:1810
SourceLocation getLSquareLoc() const
Definition DeclSpec.h:1808
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2493
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2581
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2561
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:2570
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:231
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:950
An instance of this object exists for each enum constant that is defined.
Definition Decl.h:3420
llvm::APSInt getInitVal() const
Definition Decl.h:3440
static EnumConstantDecl * Create(ASTContext &C, EnumDecl *DC, SourceLocation L, IdentifierInfo *Id, QualType T, Expr *E, const llvm::APSInt &V)
Definition Decl.cpp:5583
const Expr * getInitExpr() const
Definition Decl.h:3438
Represents an enum.
Definition Decl.h:4004
enumerator_range enumerators() const
Definition Decl.h:4141
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition Decl.h:4213
void setIntegerType(QualType T)
Set the underlying integer type.
Definition Decl.h:4177
void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo)
Set the underlying integer type source info.
Definition Decl.h:4180
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4227
static EnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, bool IsScoped, bool IsScopedUsingClassTag, bool IsFixed)
Definition Decl.cpp:4953
bool isClosedFlag() const
Returns true if this enum is annotated with flag_enum and isn't annotated with enum_extensibility(ope...
Definition Decl.cpp:4992
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition Decl.h:4222
SourceRange getIntegerTypeRange() const LLVM_READONLY
Retrieve the source range that covers the underlying type if specified.
Definition Decl.cpp:4967
void setPromotionType(QualType T)
Set the promotion type.
Definition Decl.h:4163
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4168
EvaluatedExprVisitor - This class visits 'Expr *'s.
Store information needed for an explicit specifier.
Definition DeclCXX.h:1924
This represents one expression.
Definition Expr.h:112
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3085
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:3081
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:3065
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:273
QualType getType() const
Definition Expr.h:144
Represents difference between two FPOptions values.
bool isFPConstrained() const
Represents a member of a struct/union/class.
Definition Decl.h:3157
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3260
bool isAnonymousStructOrUnion() const
Determines whether this field is a representative for an anonymous struct or union.
Definition Decl.cpp:4656
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3393
static FieldDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
Definition Decl.cpp:4641
bool isZeroLengthBitField() const
Is this a zero-length bit-field?
Definition Decl.cpp:4702
static FileScopeAsmDecl * Create(ASTContext &C, DeclContext *DC, Expr *Str, SourceLocation AsmLoc, SourceLocation RParenLoc)
Definition Decl.cpp:5716
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:78
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:139
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:128
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:102
Represents a function declaration or definition.
Definition Decl.h:1999
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2686
static FunctionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation NLoc, DeclarationName N, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin=false, bool isInlineSpecified=false, bool hasWrittenPrototype=true, ConstexprSpecKind ConstexprKind=ConstexprSpecKind::Unspecified, const AssociatedConstraint &TrailingRequiresClause={})
Definition Decl.h:2188
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2794
ConstexprSpecKind getConstexprKind() const
Definition Decl.h:2475
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4146
void setPreviousDeclaration(FunctionDecl *PrevDecl)
Definition Decl.cpp:3674
void setDescribedFunctionTemplate(FunctionTemplateDecl *Template)
Definition Decl.cpp:4139
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4134
void setIsPureVirtual(bool P=true)
Definition Decl.cpp:3290
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition Decl.h:2313
void setFriendConstraintRefersToEnclosingTemplate(bool V=true)
Definition Decl.h:2698
void setHasSkippedBody(bool Skipped=true)
Definition Decl.h:2677
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition Decl.cpp:3965
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3703
param_iterator param_end()
Definition Decl.h:2784
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:2918
void setIsMultiVersion(bool V=true)
Sets the multiversion state for this declaration and all of its redeclarations.
Definition Decl.h:2692
QualType getReturnType() const
Definition Decl.h:2842
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2771
bool isCPUSpecificMultiVersion() const
True if this function is a multiversioned processor specific function as a part of the cpu_specific/c...
Definition Decl.cpp:3647
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted.
Definition Decl.h:2388
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2376
LanguageLinkage getLanguageLinkage() const
Compute the language linkage.
Definition Decl.cpp:3555
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4254
bool hasWrittenPrototype() const
Whether this function has a written prototype.
Definition Decl.h:2447
void setWillHaveBody(bool V=true)
Definition Decl.h:2683
bool isReplaceableGlobalAllocationFunction(UnsignedOrNone *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions: void *operato...
Definition Decl.h:2593
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition Decl.h:2442
FunctionTemplateSpecializationInfo * getTemplateSpecializationInfo() const
If this function is actually a function template specialization, retrieve information about this func...
Definition Decl.cpp:4264
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3688
param_iterator param_begin()
Definition Decl.h:2783
const ParmVarDecl * getNonObjectParameter(unsigned I) const
Definition Decl.h:2820
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3125
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition Decl.h:2325
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2539
FunctionEffectsRef getFunctionEffects() const
Definition Decl.h:3131
bool isMSVCRTEntryPoint() const
Determines whether this function is a MSVCRT user defined entry point.
Definition Decl.cpp:3363
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition Decl.cpp:4198
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:2885
bool isStatic() const
Definition Decl.h:2926
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a member function.
Definition Decl.cpp:4467
void setTrivial(bool IT)
Definition Decl.h:2377
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4085
bool isFirstDecl() const
True if this is the first declaration in its redeclaration chain.
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2469
bool isDeletedAsWritten() const
Definition Decl.h:2543
redecl_iterator redecls_end() const
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition Decl.h:2352
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition Decl.cpp:3559
bool isLateTemplateParsed() const
Whether this templated function will be late parsed.
Definition Decl.h:2356
FunctionDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
bool hasImplicitReturnZero() const
Whether falling off this function implicitly returns null/zero.
Definition Decl.h:2427
void setVirtualAsWritten(bool V)
State that this function is marked as virtual explicitly.
Definition Decl.h:2348
bool hasSkippedBody() const
True if the function was a definition but its body was skipped.
Definition Decl.h:2676
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition Decl.h:2281
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition Decl.cpp:3356
void setImplicitlyInline(bool I=true)
Flag that this function is implicitly inline.
Definition Decl.h:2913
bool param_empty() const
Definition Decl.h:2782
bool isThisDeclarationInstantiatedFromAFriendDefinition() const
Determine whether this specific declaration of the function is a friend declaration that was instanti...
Definition Decl.cpp:3215
void setRangeEnd(SourceLocation E)
Definition Decl.h:2217
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
Definition Decl.cpp:3643
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2384
void setIneligibleOrNotSelected(bool II)
Definition Decl.h:2420
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:4490
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition Decl.h:2930
const IdentifierInfo * getLiteralIdentifier() const
getLiteralIdentifier - The literal suffix identifier this function represents, if any.
Definition Decl.cpp:4079
void setConstexprKind(ConstexprSpecKind CSK)
Definition Decl.h:2472
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4358
void setDefaulted(bool D=true)
Definition Decl.h:2385
bool isConsteval() const
Definition Decl.h:2481
QualType getDeclaredReturnType() const
Get the declared return type, which may differ from the actual return type if the return type is dedu...
Definition Decl.h:2859
void setBody(Stmt *B)
Definition Decl.cpp:3283
bool isGlobal() const
Determines whether this is a global function.
Definition Decl.cpp:3573
void setDeletedAsWritten(bool D=true, StringLiteral *Message=nullptr)
Definition Decl.cpp:3161
bool hasInheritedPrototype() const
Whether this function inherited its prototype from a previous declaration.
Definition Decl.h:2458
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4106
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3767
DeclarationNameInfo getNameInfo() const
Definition Decl.h:2210
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3191
void setHasImplicitReturnZero(bool IRZ)
State that falling off this function implicitly returns null/zero.
Definition Decl.h:2434
bool isDefined(const FunctionDecl *&Definition, bool CheckForPendingFriendDefinition=false) const
Returns true if the function has a definition that does not need to be instantiated.
Definition Decl.cpp:3238
FunctionDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
bool isInlineSpecified() const
Determine whether the "inline" keyword was specified for this function.
Definition Decl.h:2896
MultiVersionKind getMultiVersionKind() const
Gets the kind of multiversioning attribute this declaration has.
Definition Decl.cpp:3629
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition Decl.h:2682
A mutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5200
SmallVector< Conflict > Conflicts
Definition TypeBase.h:5232
static FunctionEffectSet getUnion(FunctionEffectsRef LHS, FunctionEffectsRef RHS, Conflicts &Errs)
Definition Type.cpp:5679
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5064
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5264
unsigned getNumParams() const
Definition TypeBase.h:5542
QualType getParamType(unsigned i) const
Definition TypeBase.h:5544
unsigned getAArch64SMEAttributes() const
Return a bitmask describing the SME attributes on the function type, see AArch64SMETypeAttributes for...
Definition TypeBase.h:5761
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition TypeBase.h:5577
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5668
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5553
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5549
Declaration of a template function.
FunctionTemplateDecl * getInstantiatedFromMemberTemplate() const
static FunctionTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a function template node.
void mergePrevDecl(FunctionTemplateDecl *Prev)
Merge Prev with our RedeclarableTemplateDecl::Common.
bool isExplicitInstantiationOrSpecialization() const
True if this declaration is an explicit specialization, explicit instantiation declaration,...
Wrapper for source info for functions.
Definition TypeLoc.h:1624
A class which abstracts out some details necessary for making a call.
Definition TypeBase.h:4571
ExtInfo withCallingConv(CallingConv cc) const
Definition TypeBase.h:4683
CallingConv getCC() const
Definition TypeBase.h:4630
ExtInfo withProducesResult(bool producesResult) const
Definition TypeBase.h:4649
unsigned getRegParm() const
Definition TypeBase.h:4623
bool getNoCallerSavedRegs() const
Definition TypeBase.h:4619
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4642
ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const
Definition TypeBase.h:4663
ExtInfo withRegParm(unsigned RegParm) const
Definition TypeBase.h:4677
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4460
ExtInfo getExtInfo() const
Definition TypeBase.h:4816
static StringRef getNameForCallConv(CallingConv CC)
Definition Type.cpp:3578
unsigned getRegParmType() const
Definition TypeBase.h:4803
CallingConv getCallConv() const
Definition TypeBase.h:4815
QualType getReturnType() const
Definition TypeBase.h:4800
bool getCmseNSCallAttr() const
Definition TypeBase.h:4814
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
bool isEditorPlaceholder() const
Return true if this identifier is an editor placeholder.
StringRef getName() const
Return the actual identifier string.
iterator - Iterate over the decls of a specified declaration name.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2068
Represents a C array with an unspecified size.
Definition TypeBase.h:3907
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3464
static IndirectFieldDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, const IdentifierInfo *Id, QualType T, MutableArrayRef< NamedDecl * > CH)
Definition Decl.cpp:5610
void setInherited(bool I)
Definition Attr.h:156
Description of a constructor that was inherited from a base class.
Definition DeclCXX.h:2575
child_range children()
Definition Expr.h:5432
Describes the kind of initialization being performed, along with location information for tokens rela...
static InitializationKind CreateDefault(SourceLocation InitLoc)
Create a default initialization.
static InitializationKind CreateForInit(SourceLocation Loc, bool DirectInit, Expr *Init)
Create an initialization from an initializer (which, for direct initialization from a parenthesized l...
step_iterator step_begin() const
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence.
@ SK_ParenthesizedListInit
Initialize an aggreagate with parenthesized list of values.
Describes an entity that is being initialized.
static InitializedEntity InitializeVariable(VarDecl *Var)
Create the initialization entity for a variable.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition Expr.cpp:971
Represents the declaration of a label.
Definition Decl.h:523
bool isResolvedMSAsmLabel() const
Definition Decl.h:558
LabelStmt * getStmt() const
Definition Decl.h:547
bool isMSAsmLabel() const
Definition Decl.h:557
llvm::iterator_range< capture_init_iterator > capture_inits()
Retrieve the initialization expressions for this lambda's captures.
Definition ExprCXX.h:2085
@ FPE_Ignore
Assume that floating-point exceptions are masked.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const
FPExceptionModeKind getDefaultExceptionMode() const
bool requiresStrictPrototypes() const
Returns true if functions without prototypes or functions with an identifier list (aka K&R C function...
std::string getOpenCLVersionString() const
Return the OpenCL C or C++ for OpenCL language name and version as a string.
bool IsHeaderFile
Indicates whether the front-end is explicitly told that the input is a header file (i....
unsigned getOpenCLCompatibleVersion() const
Return the OpenCL version that kernel language is compatible with.
static SourceLocation findLocationAfterToken(SourceLocation loc, tok::TokenKind TKind, const SourceManager &SM, const LangOptions &LangOpts, bool SkipTrailingWhitespaceAndNewLine)
Checks that the given token is the first token that occurs after the given location (this excludes co...
Definition Lexer.cpp:1377
Visibility getVisibility() const
Definition Visibility.h:89
Linkage getLinkage() const
Definition Visibility.h:88
Represents a linkage specification.
Definition DeclCXX.h:3015
static LinkageSpecDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExternLoc, SourceLocation LangLoc, LinkageSpecLanguageIDs Lang, bool HasBraces)
Definition DeclCXX.cpp:3200
A class for iterating through a result set and possibly filtering out results.
Definition Lookup.h:677
void erase()
Erase the last element returned from this iterator.
Definition Lookup.h:723
Represents the results of name lookup.
Definition Lookup.h:147
DeclClass * getAsSingle() const
Definition Lookup.h:558
bool empty() const
Return true if no decls were found.
Definition Lookup.h:362
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition Lookup.h:666
Filter makeFilter()
Create a filter for this result set.
Definition Lookup.h:751
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition Lookup.h:569
bool isAmbiguous() const
Definition Lookup.h:324
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition Lookup.h:331
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition Lookup.h:275
Sema & getSema() const
Get the Sema object that this lookup result is searching with.
Definition Lookup.h:672
UnresolvedSetImpl::iterator iterator
Definition Lookup.h:154
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition Lookup.h:576
LookupResultKind getResultKind() const
Definition Lookup.h:344
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition Lookup.h:636
DeclarationName getLookupName() const
Gets the name to look up.
Definition Lookup.h:265
iterator end() const
Definition Lookup.h:359
iterator begin() const
Definition Lookup.h:358
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition Lookup.h:255
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
virtual unsigned getManglingNumber(const CXXMethodDecl *CallOperator)=0
Retrieve the mangling number of a new lambda expression with the given call operator within this cont...
virtual unsigned getStaticLocalNumber(const VarDecl *VD)=0
Static locals are numbered by source order.
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3381
Expr * getBase() const
Definition Expr.h:3375
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3651
Describes a module or submodule.
Definition Module.h:144
SourceLocation DefinitionLoc
The location of the module definition.
Definition Module.h:150
Module * Parent
The parent of this module.
Definition Module.h:193
bool isPrivateModule() const
Definition Module.h:249
bool isHeaderLikeModule() const
Is this module have similar semantics as headers.
Definition Module.h:648
bool isModuleImplementation() const
Is this a module implementation.
Definition Module.h:664
bool isModulePartition() const
Is this a module partition.
Definition Module.h:653
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition Module.cpp:239
bool isNamedModule() const
Does this Module is a named module of a standard named module?
Definition Module.h:224
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
Definition Module.h:722
@ ClassId_NSObject
Definition NSAPI.h:30
This represents a decl that may have a name.
Definition Decl.h:273
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:486
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:294
bool isLinkageValid() const
True if the computed linkage is valid.
Definition Decl.cpp:1085
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:300
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition Decl.cpp:1095
Visibility getVisibility() const
Determines the visibility of this entity.
Definition Decl.h:443
bool hasLinkageBeenComputed() const
True if something has required us to compute the linkage of this declaration.
Definition Decl.h:478
bool hasExternalFormalLinkage() const
True if this decl has external linkage.
Definition Decl.h:428
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:339
bool declarationReplaces(const NamedDecl *OldD, bool IsKnownNewer=true) const
Determine whether this declaration, if known to be well-formed within its context,...
Definition Decl.cpp:1858
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1206
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition DeclBase.h:706
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition Decl.cpp:1930
bool isExternallyVisible() const
Definition Decl.h:432
ReservedIdentifierStatus isReserved(const LangOptions &LangOpts) const
Determine if the declaration obeys the reserved identifier rules of the given language.
Definition Decl.cpp:1132
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition Decl.h:396
Represent a C++ namespace.
Definition Decl.h:591
bool isAnonymousNamespace() const
Returns true if this is an anonymous namespace declaration.
Definition Decl.h:642
Class that aids in the construction of nested-name-specifiers along with source-location information ...
void MakeTrivial(ASTContext &Context, NestedNameSpecifier Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
A C++ nested-name-specifier augmented with source location information.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
static constexpr NestedNameSpecifier getGlobal()
bool containsErrors() const
Whether this nested name specifier contains an error.
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
@ MicrosoftSuper
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
ObjCCategoryDecl - Represents a category declaration.
Definition DeclObjC.h:2329
ObjCCompatibleAliasDecl - Represents alias of a class.
Definition DeclObjC.h:2775
ObjCContainerDecl - Represents a container for method declarations.
Definition DeclObjC.h:948
ObjCIvarDecl * getIvarDecl(IdentifierInfo *Id) const
getIvarDecl - This method looks up an ivar in this ContextDecl.
Definition DeclObjC.cpp:78
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition DeclObjC.h:2597
Represents an ObjC class declaration.
Definition DeclObjC.h:1154
known_extensions_range known_extensions() const
Definition DeclObjC.h:1762
Wrapper for source info for ObjC interfaces.
Definition TypeLoc.h:1283
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:1293
ObjCIvarDecl - Represents an ObjC instance variable.
Definition DeclObjC.h:1952
static ObjCIvarDecl * Create(ASTContext &C, ObjCContainerDecl *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, AccessControl ac, Expr *BW=nullptr, bool synthesized=false)
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
param_const_iterator param_end() const
Definition DeclObjC.h:358
param_const_iterator param_begin() const
Definition DeclObjC.h:354
const ParmVarDecl *const * param_const_iterator
Definition DeclObjC.h:349
bool isOptional() const
Definition DeclObjC.h:505
ParmVarDecl *const * param_iterator
Definition DeclObjC.h:350
ProtocolLAngleLoc, ProtocolRAngleLoc, and the source locations for protocol qualifiers are stored aft...
Definition TypeLoc.h:904
PtrTy get() const
Definition Ownership.h:81
static OpaquePtr make(DeclGroupRef P)
Definition Ownership.h:61
bool isAvailableOption(llvm::StringRef Ext, const LangOptions &LO) const
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1153
@ CSK_Normal
Normal lookup.
Definition Overload.h:1157
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1369
void NoteCandidates(PartialDiagnosticAt PA, Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, StringRef Opc="", SourceLocation Loc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
When overload resolution fails, prints diagnostic messages containing the candidates in the candidate...
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
MapType::iterator iterator
SmallVectorImpl< UniqueVirtualMethod >::iterator overriding_iterator
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:290
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1395
TypeLoc getInnerLoc() const
Definition TypeLoc.h:1408
void setLParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1391
Sugar for parentheses used when specifying types.
Definition TypeBase.h:3302
Represents a parameter to a function.
Definition Decl.h:1789
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition Decl.h:1849
ObjCDeclQualifier getObjCDeclQualifier() const
Definition Decl.h:1853
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition Decl.h:1822
void setExplicitObjectParameterLoc(SourceLocation Loc)
Definition Decl.h:1881
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition Decl.cpp:2946
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2969
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
static const ParsedAttributesView & none()
Definition ParsedAttr.h:817
bool hasAttribute(ParsedAttr::Kind K) const
Definition ParsedAttr.h:897
ParsedAttributes - A collection of parsed attributes.
Definition ParsedAttr.h:937
AttributePool & getPool() const
Definition ParsedAttr.h:944
PipeType - OpenCL20.
Definition TypeBase.h:8103
Pointer-authentication qualifiers.
Definition TypeBase.h:152
bool isAddressDiscriminated() const
Definition TypeBase.h:265
TypeLoc getPointeeLoc() const
Definition TypeLoc.h:1474
Wrapper for source info for pointers.
Definition TypeLoc.h:1493
void setStarLoc(SourceLocation Loc)
Definition TypeLoc.h:1499
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3328
QualType getPointeeType() const
Definition TypeBase.h:3338
StringRef getLastMacroWithSpelling(SourceLocation Loc, ArrayRef< TokenValue > Tokens) const
Return the name of the macro defined before Loc that has spelling Tokens.
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8369
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition TypeBase.h:8363
bool hasNonTrivialToPrimitiveCopyCUnion() const
Check if this is or contains a C union that is non-trivial to copy, which is a union that has a membe...
Definition Type.h:87
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:1453
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition Type.cpp:2921
const IdentifierInfo * getBaseTypeIdentifier() const
Retrieves a pointer to the name of the base type.
Definition Type.cpp:109
QualType withoutLocalFastQualifiers() const
Definition TypeBase.h:1214
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition TypeBase.h:1296
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const
Check if this is a non-trivial type that would cause a C struct transitively containing this type to ...
Definition Type.cpp:2970
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8285
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8411
bool hasNonTrivialToPrimitiveDestructCUnion() const
Check if this is or contains a C union that is non-trivial to destruct, which is a union that has a m...
Definition Type.h:81
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8325
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1438
QualType getCanonicalType() const
Definition TypeBase.h:8337
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8379
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:8358
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1670
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1545
bool isCanonical() const
Definition TypeBase.h:8342
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:75
A qualifier set is used to build a set of qualifiers.
Definition TypeBase.h:8225
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8232
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition Type.cpp:4666
The collection of all-type qualifiers we support.
Definition TypeBase.h:331
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:361
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:354
@ OCL_None
There is no lifetime qualification on this type.
Definition TypeBase.h:350
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:364
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition TypeBase.h:367
bool hasConst() const
Definition TypeBase.h:457
bool hasVolatile() const
Definition TypeBase.h:467
ObjCLifetime getObjCLifetime() const
Definition TypeBase.h:545
bool empty() const
Definition TypeBase.h:647
Represents a struct/union/class.
Definition Decl.h:4309
field_range fields() const
Definition Decl.h:4512
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition Decl.cpp:5111
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4509
field_iterator field_begin() const
Definition Decl.cpp:5154
Frontend produces RecoveryExprs on semantic errors that prevent creating other well-formed expression...
Definition Expr.h:7377
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:5309
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3571
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition Stmt.h:3160
void setNRVOCandidate(const VarDecl *Var)
Set the variable that might be used for the named return value optimization.
Definition Stmt.h:3203
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
void setEntity(DeclContext *E)
Definition Scope.h:409
bool isClassScope() const
isClassScope - Return true if this scope is a class/struct/union scope.
Definition Scope.h:428
unsigned getDepth() const
Returns the depth of this scope. The translation-unit has scope depth 0.
Definition Scope.h:339
unsigned getNextFunctionPrototypeIndex()
Return the number of parameters declared in this function prototype, increasing it by one for the nex...
Definition Scope.h:349
const Scope * getFnParent() const
getFnParent - Return the closest scope that is a function body.
Definition Scope.h:291
void AddDecl(Decl *D)
Definition Scope.h:362
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition Scope.h:271
bool isTypeAliasScope() const
Determine whether this scope is a type alias scope.
Definition Scope.h:628
bool isDeclScope(const Decl *D) const
isDeclScope - Return true if this is the scope that the specified decl is declared in.
Definition Scope.h:398
void RemoveDecl(Decl *D)
Definition Scope.h:370
void setLookupEntity(DeclContext *E)
Definition Scope.h:414
unsigned getMSLastManglingNumber() const
Definition Scope.h:386
DeclContext * getEntity() const
Get the entity corresponding to this scope.
Definition Scope.h:401
unsigned getMSCurManglingNumber() const
Definition Scope.h:392
bool decl_empty() const
Definition Scope.h:360
bool isTemplateParamScope() const
isTemplateParamScope - Return true if this scope is a C++ template parameter scope.
Definition Scope.h:481
unsigned getFunctionPrototypeDepth() const
Returns the number of function prototype scopes in this scope chain.
Definition Scope.h:343
Scope * getDeclParent()
Definition Scope.h:335
bool isCompoundStmtScope() const
Determine whether this scope is a compound statement scope.
Definition Scope.h:619
decl_range decls() const
Definition Scope.h:356
bool containedInPrototypeScope() const
containedInPrototypeScope - Return true if this or a parent scope is a FunctionPrototypeScope.
Definition Scope.cpp:106
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition Scope.h:287
bool isFunctionPrototypeScope() const
isFunctionPrototypeScope - Return true if this scope is a function prototype scope.
Definition Scope.h:487
bool hasUnrecoverableErrorOccurred() const
Determine whether any unrecoverable errors have occurred within this scope.
Definition Scope.h:420
void applyNRVO()
Definition Scope.cpp:166
Scope * getTemplateParamParent()
Definition Scope.h:332
@ TemplateParamScope
This is a scope that corresponds to the template parameters of a C++ template.
Definition Scope.h:81
@ DeclScope
This is a scope that can contain a declaration.
Definition Scope.h:63
void CheckSMEFunctionDefAttributes(const FunctionDecl *FD)
Definition SemaARM.cpp:1403
SemaDiagnosticBuilder DiagCompat(SourceLocation Loc, unsigned CompatDiagId, bool DeferHint=false)
Emit a compatibility diagnostic.
Definition SemaBase.cpp:91
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition SemaBase.cpp:61
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
void checkAllowedInitializer(VarDecl *VD)
Definition SemaCUDA.cpp:672
std::string getConfigureFuncName() const
Returns the name of the launch configuration function.
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition SemaCUDA.cpp:134
void maybeAddHostDeviceAttrs(FunctionDecl *FD, const LookupResult &Previous)
May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD, depending on FD and the current co...
Definition SemaCUDA.cpp:760
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:825
void CheckEntryPoint(FunctionDecl *FD)
Definition SemaHLSL.cpp:792
HLSLVkConstantIdAttr * mergeVkConstantIdAttr(Decl *D, const AttributeCommonInfo &AL, int Id)
Definition SemaHLSL.cpp:655
HLSLNumThreadsAttr * mergeNumThreadsAttr(Decl *D, const AttributeCommonInfo &AL, int X, int Y, int Z)
Definition SemaHLSL.cpp:621
void deduceAddressSpace(VarDecl *Decl)
void ActOnTopLevelFunction(FunctionDecl *FD)
Definition SemaHLSL.cpp:724
HLSLShaderAttr * mergeShaderAttr(Decl *D, const AttributeCommonInfo &AL, llvm::Triple::EnvironmentType ShaderType)
Definition SemaHLSL.cpp:691
HLSLWaveSizeAttr * mergeWaveSizeAttr(Decl *D, const AttributeCommonInfo &AL, int Min, int Max, int Preferred, int SpelledArgsCount)
Definition SemaHLSL.cpp:635
void ActOnVariableDeclarator(VarDecl *VD)
void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID)
DiagnoseDuplicateIvars - Check for duplicate ivars in the entire class at the start of @implementatio...
void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, const ObjCMethodDecl *Overridden)
Check whether the given new method is a valid override of the given overridden method,...
DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, IdentifierInfo *II)
The parser has read a name in, and Sema has detected that we're currently inside an ObjC method.
void checkRetainCycles(ObjCMessageExpr *msg)
checkRetainCycles - Check whether an Objective-C message send might create an obvious retain cycle.
ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV)
void AddCFAuditedAttribute(Decl *D)
AddCFAuditedAttribute - Check whether we're currently within '#pragma clang arc_cf_code_audited' and,...
void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, ObjCIvarDecl **Fields, unsigned nIvars, SourceLocation Loc)
CheckImplementationIvars - This routine checks if the instance variables listed in the implelementati...
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition SemaObjC.h:591
void ActOnVariableDeclarator(VarDecl *VD)
Function called when a variable declarator is created, which lets us implement the 'routine' 'functio...
OpenACCRoutineDeclAttr * mergeRoutineDeclAttr(const OpenACCRoutineDeclAttr &Old)
void ActOnFunctionDeclarator(FunctionDecl *FD)
Called when a function decl is created, which lets us implement the 'routine' 'doesn't match next thi...
void ActOnVariableInit(VarDecl *VD, QualType InitType)
Called when a variable is initialized, so we can implement the 'routine 'doesn't match the next thing...
void ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D)
Act on D, a function definition inside of an omp [begin/end] assumes.
void ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Decl *D, SmallVectorImpl< FunctionDecl * > &Bases)
Register D as specialization of all base functions in Bases in the current omp begin/end declare vari...
void ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists, SmallVectorImpl< FunctionDecl * > &Bases)
The declarator D defines a function in the scope S which is nested in an omp begin/end declare varian...
void ActOnOpenMPDeclareTargetInitializer(Decl *D)
Adds OMPDeclareTargetDeclAttr to referenced variables in declare target directive.
void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, SourceLocation IdLoc=SourceLocation())
Check declaration inside target region.
void checkRVVTypeSupport(QualType Ty, SourceLocation Loc, Decl *D, const llvm::StringMap< bool > &FeatureMap)
void CheckSYCLExternalFunctionDecl(FunctionDecl *FD)
Definition SemaSYCL.cpp:253
StmtResult BuildSYCLKernelCallStmt(FunctionDecl *FD, CompoundStmt *Body)
Definition SemaSYCL.cpp:437
void CheckSYCLEntryPointFunctionDecl(FunctionDecl *FD)
Definition SemaSYCL.cpp:270
SwiftNameAttr * mergeNameAttr(Decl *D, const SwiftNameAttr &SNA, StringRef Name)
Definition SemaSwift.cpp:26
WebAssemblyImportNameAttr * mergeImportNameAttr(Decl *D, const WebAssemblyImportNameAttr &AL)
Definition SemaWasm.cpp:334
WebAssemblyImportModuleAttr * mergeImportModuleAttr(Decl *D, const WebAssemblyImportModuleAttr &AL)
Definition SemaWasm.cpp:313
bool IsAlignAttr() const
Definition Sema.h:1890
Mode getAlignMode() const
Definition Sema.h:1892
A RAII object to temporarily push a declaration context.
Definition Sema.h:3475
A class which encapsulates the logic for delaying diagnostics during parsing and other processing.
Definition Sema.h:1358
bool shouldDelayDiagnostics()
Determines whether diagnostics should be delayed.
Definition Sema.h:1370
void add(const sema::DelayedDiagnostic &diag)
Adds a delayed diagnostic.
static NameClassification DependentNonType()
Definition Sema.h:3689
static NameClassification VarTemplate(TemplateName Name)
Definition Sema.h:3699
static NameClassification Unknown()
Definition Sema.h:3669
static NameClassification OverloadSet(ExprResult E)
Definition Sema.h:3673
static NameClassification UndeclaredTemplate(TemplateName Name)
Definition Sema.h:3717
static NameClassification FunctionTemplate(TemplateName Name)
Definition Sema.h:3705
static NameClassification NonType(NamedDecl *D)
Definition Sema.h:3679
static NameClassification Concept(TemplateName Name)
Definition Sema.h:3711
static NameClassification UndeclaredNonType()
Definition Sema.h:3685
static NameClassification TypeTemplate(TemplateName Name)
Definition Sema.h:3693
static NameClassification Error()
Definition Sema.h:3665
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12366
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12399
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:853
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:3567
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D)
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:12943
sema::CapturingScopeInfo * getEnclosingLambdaOrBlock() const
Get the innermost lambda or block enclosing the current location, if any.
Definition Sema.cpp:2539
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1119
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:8196
CXXSpecialMemberKind getSpecialMember(const CXXMethodDecl *MD)
Definition Sema.h:6271
LookupNameKind
Describes the kind of name lookup to perform.
Definition Sema.h:9286
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9290
@ LookupNestedNameSpecifierName
Look up of a name that precedes the '::' scope resolution operator in C++.
Definition Sema.h:9309
@ LookupLocalFriendName
Look up a friend of a local class.
Definition Sema.h:9325
@ LookupRedeclarationWithLinkage
Look up an ordinary name that is going to be redeclared as a name with linkage.
Definition Sema.h:9322
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9298
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition Sema.h:9293
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:1504
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:1240
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:4728
llvm::SmallSetVector< const TypedefNameDecl *, 4 > UnusedLocalTypedefNameCandidates
Set containing all typedefs that are likely unused.
Definition Sema.h:3549
PragmaClangSection PragmaClangRodataSection
Definition Sema.h:1816
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:6463
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:1444
TemplateDecl * AdjustDeclIfTemplate(Decl *&Decl)
AdjustDeclIfTemplate - If the given decl happens to be a template, reset the parameter D to reference...
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC)
Require that the context specified by SS be complete.
bool TemplateParameterListsAreEqual(const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New, const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc=SourceLocation())
Determine whether the given template parameter lists are equivalent.
bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMemberKind CSM, InheritedConstructorInfo *ICI=nullptr, bool Diagnose=false)
Determine if a special member function should have a deleted definition when it is defaulted.
void ActOnExitFunctionContext()
void inferLifetimeCaptureByAttribute(FunctionDecl *FD)
Add [[clang:lifetime_capture_by(this)]] to STL container methods.
Definition SemaAttr.cpp:277
ExprResult RebuildExprInCurrentInstantiation(Expr *E)
DeclResult ActOnVarTemplateSpecialization(Scope *S, Declarator &D, TypeSourceInfo *DI, LookupResult &Previous, SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, StorageClass SC, bool IsPartialSpecialization)
PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, const Decl *D=nullptr, QualType BlockType=QualType())
Pop a function (or block or lambda or captured region) scope from the stack.
Definition Sema.cpp:2442
Preprocessor & getPreprocessor() const
Definition Sema.h:923
void deduceOpenCLAddressSpace(ValueDecl *decl)
PragmaStack< FPOptionsOverride > FpPragmaStack
Definition Sema.h:2047
PragmaStack< StringLiteral * > CodeSegStack
Definition Sema.h:2041
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:4133
@ Delete
deleted-function-body
Definition Sema.h:4139
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:1529
sema::LambdaScopeInfo * RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator)
FunctionDecl * getCurFunctionDecl(bool AllowLambda=false) const
Returns a pointer to the innermost enclosing function, or nullptr if the current context is not insid...
Definition Sema.cpp:1647
const AttributedType * getCallingConvAttributedType(QualType T) const
Get the outermost AttributedType node that sets a calling convention.
TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S)
isTagName() - This method is called for error recovery purposes only to determine if the specified na...
Definition SemaDecl.cpp:671
bool CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old)
[module.interface]p6: A redeclaration of an entity X is implicitly exported if X was introduced by an...
void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass &SC)
CheckConversionDeclarator - Called by ActOnDeclarator to check the well-formednes of the conversion f...
VisibilityAttr * mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, VisibilityAttr::VisibilityType Vis)
TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool &MemberOfUnknownSpecialization, bool Disambiguation=false)
Decl * ActOnFileScopeAsmDecl(Expr *expr, SourceLocation AsmLoc, SourceLocation RParenLoc)
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
ASTContext & Context
Definition Sema.h:1282
void FinalizeDeclaration(Decl *D)
FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform any semantic actions neces...
void LazyProcessLifetimeCaptureByParams(FunctionDecl *FD)
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:921
void ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement)
void * SkippedDefinitionContext
Definition Sema.h:4357
bool LookupBuiltin(LookupResult &R)
Lookup a builtin function, when name lookup would otherwise fail.
SemaObjC & ObjC()
Definition Sema.h:1489
void DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record)
Emit diagnostic warnings for placeholder members.
void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, TypedefNameDecl *NewTD)
bool isRedefinitionAllowedFor(NamedDecl *D, NamedDecl **Suggested, bool &Visible)
Determine if D has a definition which allows we redefine it in current TU.
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType=nullptr)
Definition SemaDecl.cpp:75
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
PragmaStack< bool > StrictGuardStackCheckStack
Definition Sema.h:2044
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:3557
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:924
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:2040
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition Sema.cpp:756
bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S)
isMicrosoftMissingTypename - In Microsoft mode, within class scope, if a CXXScopeSpec's type is equal...
Definition SemaDecl.cpp:695
bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen)
void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord)
Add gsl::Pointer attribute to std::container::iterator.
Definition SemaAttr.cpp:112
bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn)
We've just determined that Old and New both appear to be definitions of the same variable.
OverloadKind CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &OldDecls, NamedDecl *&OldDecl, bool UseMemberUsingDeclRules)
Determine whether the given New declaration is an overload of the declarations in Old.
bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a literal type.
void ProcessPragmaWeak(Scope *S, Decl *D)
bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee)
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition Sema.h:1190
Decl * BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, AccessSpecifier AS, RecordDecl *Record, const PrintingPolicy &Policy)
BuildAnonymousStructOrUnion - Handle the declaration of an anonymous structure or union.
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition Sema.cpp:1652
bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag, bool isDefinition, SourceLocation NewTagLoc, const IdentifierInfo *Name)
Determine whether a tag with a given kind is acceptable as a redeclaration of the given tag declarati...
void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F)
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE)
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition Sema.h:12080
EnumDecl * getStdAlignValT() const
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition Sema.h:8314
bool CheckFunctionTemplateSpecialization(FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous, bool QualifiedFriend=false)
Perform semantic analysis for the given function template specialization.
bool UnifySection(StringRef SectionName, int SectionFlags, NamedDecl *TheDecl)
Definition SemaAttr.cpp:795
void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld)
MergeVarDeclTypes - We parsed a variable 'New' which has the same name and scope as a previous declar...
void PushFunctionScope()
Enter a new function scope.
Definition Sema.cpp:2330
ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, NamedDecl *Found, SourceLocation NameLoc, const Token &NextToken)
Act on the result of classifying a name as a specific non-type declaration.
bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS)
void inferGslOwnerPointerAttribute(CXXRecordDecl *Record)
Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
Definition SemaAttr.cpp:168
llvm::function_ref< void(SourceLocation Loc, PartialDiagnostic PD)> DiagReceiverTy
Definition Sema.h:4566
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:919
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:272
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:83
sema::LambdaScopeInfo * PushLambdaScope()
Definition Sema.cpp:2348
void PopCompoundScope()
Definition Sema.cpp:2481
SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, SourceLocation IILoc)
Determine whether the body of an anonymous enumeration should be skipped.
@ UPPC_FixedUnderlyingType
The fixed underlying type of an enumeration.
Definition Sema.h:14244
@ UPPC_EnumeratorValue
The enumerator value.
Definition Sema.h:14247
@ UPPC_Initializer
An initializer.
Definition Sema.h:14259
@ UPPC_FriendDeclaration
A friend declaration.
Definition Sema.h:14253
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition Sema.h:14232
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition Sema.h:14271
@ UPPC_DeclarationQualifier
A declaration qualifier.
Definition Sema.h:14256
@ UPPC_DataMemberType
The type of a data member.
Definition Sema.h:14235
@ UPPC_BitFieldWidth
The size of a bit-field.
Definition Sema.h:14238
const LangOptions & getLangOpts() const
Definition Sema.h:917
void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl, bool SupportedForCompatibility=false)
DiagnoseTemplateParameterShadow - Produce a diagnostic complaining that the template parameter 'PrevD...
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
bool RebuildTemplateParamsInCurrentInstantiation(TemplateParameterList *Params)
Rebuild the template parameters now that we know we're in a current instantiation.
void DiagnoseInvalidJumps(Stmt *Body)
SourceLocation CurInitSegLoc
Definition Sema.h:2080
void inferLifetimeBoundAttribute(FunctionDecl *FD)
Add [[clang:lifetimebound]] attr for std:: functions and methods.
Definition SemaAttr.cpp:220
bool currentModuleIsHeaderUnit() const
Is the module scope we are in a C++ Header Unit?
Definition Sema.h:3574
SemaOpenACC & OpenACC()
Definition Sema.h:1494
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:1281
bool CheckConstexprFunctionDefinition(const FunctionDecl *FD, CheckConstexprKind Kind)
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
MinSizeAttr * mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI)
NamedDecl * getShadowedDeclaration(const TypedefNameDecl *D, const LookupResult &R)
Return the declaration shadowed by the given typedef D, or null if it doesn't shadow any declaration ...
void checkTypeSupport(QualType Ty, SourceLocation Loc, ValueDecl *D=nullptr)
Check if the type is allowed to be used for the current target.
Definition Sema.cpp:2113
void CheckExtraCXXDefaultArguments(Declarator &D)
CheckExtraCXXDefaultArguments - Check for any extra default arguments in the declarator,...
void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD)
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, bool AllowExplicitConversion=false, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, ConversionSequenceList EarlyConversions={}, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false, bool StrictPackMatch=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
const LangOptions & LangOpts
Definition Sema.h:1280
bool ActOnDuplicateDefinition(Scope *S, Decl *Prev, SkipBodyInfo &SkipBody)
Perform ODR-like check for C/ObjC when merging tag types from modules.
void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock)
void PushExpressionEvaluationContextForFunction(ExpressionEvaluationContext NewContext, FunctionDecl *FD)
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition Sema.cpp:2557
bool isReachable(const NamedDecl *D)
Determine whether a declaration is reachable.
Definition Sema.h:15336
Decl * ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody=nullptr, FnBodyKind BodyKind=FnBodyKind::Other)
SemaHLSL & HLSL()
Definition Sema.h:1454
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:1817
SemaRISCV & RISCV()
Definition Sema.h:1519
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:15510
bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD, SourceLocation ReturnLoc, Expr *RetExpr, const AutoType *AT)
Deduce the return type for a function from a returned expression, per C++1y [dcl.spec....
void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D)
Definition SemaExpr.cpp:207
void CheckCXXDefaultArguments(FunctionDecl *FD)
Helpers for dealing with blocks and functions.
bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS)
checkUnsafeAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained type.
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AttrList, const ProcessDeclAttributeOptions &Options=ProcessDeclAttributeOptions())
ProcessDeclAttributeList - Apply all the decl attributes in the specified attribute list to the speci...
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired=false)
Note that the vtable for the given class was used at the given location.
SemaSwift & Swift()
Definition Sema.h:1534
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:2029
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:6922
PragmaStack< StringLiteral * > BSSSegStack
Definition Sema.h:2039
bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true, bool AllowNonTemplateFunctions=false)
DeclContext * getCurLexicalContext() const
Definition Sema.h:1123
bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous)
Perform semantic analysis for the given dependent function template specialization.
bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl)
CheckOverloadedOperatorDeclaration - Check whether the declaration of this overloaded operator is wel...
bool hasExplicitCallingConv(QualType T)
NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc, const Token &NextToken, CorrectionCandidateCallback *CCC=nullptr)
Perform name lookup on the given name, classifying it based on the results of name lookup and the fol...
Definition SemaDecl.cpp:894
void ExitDeclaratorContext(Scope *S)
void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI)
Diagnose shadowing for variables shadowed in the lambda record LambdaRD when these variables are capt...
void CheckConstructor(CXXConstructorDecl *Constructor)
CheckConstructor - Checks a fully-formed constructor for well-formedness, issuing any diagnostics req...
void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMemberKind CSM)
Diagnose why the specified class does not have a trivial special member of the given kind.
llvm::SmallSetVector< Decl *, 4 > DeclsToCheckForDeferredDiags
Function or variable declarations to be checked for whether the deferred diagnostics should be emitte...
Definition Sema.h:4743
void CheckMSVCRTEntryPoint(FunctionDecl *FD)
sema::FunctionScopeInfo * getCurFunction() const
Definition Sema.h:1313
void PushCompoundScope(bool IsStmtExpr)
Definition Sema.cpp:2476
DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef< Decl * > Group)
BuildDeclaratorGroup - convert a list of declarations into a declaration group, performing any necess...
FunctionDecl * CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID, SourceLocation Loc)
Scope * getNonFieldDeclScope(Scope *S)
getNonFieldDeclScope - Retrieves the innermost scope, starting from S, where a non-field would be dec...
void ActOnPragmaWeakID(IdentifierInfo *WeakName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc)
ActOnPragmaWeakID - Called on well formed #pragma weak ident.
bool CheckNontrivialField(FieldDecl *FD)
llvm::DenseMap< const VarDecl *, int > RefsMinusAssignments
Increment when we find a reference; decrement when we find an ignored assignment.
Definition Sema.h:6919
void AddPushedVisibilityAttribute(Decl *RD)
AddPushedVisibilityAttribute - If '#pragma GCC visibility' was used, add an appropriate visibility at...
bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method)
Check whether 'this' shows up in the attributes of the given static member function.
DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, AccessSpecifier AS, SourceLocation ModulePrivateLoc, SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody=nullptr)
QualType DeduceTemplateSpecializationFromInitializer(TypeSourceInfo *TInfo, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Init)
bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous)
Perform semantic checking on a newly-created variable declaration.
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:633
MSInheritanceAttr * mergeMSInheritanceAttr(Decl *D, const AttributeCommonInfo &CI, bool BestCase, MSInheritanceModel Model)
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition Sema.h:15330
StringLiteral * CurInitSeg
Last section used with pragma init_seg.
Definition Sema.h:2079
FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl, bool Final=false)
Module * getCurrentModule() const
Get the module unit whose scope we are currently within.
Definition Sema.h:9816
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:1417
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
SemaOpenCL & OpenCL()
Definition Sema.h:1499
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
TypeSourceInfo * RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name)
Rebuilds a type within the context of the current instantiation.
Decl * ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, MultiTemplateParamsArg TemplateParams, SourceLocation EllipsisLoc)
Handle a friend type declaration.
void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
ParmVarDecl * CheckParameter(DeclContext *DC, SourceLocation StartLoc, SourceLocation NameLoc, const IdentifierInfo *Name, QualType T, TypeSourceInfo *TSInfo, StorageClass SC)
bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc=SourceLocation(), bool ForOverloadResolution=false)
Check whether the given function decl's trailing requires clause is satisfied, if any.
bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl)
CheckLiteralOperatorDeclaration - Check whether the declaration of this literal operator function is ...
void CheckShadowingDeclModification(Expr *E, SourceLocation Loc)
Warn if 'E', which is an expression that is about to be modified, refers to a shadowing declaration.
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
void notePreviousDefinition(const NamedDecl *Old, SourceLocation New)
void applyFunctionAttributesBeforeParsingBody(Decl *FD)
DLLExportAttr * mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI)
void CleanupMergedEnum(Scope *S, Decl *New)
CleanupMergedEnum - We have just merged the decl 'New' by making another definition visible.
DeclContext * OriginalLexicalContext
Generally null except when we temporarily switch decl contexts, like in.
Definition Sema.h:3571
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:13798
SourceManager & getSourceManager() const
Definition Sema.h:922
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:3524
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:1818
@ NTCUK_Destruct
Definition Sema.h:4072
@ NTCUK_Init
Definition Sema.h:4071
@ NTCUK_Copy
Definition Sema.h:4073
PragmaClangSection PragmaClangDataSection
Definition Sema.h:1815
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:6724
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:218
bool CheckParmsForFunctionDef(ArrayRef< ParmVarDecl * > Parameters, bool CheckParameterNames)
CheckParmsForFunctionDef - Check that the parameters of the given function are appropriate for the de...
TopLevelStmtDecl * ActOnStartTopLevelStmtDecl(Scope *S)
void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R)
Diagnose variable or built-in function shadowing.
void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor)
Build an exception spec for destructors that don't have one.
bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
Perform semantic analysis for the given non-template member specialization.
TypeResult ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, const IdentifierInfo &II, SourceLocation IdLoc, ImplicitTypenameContext IsImplicitTypename=ImplicitTypenameContext::No)
Called when the parser has parsed a C++ typename specifier, e.g., "typename T::type".
OptimizeNoneAttr * mergeOptimizeNoneAttr(Decl *D, const AttributeCommonInfo &CI)
bool CheckImmediateEscalatingFunctionDefinition(FunctionDecl *FD, const sema::FunctionScopeInfo *FSI)
void InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor)
In the MS ABI, we need to instantiate default arguments of dllexported default constructors along wit...
void CheckCompleteVariableDeclaration(VarDecl *VD)
bool IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, ArrayRef< Decl * > Group)
void setFunctionHasBranchProtectedScope()
Definition Sema.cpp:2497
RedeclarationKind forRedeclarationInCurContext() const
void MergeVarDecl(VarDecl *New, LookupResult &Previous)
MergeVarDecl - We just parsed a variable 'New' which has the same name and scope as a previous declar...
LazyDeclPtr StdNamespace
The C++ "std" namespace, where the standard library resides.
Definition Sema.h:6485
ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II, SourceLocation NameLoc, bool IsTemplateTypeArg)
Attempt to behave like MSVC in situations where lookup of an unqualified type name has failed in a de...
Definition SemaDecl.cpp:623
EnforceTCBLeafAttr * mergeEnforceTCBLeafAttr(Decl *D, const EnforceTCBLeafAttr &AL)
void ActOnLastBitfield(SourceLocation DeclStart, SmallVectorImpl< Decl * > &AllIvarDecls)
ActOnLastBitfield - This routine handles synthesized bitfields rules for class and class extensions.
void FinalizeVarWithDestructor(VarDecl *VD, CXXRecordDecl *DeclInit)
FinalizeVarWithDestructor - Prepare for calling destructor on the constructed variable.
void MarkUnusedFileScopedDecl(const DeclaratorDecl *D)
If it's a file scoped decl that must warn if not used, keep track of it.
llvm::DenseMap< IdentifierInfo *, AsmLabelAttr * > ExtnameUndeclaredIdentifiers
ExtnameUndeclaredIdentifiers - Identifiers contained in #pragma redefine_extname before declared.
Definition Sema.h:3545
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=AllowFoldKind::No)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec *SS=nullptr, bool isClassName=false, bool HasTrailingDot=false, ParsedType ObjectType=nullptr, bool IsCtorOrDtorName=false, bool WantNontrivialTypeSourceInfo=false, bool IsClassTemplateDeductionContext=true, ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No, IdentifierInfo **CorrectedII=nullptr)
If the identifier refers to a type name within this scope, return the declaration of that type.
Definition SemaDecl.cpp:270
EnumConstantDecl * CheckEnumConstant(EnumDecl *Enum, EnumConstantDecl *LastEnumConst, SourceLocation IdLoc, IdentifierInfo *Id, Expr *val)
bool CheckForConstantInitializer(Expr *Init, unsigned DiagID=diag::err_init_element_not_constant)
type checking declaration initializers (C99 6.7.8)
ASTConsumer & Consumer
Definition Sema.h:1283
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition Sema.h:4629
SmallVector< ExprWithCleanups::CleanupObject, 8 > ExprCleanupObjects
ExprCleanupObjects - This is the stack of objects requiring cleanup that are created by the current f...
Definition Sema.h:6926
void DiagnoseUnusedNestedTypedefs(const RecordDecl *D)
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition Sema.h:1318
bool hasUncompilableErrorOccurred() const
Whether uncompilable error has occurred.
Definition Sema.cpp:1772
@ FirstDecl
Parsing the first decl in a TU.
Definition Sema.h:9844
void CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc)
void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FunctionDecl *FD)
If this function is a C++ replaceable global allocation function (C++2a [basic.stc....
FormatAttr * mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Format, int FormatIdx, int FirstArg)
void ActOnDocumentableDecls(ArrayRef< Decl * > Group)
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
void CheckStaticLocalForDllExport(VarDecl *VD)
Check if VD needs to be dllexport/dllimport due to being in a dllexport/import function.
void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery=true)
DeclResult ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, AccessSpecifier AS, SourceLocation ModulePrivateLoc, MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, bool &IsDependent, SourceLocation ScopedEnumKWLoc, bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, bool IsTypeSpecifier, bool IsTemplateParamOrArg, OffsetOfKind OOK, SkipBodyInfo *SkipBody=nullptr)
This is invoked when we see 'struct foo' or 'struct {'.
Decl * ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, const ParsedAttributesView &DeclAttrs, RecordDecl *&AnonRecord)
ParsedFreeStandingDeclSpec - This method is invoked when a declspec with no declarator (e....
SemaPPC & PPC()
Definition Sema.h:1509
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:1245
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:3564
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:8269
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:1285
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:1284
OpenCLOptions & getOpenCLOptions()
Definition Sema.h:918
FPOptions CurFPFeatures
Definition Sema.h:1278
static bool CanBeGetReturnObject(const FunctionDecl *FD)
NamespaceDecl * getStdNamespace() const
bool IsAtLeastAsConstrained(const NamedDecl *D1, MutableArrayRef< AssociatedConstraint > AC1, const NamedDecl *D2, MutableArrayRef< AssociatedConstraint > AC2, bool &Result)
Check whether the given declaration's associated constraints are at least as constrained than another...
NamedDecl * ActOnTypedefDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous)
PragmaStack< StringLiteral * > DataSegStack
Definition Sema.h:2038
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:11537
@ TPC_ClassTemplateMember
Definition Sema.h:11535
@ TPC_FunctionTemplate
Definition Sema.h:11534
@ TPC_FriendFunctionTemplateDefinition
Definition Sema.h:11538
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:1559
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:6501
QualType CheckConstructorDeclarator(Declarator &D, QualType R, StorageClass &SC)
CheckConstructorDeclarator - Called by ActOnDeclarator to check the well-formedness of the constructo...
void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD)
ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in it, apply them to D.
QualType SubstAutoTypeDependent(QualType TypeWithAuto)
void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace)
Filters out lookup results that don't fall within the given scope as determined by isDeclInScope.
void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, const WeakInfo &W)
DeclApplyPragmaWeak - A declaration (maybe definition) needs #pragma weak applied to it,...
bool IsInvalidSMECallConversion(QualType FromType, QualType ToType)
void ActOnUninitializedDecl(Decl *dcl)
void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc)
Emit diagnostics if the initializer or any of its explicit or implicitly-generated subexpressions req...
static Scope * getScopeForDeclContext(Scope *S, DeclContext *DC)
Finds the scope corresponding to the given decl context, if it happens to be an enclosing scope.
TypedefDecl * ParseTypedefDecl(Scope *S, Declarator &D, QualType T, TypeSourceInfo *TInfo)
Subroutines of ActOnDeclarator().
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit)
AddInitializerToDecl - Adds the initializer Init to the declaration dcl.
bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckOverridingFunctionExceptionSpec - Checks whether the exception spec is a subset of base spec.
Decl * ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth)
ActOnField - Each field of a C struct/union is passed into this in order to create a FieldDecl object...
FormatMatchesAttr * mergeFormatMatchesAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Format, int FormatIdx, StringLiteral *FormatStr)
AvailabilityAttr * mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI, IdentifierInfo *Platform, bool Implicit, VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable, StringRef Message, bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK, int Priority, IdentifierInfo *IIEnvironment)
void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old)
bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC, SkipBodyInfo *SkipBody=nullptr)
Checks the validity of a template parameter list, possibly considering the template parameter list fr...
void ActOnCXXForRangeDecl(Decl *D)
bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckOverridingFunctionReturnType - Checks whether the return types are covariant,...
std::tuple< MangleNumberingContext *, Decl * > getCurrentMangleNumberContext(const DeclContext *DC)
Compute the mangling number context for a lambda expression or block literal.
llvm::MapVector< IdentifierInfo *, llvm::SetVector< WeakInfo, llvm::SmallVector< WeakInfo, 1u >, llvm::SmallDenseSet< WeakInfo, 2u, WeakInfo::DenseMapInfoByAliasOnly > > > WeakUndeclaredIdentifiers
WeakUndeclaredIdentifiers - Identifiers contained in #pragma weak before declared.
Definition Sema.h:3539
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition Sema.cpp:2096
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
PragmaClangSection PragmaClangBSSSection
Definition Sema.h:1814
Decl * ActOnDeclarator(Scope *S, Declarator &D)
@ AbstractVariableType
Definition Sema.h:6195
@ AbstractReturnType
Definition Sema.h:6193
@ AbstractFieldType
Definition Sema.h:6196
@ AbstractIvarType
Definition Sema.h:6197
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:8318
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:6382
void CheckVariableDeclarationType(VarDecl *NewVD)
OpaquePtr< TemplateName > TemplateTy
Definition Sema.h:1274
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:3520
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:1544
IdentifierResolver IdResolver
Definition Sema.h:3468
bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, bool AllowMask) const
IsValueInFlagEnum - Determine if a value is allowed as part of a flag enum.
bool hasAnyUnrecoverableErrorsInThisFunction() const
Determine whether any errors occurred within this function/method/ block.
Definition Sema.cpp:2488
void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc, Scope *S, CXXScopeSpec *SS, ParsedType &SuggestedType, bool IsTemplateName=false)
Definition SemaDecl.cpp:714
void DiagnoseSizeOfParametersAndReturnValue(ArrayRef< ParmVarDecl * > Parameters, QualType ReturnTy, NamedDecl *D)
Diagnose whether the size of parameters or return value of a function or obj-c method definition is p...
void checkTypeDeclType(DeclContext *LookupCtx, DiagCtorKind DCK, TypeDecl *TD, SourceLocation NameLoc)
Returns the TypeDeclType for the given type declaration, as ASTContext::getTypeDeclType would,...
Definition SemaDecl.cpp:143
void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD)
llvm::SmallVector< std::pair< SourceLocation, const BlockDecl * >, 1 > ImplicitlyRetainedSelfLocs
List of SourceLocations where 'self' is implicitly retained inside a block.
Definition Sema.h:8277
OpaquePtr< DeclGroupRef > DeclGroupPtrTy
Definition Sema.h:1273
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:3812
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:1424
void inferNullableClassAttribute(CXXRecordDecl *CRD)
Add _Nullable attributes for std:: types.
Definition SemaAttr.cpp:322
void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, SourceLocation FinalLoc, bool IsFinalSpelledSealed, bool IsAbstract, SourceLocation TriviallyRelocatable, SourceLocation Replaceable, SourceLocation LBraceLoc)
ActOnStartCXXMemberDeclarations - Invoked when we have parsed a C++ record definition's base-specifie...
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8608
ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet)
Act on the result of classifying a name as an overload set.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
This class handles loading and caching of source files into memory.
bool isInMainFile(SourceLocation Loc) const
Returns whether the PresumedLoc for a given SourceLocation is in the main file.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
Stmt - This represents one statement.
Definition Stmt.h:85
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:358
child_range children()
Definition Stmt.cpp:295
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:334
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:346
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h: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:3714
static TagDecl * castFromDeclContext(const DeclContext *DC)
Definition Decl.h:3996
TagDecl * getDefinition() const
Returns the TagDecl that actually defines this struct/union/class/enum.
Definition Decl.cpp:4870
bool isThisDeclarationADefinition() const
Return true if this declaration is a completion definition of the type.
Definition Decl.h:3804
SourceLocation getInnerLocStart() const
Return SourceLocation representing start of source range ignoring outer template declarations.
Definition Decl.h:3790
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3809
bool isStruct() const
Definition Decl.h:3916
void setTypedefNameForAnonDecl(TypedefNameDecl *TDD)
Definition Decl.cpp:4842
bool isUnion() const
Definition Decl.h:3919
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type?
Definition Decl.h:3941
TagKind getTagKind() const
Definition Decl.h:3908
bool isDependentType() const
Whether this declaration declares a type that is dependent, i.e., a type that somehow depends on temp...
Definition Decl.h:3854
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:810
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Exposes information about the current target.
Definition TargetInfo.h:226
virtual bool validateCpuIs(StringRef Name) const
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
virtual llvm::APInt getFMVPriority(ArrayRef< StringRef > Features) const
virtual bool validateCpuSupports(StringRef Name) const
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
virtual bool isValidFeatureName(StringRef Feature) const
Determine whether this TargetInfo supports the given feature.
virtual ParsedTargetAttr parseTargetAttr(StringRef Str) const
bool supportsMultiVersioning() const
Identify whether this target supports multiversioning of functions, which requires support for cpu_su...
virtual bool shouldDLLImportComdatSymbols() const
Does this target aim for semantic compatibility with Microsoft C++ code using dllimport/export attrib...
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
A convenient class for passing around template argument information.
void setLAngleLoc(SourceLocation Loc)
void setRAngleLoc(SourceLocation Loc)
ArrayRef< TemplateArgumentLoc > arguments() const
Location wrapper for a TemplateArgument.
The base class of all kinds of template declarations (e.g., class, function, etc.).
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
Stores a list of template parameters for a TemplateDecl and its derived classes.
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation getRAngleLoc() const
SourceLocation getTemplateLoc() const
Token - This structure provides full information about a lexed token.
Definition Token.h:36
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {....
Definition Token.h:102
bool isOneOf(Ts... Ks) const
Definition Token.h:104
bool isNot(tok::TokenKind K) const
Definition Token.h:103
A declaration that models statements at global scope.
Definition Decl.h:4614
static TopLevelStmtDecl * Create(ASTContext &C, Stmt *Statement)
Definition Decl.cpp:5734
void setStmt(Stmt *S)
Definition Decl.cpp:5754
Represents a declaration of a type.
Definition Decl.h:3510
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
TypeSpecTypeLoc pushTypeSpec(QualType T)
Pushes space for a typespec TypeLoc.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:59
UnqualTypeLoc getUnqualifiedLoc() const
Skips past any qualifiers, if this is qualified.
Definition TypeLoc.h:354
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:89
TypeLoc IgnoreParens() const
Definition TypeLoc.h:1417
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition TypeLoc.h:78
void initializeFullCopy(TypeLoc Other)
Initializes this by copying its information from another TypeLoc of the same type.
Definition TypeLoc.h:222
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition TypeLoc.h:154
AutoTypeLoc getContainedAutoTypeLoc() const
Get the typeloc of an AutoType whose type will be deduced for a variable with an initializer of this ...
Definition TypeLoc.cpp:913
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:2715
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:193
A container of type source information.
Definition TypeBase.h:8256
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:272
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8267
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:556
The base class of the type hierarchy.
Definition TypeBase.h:1833
bool isStructureType() const
Definition Type.cpp:678
bool isDependentSizedArrayType() const
Definition TypeBase.h:8641
bool isVoidType() const
Definition TypeBase.h:8878
bool isBooleanType() const
Definition TypeBase.h:9008
bool isFunctionReferenceType() const
Definition TypeBase.h:8596
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2225
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition TypeBase.h:9058
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:8629
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9174
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:8625
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition TypeBase.h:9038
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isArrayType() const
Definition TypeBase.h:8621
bool isFunctionPointerType() const
Definition TypeBase.h:8589
bool isPointerType() const
Definition TypeBase.h:8522
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9165
bool isReferenceType() const
Definition TypeBase.h:8546
bool isScalarType() const
Definition TypeBase.h:8980
bool isVariableArrayType() const
Definition TypeBase.h:8633
bool isClkEventT() const
Definition TypeBase.h:8764
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2103
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:752
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:8996
TagDecl * getAsTagDecl() const
Retrieves the TagDecl that this type refers to, either because the type is a TagType or because it is...
Definition Type.h:65
bool isImageType() const
Definition TypeBase.h:8776
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition TypeBase.h:2899
bool isPipeType() const
Definition TypeBase.h:8783
bool isOpenCLSpecificType() const
Definition TypeBase.h:8812
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2782
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition Type.cpp:2411
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool isHalfType() const
Definition TypeBase.h:8882
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition Type.cpp:2056
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition Type.cpp:2558
bool containsErrors() const
Whether this type is an error type.
Definition TypeBase.h:2776
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition TypeBase.h:9051
bool isAtomicType() const
Definition TypeBase.h:8704
bool isFunctionProtoType() const
Definition TypeBase.h:2601
bool isObjCIdType() const
Definition TypeBase.h:8724
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2800
bool isObjCObjectType() const
Definition TypeBase.h:8695
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9014
bool isEventT() const
Definition TypeBase.h:8760
bool isPointerOrReferenceType() const
Definition TypeBase.h:8526
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:9115
bool isFunctionType() const
Definition TypeBase.h:8518
bool isObjCObjectPointerType() const
Definition TypeBase.h:8691
bool isMemberFunctionPointerType() const
Definition TypeBase.h:8607
bool isFloatingType() const
Definition Type.cpp:2304
bool isAnyPointerType() const
Definition TypeBase.h:8530
bool hasAutoForTrailingReturnType() const
Determine whether this type was written with a leading 'auto' corresponding to a trailing return type...
Definition Type.cpp:2061
bool isSamplerT() const
Definition TypeBase.h:8756
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9098
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:653
bool isNullPtrType() const
Definition TypeBase.h:8915
bool isRecordType() const
Definition TypeBase.h:8649
bool isHLSLResourceRecordArray() const
Definition Type.cpp:5374
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5022
bool isUnionType() const
Definition Type.cpp:718
bool isFunctionNoProtoType() const
Definition TypeBase.h:2600
bool isReserveIDT() const
Definition TypeBase.h:8772
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition Decl.h:3664
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition Decl.cpp:5633
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3559
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:3609
QualType getUnderlyingType() const
Definition Decl.h:3614
void setTypeSourceInfo(TypeSourceInfo *newType)
Definition Decl.h:3620
Wrapper for source info for typedefs.
Definition TypeLoc.h:782
TypedefNameDecl * getDecl() const
Definition TypeBase.h:6109
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:787
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3399
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3463
BaseUsingDecl * getIntroducer() const
Gets the (written or instantiated) using declaration that introduced this declaration.
Definition DeclCXX.cpp:3374
Wrapper for source info for types used via transparent aliases.
Definition TypeLoc.h:790
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:711
void setType(QualType newType)
Definition Decl.h:723
QualType getType() const
Definition Decl.h:722
bool isParameterPack() const
Determine whether this value is actually a function parameter pack, init-capture pack,...
Definition Decl.cpp:5465
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.cpp:5459
Represents a variable declaration or definition.
Definition Decl.h:925
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition Decl.cpp:2810
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition Decl.cpp:2151
void setCXXForRangeDecl(bool FRD)
Definition Decl.h:1524
bool isFirstDecl() const
True if this is the first declaration in its redeclaration chain.
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition Decl.h:1568
TLSKind getTLSKind() const
Definition Decl.cpp:2168
bool hasInit() const
Definition Decl.cpp:2398
void setInitStyle(InitializationStyle Style)
Definition Decl.h:1451
VarDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
Definition Decl.cpp:2260
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2190
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a static data member.
Definition Decl.cpp:2461
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:2257
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.h:1577
bool isCXXCondDecl() const
Definition Decl.h:1610
@ ListInit
Direct list-initialization (C++11)
Definition Decl.h:936
@ ParenListInit
Parenthesized list-initialization (C++20)
Definition Decl.h:939
@ CallInit
Call-style initialization (C++98)
Definition Decl.h:933
void setStorageClass(StorageClass SC)
Definition Decl.cpp:2163
void setPreviousDeclInSameBlockScope(bool Same)
Definition Decl.h:1592
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1282
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition Decl.h:1225
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition Decl.cpp:2366
void setInlineSpecified()
Definition Decl.h:1557
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1207
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition Decl.cpp:2772
bool isFileVarDecl() const
Returns true for file scoped variable declaration.
Definition Decl.h:1341
void setTSCSpec(ThreadStorageClassSpecifier TSC)
Definition Decl.h:1172
bool isInline() const
Whether this variable is (C++1z) inline.
Definition Decl.h:1550
ThreadStorageClassSpecifier getTSCSpec() const
Definition Decl.h:1176
const Expr * getInit() const
Definition Decl.h:1367
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition Decl.h:1216
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition Decl.h:1183
VarDecl * getInitializingDeclaration()
Get the initializing declaration of this variable, if any.
Definition Decl.cpp:2429
void setConstexpr(bool IC)
Definition Decl.h:1571
@ TLS_Static
TLS with a known-constant initializer.
Definition Decl.h:948
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition Decl.h:951
void setInit(Expr *I)
Definition Decl.cpp:2477
VarDecl * getActingDefinition()
Get the tentative definition that acts as the real definition in a TU.
Definition Decl.cpp:2345
@ TentativeDefinition
This declaration is a tentative definition.
Definition Decl.h:1297
@ DeclarationOnly
This declaration is only a declaration.
Definition Decl.h:1294
@ Definition
This declaration is definitely a definition.
Definition Decl.h:1300
void setDescribedVarTemplate(VarTemplateDecl *Template)
Definition Decl.cpp:2815
bool isExternC() const
Determines whether this variable is a variable with external, C linkage.
Definition Decl.cpp:2245
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition Decl.h:1252
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:1167
void setImplicitlyInline()
Definition Decl.h:1562
bool isThisDeclarationADemotedDefinition() const
If this definition should pretend to be a declaration.
Definition Decl.h:1475
bool isPreviousDeclInSameBlockScope() const
Whether this local extern variable declaration's previous declaration was declared in the same block ...
Definition Decl.h:1587
VarDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
bool hasDependentAlignment() const
Determines if this variable's alignment is dependent.
Definition Decl.cpp:2706
bool isLocalVarDeclOrParm() const
Similar to isLocalVarDecl but also includes parameters.
Definition Decl.h:1261
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition Decl.cpp:2779
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition Decl.h:1357
Declaration of a variable template.
VarDecl * getTemplatedDecl() const
Get the underlying variable declarations of the template.
VarTemplateDecl * getInstantiatedFromMemberTemplate() const
static VarTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, VarDecl *Decl)
Create a variable template node.
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:3964
Expr * getSizeExpr() const
Definition TypeBase.h:3978
Captures information about a #pragma weak directive.
Definition Weak.h:25
ValueDecl * getVariable() const
Definition ScopeInfo.h:675
bool isVariableCapture() const
Definition ScopeInfo.h:650
SourceLocation getLocation() const
Retrieve the location at which this variable was captured.
Definition ScopeInfo.h:686
void addVLATypeCapture(SourceLocation Loc, const VariableArrayType *VLAType, QualType CaptureType)
Definition ScopeInfo.h:745
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition ScopeInfo.h:732
SmallVector< Capture, 4 > Captures
Captures - The captures.
Definition ScopeInfo.h:721
ImplicitCaptureStyle ImpCaptureStyle
Definition ScopeInfo.h:708
bool isCXXThisCaptured() const
Determine whether the C++ 'this' is captured.
Definition ScopeInfo.h:755
void addThisCapture(bool isNested, SourceLocation Loc, QualType CaptureType, bool ByCopy)
Definition ScopeInfo.h:1096
void addCapture(ValueDecl *Var, bool isBlock, bool isByref, bool isNested, SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType, bool Invalid)
Definition ScopeInfo.h:737
static DelayedDiagnostic makeForbiddenType(SourceLocation loc, unsigned diagnostic, QualType type, unsigned argument)
Retains information about a function, method, or block that is currently being parsed.
Definition ScopeInfo.h:104
bool UsesFPIntrin
Whether this function uses constrained floating point intrinsics.
Definition ScopeInfo.h:141
void addByrefBlockVar(VarDecl *VD)
Definition ScopeInfo.h:498
bool ObjCShouldCallSuper
A flag that is set when parsing a method that must call super's implementation, such as -dealloc,...
Definition ScopeInfo.h:150
bool ObjCWarnForNoInitDelegation
This starts true for a secondary initializer method and will be set to false if there is an invocatio...
Definition ScopeInfo.h:167
bool HasPotentialAvailabilityViolations
Whether we make reference to a declaration that could be unavailable.
Definition ScopeInfo.h:145
bool ObjCWarnForNoDesignatedInitChain
This starts true for a method marked as designated initializer and will be set to false if there is a...
Definition ScopeInfo.h:158
SourceRange IntroducerRange
Source range covering the lambda introducer [...].
Definition ScopeInfo.h:884
TemplateParameterList * GLTemplateParameterList
If this is a generic lambda, and the template parameter list has been created (from the TemplateParam...
Definition ScopeInfo.h:915
ParmVarDecl * ExplicitObjectParameter
Definition ScopeInfo.h:881
llvm::SmallVector< ShadowedOuterDecl, 4 > ShadowingDecls
Definition ScopeInfo.h:948
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition ScopeInfo.h:871
bool AfterParameterList
Indicate that we parsed the parameter list at which point the mutability of the lambda is known.
Definition ScopeInfo.h:879
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition ScopeInfo.h:874
bool Mutable
Whether this is a mutable lambda.
Definition ScopeInfo.h:896
Provides information about an attempted template argument deduction, whose success or failure was des...
#define bool
Definition gpuintrin.h:32
Defines the clang::TargetInfo interface.
bool evaluateRequiredTargetFeatures(llvm::StringRef RequiredFatures, const llvm::StringMap< bool > &TargetFetureMap)
Returns true if the required target features of a builtin function are enabled.
Public enums and private classes that are part of the SourceManager implementation.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
unsigned kind
All of the diagnostics that can be emitted by the frontend.
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
bool randomizeStructureLayout(const ASTContext &Context, RecordDecl *RD, llvm::SmallVectorImpl< Decl * > &FinalOrdering)
The JSON file list parser is used to communicate input to InstallAPI.
bool FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI)
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
@ TST_struct
Definition Specifiers.h:81
@ TST_class
Definition Specifiers.h:82
@ TST_union
Definition Specifiers.h:80
@ TST_enum
Definition Specifiers.h:79
@ TST_interface
Definition Specifiers.h:83
ImplicitTypenameContext
Definition DeclSpec.h:1857
@ NonFunction
This is not an overload because the lookup results contain a non-function.
Definition Sema.h:819
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:815
@ Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition Sema.h:811
bool isa(CodeGen::Address addr)
Definition Address.h:330
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition Specifiers.h:212
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus11
@ CPlusPlus14
@ CPlusPlus17
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition Ownership.h:263
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition Overload.h:55
@ GVA_AvailableExternally
Definition Linkage.h:74
CUDAFunctionTarget
Definition Cuda.h:60
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition ASTLambda.h:102
int hasAttribute(AttributeCommonInfo::Syntax Syntax, llvm::StringRef ScopeName, llvm::StringRef AttrName, const TargetInfo &Target, const LangOptions &LangOpts, bool CheckPlugins)
Return the version number associated with the attribute if we recognize and implement the attribute s...
ConstexprSpecKind
Define the kind of constexpr specifier.
Definition Specifiers.h:35
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition Lookup.h:64
@ NotFound
No entity found met the criteria.
Definition Lookup.h:41
@ FoundOverloaded
Name lookup found a set of overloaded functions that met the criteria.
Definition Lookup.h:54
@ Found
Name lookup found a single declaration that met the criteria.
Definition Lookup.h:50
@ FoundUnresolvedValue
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition Lookup.h:59
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition Lookup.h:46
InClassInitStyle
In-class initialization styles for non-static data members.
Definition Specifiers.h:271
@ ICIS_NoInit
No in-class initializer.
Definition Specifiers.h:272
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
Definition Parser.h:61
OverloadCandidateDisplayKind
Definition Overload.h:64
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
Definition Overload.h:73
@ OCD_AllCandidates
Requests that all candidates be shown.
Definition Overload.h:67
std::pair< FileID, unsigned > FileIDAndOffset
@ LCK_ByRef
Capturing by reference.
Definition Lambda.h:37
@ LCK_StarThis
Capturing the *this object by copy.
Definition Lambda.h:35
NonTagKind
Common ways to introduce type names without a tag for use in diagnostics.
Definition Sema.h:601
@ TemplateTemplateArgument
Definition Sema.h:610
NonTrivialCUnionContext
Definition Sema.h:529
AvailabilityMergeKind
Describes the kind of merge to perform for availability attributes (including "deprecated",...
Definition Sema.h:625
@ None
Don't merge availability attributes at all.
Definition Sema.h:627
@ Override
Merge availability attributes for an override, which requires an exact match or a weakening of constr...
Definition Sema.h:633
@ OptionalProtocolImplementation
Merge availability attributes for an implementation of an optional protocol requirement.
Definition Sema.h:639
@ Redeclaration
Merge availability attributes for a redeclaration, which requires an exact match.
Definition Sema.h:630
@ ProtocolImplementation
Merge availability attributes for an implementation of a protocol requirement.
Definition Sema.h:636
@ IK_DeductionGuideName
A deduction-guide name (a template-name)
Definition DeclSpec.h:994
@ IK_ImplicitSelfParam
An implicit 'self' parameter.
Definition DeclSpec.h:992
@ IK_TemplateId
A template-id, e.g., f<int>.
Definition DeclSpec.h:990
@ IK_ConstructorTemplateId
A constructor named via a template-id.
Definition DeclSpec.h:986
@ IK_ConstructorName
A constructor name.
Definition DeclSpec.h:984
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
Definition DeclSpec.h:982
@ IK_Identifier
An identifier.
Definition DeclSpec.h:976
@ IK_DestructorName
A destructor name.
Definition DeclSpec.h:988
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
Definition DeclSpec.h:978
@ IK_ConversionFunctionId
A conversion function name, e.g., operator int.
Definition DeclSpec.h:980
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition Specifiers.h:123
@ AS_public
Definition Specifiers.h:124
@ AS_protected
Definition Specifiers.h:125
@ AS_none
Definition Specifiers.h:127
SmallVector< Attr *, 4 > AttrVec
AttrVec - A vector of Attr, which is how they are stored on the AST.
ActionResult< Decl * > DeclResult
Definition Ownership.h:255
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
bool DeclAttrsMatchCUDAMode(const LangOptions &LangOpts, Decl *D)
@ AmbiguousTagHiding
Name lookup results in an ambiguity because an entity with a tag name was hidden by an entity with an...
Definition Lookup.h:137
LanguageLinkage
Describes the different kinds of language linkage (C++ [dcl.link]) that an entity may have.
Definition Linkage.h:63
@ CLanguageLinkage
Definition Linkage.h:64
@ CXXLanguageLinkage
Definition Linkage.h:65
StorageClass
Storage classes.
Definition Specifiers.h:248
@ SC_Auto
Definition Specifiers.h:256
@ SC_PrivateExtern
Definition Specifiers.h:253
@ SC_Extern
Definition Specifiers.h:251
@ SC_Register
Definition Specifiers.h:257
@ SC_Static
Definition Specifiers.h:252
@ SC_None
Definition Specifiers.h:250
@ TSCS_thread_local
C++11 thread_local.
Definition Specifiers.h:241
@ TSCS_unspecified
Definition Specifiers.h:236
@ TSCS__Thread_local
C11 _Thread_local.
Definition Specifiers.h:244
@ TSCS___thread
GNU __thread.
Definition Specifiers.h:238
const StreamingDiagnostic & operator<<(const StreamingDiagnostic &DB, const ASTContext::SectionInfo &Section)
Insertion operator for diagnostics.
std::pair< NullabilityKind, bool > DiagNullabilityKind
A nullability kind paired with a bit indicating whether it used a context-sensitive keyword.
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
Definition Linkage.h:24
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition Linkage.h:35
@ External
External linkage, which indicates that the entity can be referred to from other translation units.
Definition Linkage.h:58
@ Module
Module linkage, which indicates that the entity can be referred to from other translation units withi...
Definition Linkage.h:54
TemplateDecl * getAsTypeTemplateDecl(Decl *D)
llvm::Expected< Decl * > ExpectedDecl
@ SD_Thread
Thread storage duration.
Definition Specifiers.h:342
@ SD_Static
Static storage duration.
Definition Specifiers.h:343
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition ASTLambda.h:28
@ Parameter
The parameter type of a method or function.
Definition TypeBase.h:908
@ Result
The result type of a method or function.
Definition TypeBase.h:905
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
OffsetOfKind
Definition Sema.h:613
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:448
TagTypeKind
The kind of a tag type.
Definition TypeBase.h:5888
@ Interface
The "__interface" keyword.
Definition TypeBase.h:5893
@ Struct
The "struct" keyword.
Definition TypeBase.h:5890
@ Class
The "class" keyword.
Definition TypeBase.h:5899
@ Union
The "union" keyword.
Definition TypeBase.h:5896
@ Enum
The "enum" keyword.
Definition TypeBase.h:5902
LLVM_READONLY bool isWhitespace(unsigned char c)
Return true if this character is horizontal or vertical ASCII whitespace: ' ', '\t',...
Definition CharInfo.h:108
bool isDiscardableGVALinkage(GVALinkage L)
Definition Linkage.h:80
ExprResult ExprError()
Definition Ownership.h:265
LangAS
Defines the address space values used by the address space qualifier of QualType.
@ CanNeverPassInRegs
The argument of this type cannot be passed directly in registers.
Definition Decl.h:4302
@ TU_Complete
The translation unit is a complete translation unit.
MutableArrayRef< ParsedTemplateArgument > ASTTemplateArgsPtr
Definition Ownership.h:261
CXXSpecialMemberKind
Kinds of C++ special members.
Definition Sema.h:424
@ TNK_Type_template
The name refers to a template whose specialization produces a type.
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
LambdaCaptureDefault
The default, if any, capture method for a lambda expression.
Definition Lambda.h:22
@ LCD_ByRef
Definition Lambda.h:25
@ LCD_None
Definition Lambda.h:23
@ LCD_ByCopy
Definition Lambda.h:24
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:135
MultiVersionKind
Definition Decl.h:1978
bool isExternalFormalLinkage(Linkage L)
Definition Linkage.h:117
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1288
TemplateDeductionResult
Describes the result of template argument deduction.
Definition Sema.h:366
@ Success
Template argument deduction was successful.
Definition Sema.h:368
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:420
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:188
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition Specifiers.h:206
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:202
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:198
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:194
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:191
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:278
@ CC_X86StdCall
Definition Specifiers.h:280
U cast(CodeGen::Address addr)
Definition Address.h:327
@ None
The alignment was not explicit in code.
Definition ASTContext.h:146
@ Enumerator
Enumerator value with fixed underlying type.
Definition Sema.h:825
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:5884
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5874
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5877
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition TypeBase.h:5881
bool IsArmStreamingFunction(const FunctionDecl *FD, bool IncludeLocallyStreaming)
Returns whether the given FunctionDecl has an __arm[_locally]_streaming attribute.
Definition Decl.cpp:5971
ReservedIdentifierStatus
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Other
Other implicit parameter.
Definition Decl.h:1745
@ EST_None
no exception specification
@ EST_BasicNoexcept
noexcept
@ HiddenVisibility
Objects with "hidden" visibility are not seen by the dynamic linker.
Definition Visibility.h:37
ActionResult< Stmt * > StmtResult
Definition Ownership.h:250
bool isGenericLambdaCallOperatorSpecialization(const CXXMethodDecl *MD)
Definition ASTLambda.h:60
const Expr * ConstraintExpr
Definition Decl.h:87
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
DeclarationName getName() const
getName - Returns the embedded declaration name.
void setLoc(SourceLocation L)
setLoc - Sets the main location of the declaration name.
void setCXXLiteralOperatorNameLoc(SourceLocation Loc)
setCXXLiteralOperatorNameLoc - Sets the location of the literal operator name (not the operator keywo...
void setNamedTypeInfo(TypeSourceInfo *TInfo)
setNamedTypeInfo - Sets the source type info associated to the name.
void setCXXOperatorNameRange(SourceRange R)
setCXXOperatorNameRange - Sets the range of the operator name (without the operator keyword).
SourceRange getCXXOperatorNameRange() const
getCXXOperatorNameRange - Gets the range of the operator name (without the operator keyword).
void setName(DeclarationName N)
setName - Sets the embedded declaration name.
ParamInfo * Params
Params - This is a pointer to a new[]'d array of ParamInfo objects that describe the parameters speci...
Definition DeclSpec.h:1398
ArrayRef< NamedDecl * > getDeclsInPrototype() const
Get the non-parameter decls defined within this function prototype.
Definition DeclSpec.h:1549
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition DeclSpec.h:1373
unsigned hasPrototype
hasPrototype - This is true if the function had at least one typed parameter.
Definition DeclSpec.h:1332
const IdentifierInfo * Ident
Definition DeclSpec.h:1304
One instance of this struct is used for each type in a declarator that is parsed.
Definition DeclSpec.h:1221
const ParsedAttributesView & getAttrs() const
If there are attributes applied to this declaratorchunk, return them.
Definition DeclSpec.h:1633
static DeclaratorChunk getFunction(bool HasProto, bool IsAmbiguous, SourceLocation LParenLoc, ParamInfo *Params, unsigned NumParams, SourceLocation EllipsisLoc, SourceLocation RParenLoc, bool RefQualifierIsLvalueRef, SourceLocation RefQualifierLoc, SourceLocation MutableLoc, ExceptionSpecificationType ESpecType, SourceRange ESpecRange, ParsedType *Exceptions, SourceRange *ExceptionRanges, unsigned NumExceptions, Expr *NoexceptExpr, CachedTokens *ExceptionSpecTokens, ArrayRef< NamedDecl * > DeclsInPrototype, SourceLocation LocalRangeBegin, SourceLocation LocalRangeEnd, Declarator &TheDeclarator, TypeResult TrailingReturnType=TypeResult(), SourceLocation TrailingReturnTypeLoc=SourceLocation(), DeclSpec *MethodQualifiers=nullptr)
DeclaratorChunk::getFunction - Return a DeclaratorChunk for a function.
Definition DeclSpec.cpp:132
MemberPointerTypeInfo Mem
Definition DeclSpec.h:1614
FunctionTypeInfo Fun
Definition DeclSpec.h:1612
enum clang::DeclaratorChunk::@340323374315200305336204205154073066142310370142 Kind
static DeclaratorChunk getReference(unsigned TypeQuals, SourceLocation Loc, bool lvalue)
Return a DeclaratorChunk for a reference.
Definition DeclSpec.h:1657
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:645
Extra information about a function prototype.
Definition TypeBase.h:5349
ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI)
Definition TypeBase.h:5376
static StringRef getTagTypeKindName(TagTypeKind Kind)
Definition TypeBase.h:5927
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:2014
SourceLocation CurrentPragmaLocation
Definition Sema.h:2015
bool CheckSameAsPrevious
Definition Sema.h:352
NamedDecl * Previous
Definition Sema.h:353
NamedDecl * New
Definition Sema.h:354
Information about a template-id annotation token.
const IdentifierInfo * Name
FIXME: Temporarily stores the name of a specialization.
unsigned NumArgs
NumArgs - The number of template arguments.
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
SourceLocation LAngleLoc
The location of the '<' before the template argument list.
SourceLocation TemplateKWLoc
TemplateKWLoc - The location of the template keyword.
ParsedTemplateTy Template
The declaration of the template corresponding to the template-name.
OpaquePtr< T > get() const
Definition Ownership.h:105
SourceLocation SymbolLocations[3]
The source locations of the individual tokens that name the operator, e.g., the "new",...
Definition DeclSpec.h:1018
OverloadedOperatorKind Operator
The kind of overloaded operator.
Definition DeclSpec.h:1009