Bug Summary

File:clang/lib/Sema/SemaDecl.cpp
Warning:line 9907, column 19
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaDecl.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/build-llvm/tools/clang/lib/Sema -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D CLANG_ROUND_TRIP_CC1_ARGS=ON -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema -I /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include -I /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/build-llvm/include -I /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/include -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-08-28-193554-24367-1 -x c++ /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp

/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp

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"
14#include "clang/AST/ASTConsumer.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/ASTLambda.h"
17#include "clang/AST/CXXInheritance.h"
18#include "clang/AST/CharUnits.h"
19#include "clang/AST/CommentDiagnostic.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclObjC.h"
22#include "clang/AST/DeclTemplate.h"
23#include "clang/AST/EvaluatedExprVisitor.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/NonTrivialTypeVisitor.h"
27#include "clang/AST/StmtCXX.h"
28#include "clang/Basic/Builtins.h"
29#include "clang/Basic/PartialDiagnostic.h"
30#include "clang/Basic/SourceManager.h"
31#include "clang/Basic/TargetInfo.h"
32#include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
33#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
34#include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
35#include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
36#include "clang/Sema/CXXFieldCollector.h"
37#include "clang/Sema/DeclSpec.h"
38#include "clang/Sema/DelayedDiagnostic.h"
39#include "clang/Sema/Initialization.h"
40#include "clang/Sema/Lookup.h"
41#include "clang/Sema/ParsedTemplate.h"
42#include "clang/Sema/Scope.h"
43#include "clang/Sema/ScopeInfo.h"
44#include "clang/Sema/SemaInternal.h"
45#include "clang/Sema/Template.h"
46#include "llvm/ADT/SmallString.h"
47#include "llvm/ADT/Triple.h"
48#include <algorithm>
49#include <cstring>
50#include <functional>
51#include <unordered_map>
52
53using namespace clang;
54using namespace sema;
55
56Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
57 if (OwnedType) {
58 Decl *Group[2] = { OwnedType, Ptr };
59 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
60 }
61
62 return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
63}
64
65namespace {
66
67class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
68 public:
69 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
70 bool AllowTemplates = false,
71 bool AllowNonTemplates = true)
72 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
73 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
74 WantExpressionKeywords = false;
75 WantCXXNamedCasts = false;
76 WantRemainingKeywords = false;
77 }
78
79 bool ValidateCandidate(const TypoCorrection &candidate) override {
80 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
81 if (!AllowInvalidDecl && ND->isInvalidDecl())
82 return false;
83
84 if (getAsTypeTemplateDecl(ND))
85 return AllowTemplates;
86
87 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
88 if (!IsType)
89 return false;
90
91 if (AllowNonTemplates)
92 return true;
93
94 // An injected-class-name of a class template (specialization) is valid
95 // as a template or as a non-template.
96 if (AllowTemplates) {
97 auto *RD = dyn_cast<CXXRecordDecl>(ND);
98 if (!RD || !RD->isInjectedClassName())
99 return false;
100 RD = cast<CXXRecordDecl>(RD->getDeclContext());
101 return RD->getDescribedClassTemplate() ||
102 isa<ClassTemplateSpecializationDecl>(RD);
103 }
104
105 return false;
106 }
107
108 return !WantClassName && candidate.isKeyword();
109 }
110
111 std::unique_ptr<CorrectionCandidateCallback> clone() override {
112 return std::make_unique<TypeNameValidatorCCC>(*this);
113 }
114
115 private:
116 bool AllowInvalidDecl;
117 bool WantClassName;
118 bool AllowTemplates;
119 bool AllowNonTemplates;
120};
121
122} // end anonymous namespace
123
124/// Determine whether the token kind starts a simple-type-specifier.
125bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
126 switch (Kind) {
127 // FIXME: Take into account the current language when deciding whether a
128 // token kind is a valid type specifier
129 case tok::kw_short:
130 case tok::kw_long:
131 case tok::kw___int64:
132 case tok::kw___int128:
133 case tok::kw_signed:
134 case tok::kw_unsigned:
135 case tok::kw_void:
136 case tok::kw_char:
137 case tok::kw_int:
138 case tok::kw_half:
139 case tok::kw_float:
140 case tok::kw_double:
141 case tok::kw___bf16:
142 case tok::kw__Float16:
143 case tok::kw___float128:
144 case tok::kw_wchar_t:
145 case tok::kw_bool:
146 case tok::kw___underlying_type:
147 case tok::kw___auto_type:
148 return true;
149
150 case tok::annot_typename:
151 case tok::kw_char16_t:
152 case tok::kw_char32_t:
153 case tok::kw_typeof:
154 case tok::annot_decltype:
155 case tok::kw_decltype:
156 return getLangOpts().CPlusPlus;
157
158 case tok::kw_char8_t:
159 return getLangOpts().Char8;
160
161 default:
162 break;
163 }
164
165 return false;
166}
167
168namespace {
169enum class UnqualifiedTypeNameLookupResult {
170 NotFound,
171 FoundNonType,
172 FoundType
173};
174} // end anonymous namespace
175
176/// Tries to perform unqualified lookup of the type decls in bases for
177/// dependent class.
178/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
179/// type decl, \a FoundType if only type decls are found.
180static UnqualifiedTypeNameLookupResult
181lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
182 SourceLocation NameLoc,
183 const CXXRecordDecl *RD) {
184 if (!RD->hasDefinition())
185 return UnqualifiedTypeNameLookupResult::NotFound;
186 // Look for type decls in base classes.
187 UnqualifiedTypeNameLookupResult FoundTypeDecl =
188 UnqualifiedTypeNameLookupResult::NotFound;
189 for (const auto &Base : RD->bases()) {
190 const CXXRecordDecl *BaseRD = nullptr;
191 if (auto *BaseTT = Base.getType()->getAs<TagType>())
192 BaseRD = BaseTT->getAsCXXRecordDecl();
193 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
194 // Look for type decls in dependent base classes that have known primary
195 // templates.
196 if (!TST || !TST->isDependentType())
197 continue;
198 auto *TD = TST->getTemplateName().getAsTemplateDecl();
199 if (!TD)
200 continue;
201 if (auto *BasePrimaryTemplate =
202 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
203 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
204 BaseRD = BasePrimaryTemplate;
205 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
206 if (const ClassTemplatePartialSpecializationDecl *PS =
207 CTD->findPartialSpecialization(Base.getType()))
208 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
209 BaseRD = PS;
210 }
211 }
212 }
213 if (BaseRD) {
214 for (NamedDecl *ND : BaseRD->lookup(&II)) {
215 if (!isa<TypeDecl>(ND))
216 return UnqualifiedTypeNameLookupResult::FoundNonType;
217 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
218 }
219 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
220 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
221 case UnqualifiedTypeNameLookupResult::FoundNonType:
222 return UnqualifiedTypeNameLookupResult::FoundNonType;
223 case UnqualifiedTypeNameLookupResult::FoundType:
224 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
225 break;
226 case UnqualifiedTypeNameLookupResult::NotFound:
227 break;
228 }
229 }
230 }
231 }
232
233 return FoundTypeDecl;
234}
235
236static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
237 const IdentifierInfo &II,
238 SourceLocation NameLoc) {
239 // Lookup in the parent class template context, if any.
240 const CXXRecordDecl *RD = nullptr;
241 UnqualifiedTypeNameLookupResult FoundTypeDecl =
242 UnqualifiedTypeNameLookupResult::NotFound;
243 for (DeclContext *DC = S.CurContext;
244 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
245 DC = DC->getParent()) {
246 // Look for type decls in dependent base classes that have known primary
247 // templates.
248 RD = dyn_cast<CXXRecordDecl>(DC);
249 if (RD && RD->getDescribedClassTemplate())
250 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
251 }
252 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
253 return nullptr;
254
255 // We found some types in dependent base classes. Recover as if the user
256 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
257 // lookup during template instantiation.
258 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
259
260 ASTContext &Context = S.Context;
261 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
262 cast<Type>(Context.getRecordType(RD)));
263 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
264
265 CXXScopeSpec SS;
266 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
267
268 TypeLocBuilder Builder;
269 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
270 DepTL.setNameLoc(NameLoc);
271 DepTL.setElaboratedKeywordLoc(SourceLocation());
272 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
273 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
274}
275
276/// If the identifier refers to a type name within this scope,
277/// return the declaration of that type.
278///
279/// This routine performs ordinary name lookup of the identifier II
280/// within the given scope, with optional C++ scope specifier SS, to
281/// determine whether the name refers to a type. If so, returns an
282/// opaque pointer (actually a QualType) corresponding to that
283/// type. Otherwise, returns NULL.
284ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
285 Scope *S, CXXScopeSpec *SS,
286 bool isClassName, bool HasTrailingDot,
287 ParsedType ObjectTypePtr,
288 bool IsCtorOrDtorName,
289 bool WantNontrivialTypeSourceInfo,
290 bool IsClassTemplateDeductionContext,
291 IdentifierInfo **CorrectedII) {
292 // FIXME: Consider allowing this outside C++1z mode as an extension.
293 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
294 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
295 !isClassName && !HasTrailingDot;
296
297 // Determine where we will perform name lookup.
298 DeclContext *LookupCtx = nullptr;
299 if (ObjectTypePtr) {
300 QualType ObjectType = ObjectTypePtr.get();
301 if (ObjectType->isRecordType())
302 LookupCtx = computeDeclContext(ObjectType);
303 } else if (SS && SS->isNotEmpty()) {
304 LookupCtx = computeDeclContext(*SS, false);
305
306 if (!LookupCtx) {
307 if (isDependentScopeSpecifier(*SS)) {
308 // C++ [temp.res]p3:
309 // A qualified-id that refers to a type and in which the
310 // nested-name-specifier depends on a template-parameter (14.6.2)
311 // shall be prefixed by the keyword typename to indicate that the
312 // qualified-id denotes a type, forming an
313 // elaborated-type-specifier (7.1.5.3).
314 //
315 // We therefore do not perform any name lookup if the result would
316 // refer to a member of an unknown specialization.
317 if (!isClassName && !IsCtorOrDtorName)
318 return nullptr;
319
320 // We know from the grammar that this name refers to a type,
321 // so build a dependent node to describe the type.
322 if (WantNontrivialTypeSourceInfo)
323 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
324
325 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
326 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
327 II, NameLoc);
328 return ParsedType::make(T);
329 }
330
331 return nullptr;
332 }
333
334 if (!LookupCtx->isDependentContext() &&
335 RequireCompleteDeclContext(*SS, LookupCtx))
336 return nullptr;
337 }
338
339 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
340 // lookup for class-names.
341 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
342 LookupOrdinaryName;
343 LookupResult Result(*this, &II, NameLoc, Kind);
344 if (LookupCtx) {
345 // Perform "qualified" name lookup into the declaration context we
346 // computed, which is either the type of the base of a member access
347 // expression or the declaration context associated with a prior
348 // nested-name-specifier.
349 LookupQualifiedName(Result, LookupCtx);
350
351 if (ObjectTypePtr && Result.empty()) {
352 // C++ [basic.lookup.classref]p3:
353 // If the unqualified-id is ~type-name, the type-name is looked up
354 // in the context of the entire postfix-expression. If the type T of
355 // the object expression is of a class type C, the type-name is also
356 // looked up in the scope of class C. At least one of the lookups shall
357 // find a name that refers to (possibly cv-qualified) T.
358 LookupName(Result, S);
359 }
360 } else {
361 // Perform unqualified name lookup.
362 LookupName(Result, S);
363
364 // For unqualified lookup in a class template in MSVC mode, look into
365 // dependent base classes where the primary class template is known.
366 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
367 if (ParsedType TypeInBase =
368 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
369 return TypeInBase;
370 }
371 }
372
373 NamedDecl *IIDecl = nullptr;
374 switch (Result.getResultKind()) {
375 case LookupResult::NotFound:
376 case LookupResult::NotFoundInCurrentInstantiation:
377 if (CorrectedII) {
378 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
379 AllowDeducedTemplate);
380 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
381 S, SS, CCC, CTK_ErrorRecovery);
382 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
383 TemplateTy Template;
384 bool MemberOfUnknownSpecialization;
385 UnqualifiedId TemplateName;
386 TemplateName.setIdentifier(NewII, NameLoc);
387 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
388 CXXScopeSpec NewSS, *NewSSPtr = SS;
389 if (SS && NNS) {
390 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
391 NewSSPtr = &NewSS;
392 }
393 if (Correction && (NNS || NewII != &II) &&
394 // Ignore a correction to a template type as the to-be-corrected
395 // identifier is not a template (typo correction for template names
396 // is handled elsewhere).
397 !(getLangOpts().CPlusPlus && NewSSPtr &&
398 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
399 Template, MemberOfUnknownSpecialization))) {
400 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
401 isClassName, HasTrailingDot, ObjectTypePtr,
402 IsCtorOrDtorName,
403 WantNontrivialTypeSourceInfo,
404 IsClassTemplateDeductionContext);
405 if (Ty) {
406 diagnoseTypo(Correction,
407 PDiag(diag::err_unknown_type_or_class_name_suggest)
408 << Result.getLookupName() << isClassName);
409 if (SS && NNS)
410 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
411 *CorrectedII = NewII;
412 return Ty;
413 }
414 }
415 }
416 // If typo correction failed or was not performed, fall through
417 LLVM_FALLTHROUGH[[gnu::fallthrough]];
418 case LookupResult::FoundOverloaded:
419 case LookupResult::FoundUnresolvedValue:
420 Result.suppressDiagnostics();
421 return nullptr;
422
423 case LookupResult::Ambiguous:
424 // Recover from type-hiding ambiguities by hiding the type. We'll
425 // do the lookup again when looking for an object, and we can
426 // diagnose the error then. If we don't do this, then the error
427 // about hiding the type will be immediately followed by an error
428 // that only makes sense if the identifier was treated like a type.
429 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
430 Result.suppressDiagnostics();
431 return nullptr;
432 }
433
434 // Look to see if we have a type anywhere in the list of results.
435 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
436 Res != ResEnd; ++Res) {
437 NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
438 if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
439 RealRes) ||
440 (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
441 if (!IIDecl ||
442 // Make the selection of the recovery decl deterministic.
443 RealRes->getLocation() < IIDecl->getLocation())
444 IIDecl = RealRes;
445 }
446 }
447
448 if (!IIDecl) {
449 // None of the entities we found is a type, so there is no way
450 // to even assume that the result is a type. In this case, don't
451 // complain about the ambiguity. The parser will either try to
452 // perform this lookup again (e.g., as an object name), which
453 // will produce the ambiguity, or will complain that it expected
454 // a type name.
455 Result.suppressDiagnostics();
456 return nullptr;
457 }
458
459 // We found a type within the ambiguous lookup; diagnose the
460 // ambiguity and then return that type. This might be the right
461 // answer, or it might not be, but it suppresses any attempt to
462 // perform the name lookup again.
463 break;
464
465 case LookupResult::Found:
466 IIDecl = Result.getFoundDecl();
467 break;
468 }
469
470 assert(IIDecl && "Didn't find decl")(static_cast <bool> (IIDecl && "Didn't find decl"
) ? void (0) : __assert_fail ("IIDecl && \"Didn't find decl\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 470, __extension__ __PRETTY_FUNCTION__))
;
471
472 QualType T;
473 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
474 // C++ [class.qual]p2: A lookup that would find the injected-class-name
475 // instead names the constructors of the class, except when naming a class.
476 // This is ill-formed when we're not actually forming a ctor or dtor name.
477 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
478 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
479 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
480 FoundRD->isInjectedClassName() &&
481 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
482 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
483 << &II << /*Type*/1;
484
485 DiagnoseUseOfDecl(IIDecl, NameLoc);
486
487 T = Context.getTypeDeclType(TD);
488 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
489 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
490 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
491 if (!HasTrailingDot)
492 T = Context.getObjCInterfaceType(IDecl);
493 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
494 (void)DiagnoseUseOfDecl(UD, NameLoc);
495 // Recover with 'int'
496 T = Context.IntTy;
497 } else if (AllowDeducedTemplate) {
498 if (auto *TD = getAsTypeTemplateDecl(IIDecl))
499 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
500 QualType(), false);
501 }
502
503 if (T.isNull()) {
504 // If it's not plausibly a type, suppress diagnostics.
505 Result.suppressDiagnostics();
506 return nullptr;
507 }
508
509 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
510 // constructor or destructor name (in such a case, the scope specifier
511 // will be attached to the enclosing Expr or Decl node).
512 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
513 !isa<ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(IIDecl)) {
514 if (WantNontrivialTypeSourceInfo) {
515 // Construct a type with type-source information.
516 TypeLocBuilder Builder;
517 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
518
519 T = getElaboratedType(ETK_None, *SS, T);
520 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
521 ElabTL.setElaboratedKeywordLoc(SourceLocation());
522 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
523 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
524 } else {
525 T = getElaboratedType(ETK_None, *SS, T);
526 }
527 }
528
529 return ParsedType::make(T);
530}
531
532// Builds a fake NNS for the given decl context.
533static NestedNameSpecifier *
534synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
535 for (;; DC = DC->getLookupParent()) {
536 DC = DC->getPrimaryContext();
537 auto *ND = dyn_cast<NamespaceDecl>(DC);
538 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
539 return NestedNameSpecifier::Create(Context, nullptr, ND);
540 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
541 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
542 RD->getTypeForDecl());
543 else if (isa<TranslationUnitDecl>(DC))
544 return NestedNameSpecifier::GlobalSpecifier(Context);
545 }
546 llvm_unreachable("something isn't in TU scope?")::llvm::llvm_unreachable_internal("something isn't in TU scope?"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 546)
;
547}
548
549/// Find the parent class with dependent bases of the innermost enclosing method
550/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
551/// up allowing unqualified dependent type names at class-level, which MSVC
552/// correctly rejects.
553static const CXXRecordDecl *
554findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
555 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
556 DC = DC->getPrimaryContext();
557 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
558 if (MD->getParent()->hasAnyDependentBases())
559 return MD->getParent();
560 }
561 return nullptr;
562}
563
564ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
565 SourceLocation NameLoc,
566 bool IsTemplateTypeArg) {
567 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode")(static_cast <bool> (getLangOpts().MSVCCompat &&
"shouldn't be called in non-MSVC mode") ? void (0) : __assert_fail
("getLangOpts().MSVCCompat && \"shouldn't be called in non-MSVC mode\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 567, __extension__ __PRETTY_FUNCTION__))
;
568
569 NestedNameSpecifier *NNS = nullptr;
570 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
571 // If we weren't able to parse a default template argument, delay lookup
572 // until instantiation time by making a non-dependent DependentTypeName. We
573 // pretend we saw a NestedNameSpecifier referring to the current scope, and
574 // lookup is retried.
575 // FIXME: This hurts our diagnostic quality, since we get errors like "no
576 // type named 'Foo' in 'current_namespace'" when the user didn't write any
577 // name specifiers.
578 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
579 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
580 } else if (const CXXRecordDecl *RD =
581 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
582 // Build a DependentNameType that will perform lookup into RD at
583 // instantiation time.
584 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
585 RD->getTypeForDecl());
586
587 // Diagnose that this identifier was undeclared, and retry the lookup during
588 // template instantiation.
589 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
590 << RD;
591 } else {
592 // This is not a situation that we should recover from.
593 return ParsedType();
594 }
595
596 QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
597
598 // Build type location information. We synthesized the qualifier, so we have
599 // to build a fake NestedNameSpecifierLoc.
600 NestedNameSpecifierLocBuilder NNSLocBuilder;
601 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
602 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
603
604 TypeLocBuilder Builder;
605 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
606 DepTL.setNameLoc(NameLoc);
607 DepTL.setElaboratedKeywordLoc(SourceLocation());
608 DepTL.setQualifierLoc(QualifierLoc);
609 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
610}
611
612/// isTagName() - This method is called *for error recovery purposes only*
613/// to determine if the specified name is a valid tag name ("struct foo"). If
614/// so, this returns the TST for the tag corresponding to it (TST_enum,
615/// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
616/// cases in C where the user forgot to specify the tag.
617DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
618 // Do a tag name lookup in this scope.
619 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
620 LookupName(R, S, false);
621 R.suppressDiagnostics();
622 if (R.getResultKind() == LookupResult::Found)
623 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
624 switch (TD->getTagKind()) {
625 case TTK_Struct: return DeclSpec::TST_struct;
626 case TTK_Interface: return DeclSpec::TST_interface;
627 case TTK_Union: return DeclSpec::TST_union;
628 case TTK_Class: return DeclSpec::TST_class;
629 case TTK_Enum: return DeclSpec::TST_enum;
630 }
631 }
632
633 return DeclSpec::TST_unspecified;
634}
635
636/// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
637/// if a CXXScopeSpec's type is equal to the type of one of the base classes
638/// then downgrade the missing typename error to a warning.
639/// This is needed for MSVC compatibility; Example:
640/// @code
641/// template<class T> class A {
642/// public:
643/// typedef int TYPE;
644/// };
645/// template<class T> class B : public A<T> {
646/// public:
647/// A<T>::TYPE a; // no typename required because A<T> is a base class.
648/// };
649/// @endcode
650bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
651 if (CurContext->isRecord()) {
652 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
653 return true;
654
655 const Type *Ty = SS->getScopeRep()->getAsType();
656
657 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
658 for (const auto &Base : RD->bases())
659 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
660 return true;
661 return S->isFunctionPrototypeScope();
662 }
663 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
664}
665
666void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
667 SourceLocation IILoc,
668 Scope *S,
669 CXXScopeSpec *SS,
670 ParsedType &SuggestedType,
671 bool IsTemplateName) {
672 // Don't report typename errors for editor placeholders.
673 if (II->isEditorPlaceholder())
674 return;
675 // We don't have anything to suggest (yet).
676 SuggestedType = nullptr;
677
678 // There may have been a typo in the name of the type. Look up typo
679 // results, in case we have something that we can suggest.
680 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
681 /*AllowTemplates=*/IsTemplateName,
682 /*AllowNonTemplates=*/!IsTemplateName);
683 if (TypoCorrection Corrected =
684 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
685 CCC, CTK_ErrorRecovery)) {
686 // FIXME: Support error recovery for the template-name case.
687 bool CanRecover = !IsTemplateName;
688 if (Corrected.isKeyword()) {
689 // We corrected to a keyword.
690 diagnoseTypo(Corrected,
691 PDiag(IsTemplateName ? diag::err_no_template_suggest
692 : diag::err_unknown_typename_suggest)
693 << II);
694 II = Corrected.getCorrectionAsIdentifierInfo();
695 } else {
696 // We found a similarly-named type or interface; suggest that.
697 if (!SS || !SS->isSet()) {
698 diagnoseTypo(Corrected,
699 PDiag(IsTemplateName ? diag::err_no_template_suggest
700 : diag::err_unknown_typename_suggest)
701 << II, CanRecover);
702 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
703 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
704 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
705 II->getName().equals(CorrectedStr);
706 diagnoseTypo(Corrected,
707 PDiag(IsTemplateName
708 ? diag::err_no_member_template_suggest
709 : diag::err_unknown_nested_typename_suggest)
710 << II << DC << DroppedSpecifier << SS->getRange(),
711 CanRecover);
712 } else {
713 llvm_unreachable("could not have corrected a typo here")::llvm::llvm_unreachable_internal("could not have corrected a typo here"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 713)
;
714 }
715
716 if (!CanRecover)
717 return;
718
719 CXXScopeSpec tmpSS;
720 if (Corrected.getCorrectionSpecifier())
721 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
722 SourceRange(IILoc));
723 // FIXME: Support class template argument deduction here.
724 SuggestedType =
725 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
726 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
727 /*IsCtorOrDtorName=*/false,
728 /*WantNontrivialTypeSourceInfo=*/true);
729 }
730 return;
731 }
732
733 if (getLangOpts().CPlusPlus && !IsTemplateName) {
734 // See if II is a class template that the user forgot to pass arguments to.
735 UnqualifiedId Name;
736 Name.setIdentifier(II, IILoc);
737 CXXScopeSpec EmptySS;
738 TemplateTy TemplateResult;
739 bool MemberOfUnknownSpecialization;
740 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
741 Name, nullptr, true, TemplateResult,
742 MemberOfUnknownSpecialization) == TNK_Type_template) {
743 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
744 return;
745 }
746 }
747
748 // FIXME: Should we move the logic that tries to recover from a missing tag
749 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
750
751 if (!SS || (!SS->isSet() && !SS->isInvalid()))
752 Diag(IILoc, IsTemplateName ? diag::err_no_template
753 : diag::err_unknown_typename)
754 << II;
755 else if (DeclContext *DC = computeDeclContext(*SS, false))
756 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
757 : diag::err_typename_nested_not_found)
758 << II << DC << SS->getRange();
759 else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
760 SuggestedType =
761 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
762 } else if (isDependentScopeSpecifier(*SS)) {
763 unsigned DiagID = diag::err_typename_missing;
764 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
765 DiagID = diag::ext_typename_missing;
766
767 Diag(SS->getRange().getBegin(), DiagID)
768 << SS->getScopeRep() << II->getName()
769 << SourceRange(SS->getRange().getBegin(), IILoc)
770 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
771 SuggestedType = ActOnTypenameType(S, SourceLocation(),
772 *SS, *II, IILoc).get();
773 } else {
774 assert(SS && SS->isInvalid() &&(static_cast <bool> (SS && SS->isInvalid() &&
"Invalid scope specifier has already been diagnosed") ? void
(0) : __assert_fail ("SS && SS->isInvalid() && \"Invalid scope specifier has already been diagnosed\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 775, __extension__ __PRETTY_FUNCTION__))
775 "Invalid scope specifier has already been diagnosed")(static_cast <bool> (SS && SS->isInvalid() &&
"Invalid scope specifier has already been diagnosed") ? void
(0) : __assert_fail ("SS && SS->isInvalid() && \"Invalid scope specifier has already been diagnosed\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 775, __extension__ __PRETTY_FUNCTION__))
;
776 }
777}
778
779/// Determine whether the given result set contains either a type name
780/// or
781static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
782 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
783 NextToken.is(tok::less);
784
785 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
786 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
787 return true;
788
789 if (CheckTemplate && isa<TemplateDecl>(*I))
790 return true;
791 }
792
793 return false;
794}
795
796static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
797 Scope *S, CXXScopeSpec &SS,
798 IdentifierInfo *&Name,
799 SourceLocation NameLoc) {
800 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
801 SemaRef.LookupParsedName(R, S, &SS);
802 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
803 StringRef FixItTagName;
804 switch (Tag->getTagKind()) {
805 case TTK_Class:
806 FixItTagName = "class ";
807 break;
808
809 case TTK_Enum:
810 FixItTagName = "enum ";
811 break;
812
813 case TTK_Struct:
814 FixItTagName = "struct ";
815 break;
816
817 case TTK_Interface:
818 FixItTagName = "__interface ";
819 break;
820
821 case TTK_Union:
822 FixItTagName = "union ";
823 break;
824 }
825
826 StringRef TagName = FixItTagName.drop_back();
827 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
828 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
829 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
830
831 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
832 I != IEnd; ++I)
833 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
834 << Name << TagName;
835
836 // Replace lookup results with just the tag decl.
837 Result.clear(Sema::LookupTagName);
838 SemaRef.LookupParsedName(Result, S, &SS);
839 return true;
840 }
841
842 return false;
843}
844
845/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
846static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
847 QualType T, SourceLocation NameLoc) {
848 ASTContext &Context = S.Context;
849
850 TypeLocBuilder Builder;
851 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
852
853 T = S.getElaboratedType(ETK_None, SS, T);
854 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
855 ElabTL.setElaboratedKeywordLoc(SourceLocation());
856 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
857 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
858}
859
860Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
861 IdentifierInfo *&Name,
862 SourceLocation NameLoc,
863 const Token &NextToken,
864 CorrectionCandidateCallback *CCC) {
865 DeclarationNameInfo NameInfo(Name, NameLoc);
866 ObjCMethodDecl *CurMethod = getCurMethodDecl();
867
868 assert(NextToken.isNot(tok::coloncolon) &&(static_cast <bool> (NextToken.isNot(tok::coloncolon) &&
"parse nested name specifiers before calling ClassifyName") ?
void (0) : __assert_fail ("NextToken.isNot(tok::coloncolon) && \"parse nested name specifiers before calling ClassifyName\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 869, __extension__ __PRETTY_FUNCTION__))
869 "parse nested name specifiers before calling ClassifyName")(static_cast <bool> (NextToken.isNot(tok::coloncolon) &&
"parse nested name specifiers before calling ClassifyName") ?
void (0) : __assert_fail ("NextToken.isNot(tok::coloncolon) && \"parse nested name specifiers before calling ClassifyName\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 869, __extension__ __PRETTY_FUNCTION__))
;
870 if (getLangOpts().CPlusPlus && SS.isSet() &&
871 isCurrentClassName(*Name, S, &SS)) {
872 // Per [class.qual]p2, this names the constructors of SS, not the
873 // injected-class-name. We don't have a classification for that.
874 // There's not much point caching this result, since the parser
875 // will reject it later.
876 return NameClassification::Unknown();
877 }
878
879 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
880 LookupParsedName(Result, S, &SS, !CurMethod);
881
882 if (SS.isInvalid())
883 return NameClassification::Error();
884
885 // For unqualified lookup in a class template in MSVC mode, look into
886 // dependent base classes where the primary class template is known.
887 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
888 if (ParsedType TypeInBase =
889 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
890 return TypeInBase;
891 }
892
893 // Perform lookup for Objective-C instance variables (including automatically
894 // synthesized instance variables), if we're in an Objective-C method.
895 // FIXME: This lookup really, really needs to be folded in to the normal
896 // unqualified lookup mechanism.
897 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
898 DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
899 if (Ivar.isInvalid())
900 return NameClassification::Error();
901 if (Ivar.isUsable())
902 return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
903
904 // We defer builtin creation until after ivar lookup inside ObjC methods.
905 if (Result.empty())
906 LookupBuiltin(Result);
907 }
908
909 bool SecondTry = false;
910 bool IsFilteredTemplateName = false;
911
912Corrected:
913 switch (Result.getResultKind()) {
914 case LookupResult::NotFound:
915 // If an unqualified-id is followed by a '(', then we have a function
916 // call.
917 if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
918 // In C++, this is an ADL-only call.
919 // FIXME: Reference?
920 if (getLangOpts().CPlusPlus)
921 return NameClassification::UndeclaredNonType();
922
923 // C90 6.3.2.2:
924 // If the expression that precedes the parenthesized argument list in a
925 // function call consists solely of an identifier, and if no
926 // declaration is visible for this identifier, the identifier is
927 // implicitly declared exactly as if, in the innermost block containing
928 // the function call, the declaration
929 //
930 // extern int identifier ();
931 //
932 // appeared.
933 //
934 // We also allow this in C99 as an extension.
935 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
936 return NameClassification::NonType(D);
937 }
938
939 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
940 // In C++20 onwards, this could be an ADL-only call to a function
941 // template, and we're required to assume that this is a template name.
942 //
943 // FIXME: Find a way to still do typo correction in this case.
944 TemplateName Template =
945 Context.getAssumedTemplateName(NameInfo.getName());
946 return NameClassification::UndeclaredTemplate(Template);
947 }
948
949 // In C, we first see whether there is a tag type by the same name, in
950 // which case it's likely that the user just forgot to write "enum",
951 // "struct", or "union".
952 if (!getLangOpts().CPlusPlus && !SecondTry &&
953 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
954 break;
955 }
956
957 // Perform typo correction to determine if there is another name that is
958 // close to this name.
959 if (!SecondTry && CCC) {
960 SecondTry = true;
961 if (TypoCorrection Corrected =
962 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
963 &SS, *CCC, CTK_ErrorRecovery)) {
964 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
965 unsigned QualifiedDiag = diag::err_no_member_suggest;
966
967 NamedDecl *FirstDecl = Corrected.getFoundDecl();
968 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
969 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
970 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
971 UnqualifiedDiag = diag::err_no_template_suggest;
972 QualifiedDiag = diag::err_no_member_template_suggest;
973 } else if (UnderlyingFirstDecl &&
974 (isa<TypeDecl>(UnderlyingFirstDecl) ||
975 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
976 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
977 UnqualifiedDiag = diag::err_unknown_typename_suggest;
978 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
979 }
980
981 if (SS.isEmpty()) {
982 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
983 } else {// FIXME: is this even reachable? Test it.
984 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
985 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
986 Name->getName().equals(CorrectedStr);
987 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
988 << Name << computeDeclContext(SS, false)
989 << DroppedSpecifier << SS.getRange());
990 }
991
992 // Update the name, so that the caller has the new name.
993 Name = Corrected.getCorrectionAsIdentifierInfo();
994
995 // Typo correction corrected to a keyword.
996 if (Corrected.isKeyword())
997 return Name;
998
999 // Also update the LookupResult...
1000 // FIXME: This should probably go away at some point
1001 Result.clear();
1002 Result.setLookupName(Corrected.getCorrection());
1003 if (FirstDecl)
1004 Result.addDecl(FirstDecl);
1005
1006 // If we found an Objective-C instance variable, let
1007 // LookupInObjCMethod build the appropriate expression to
1008 // reference the ivar.
1009 // FIXME: This is a gross hack.
1010 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1011 DeclResult R =
1012 LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1013 if (R.isInvalid())
1014 return NameClassification::Error();
1015 if (R.isUsable())
1016 return NameClassification::NonType(Ivar);
1017 }
1018
1019 goto Corrected;
1020 }
1021 }
1022
1023 // We failed to correct; just fall through and let the parser deal with it.
1024 Result.suppressDiagnostics();
1025 return NameClassification::Unknown();
1026
1027 case LookupResult::NotFoundInCurrentInstantiation: {
1028 // We performed name lookup into the current instantiation, and there were
1029 // dependent bases, so we treat this result the same way as any other
1030 // dependent nested-name-specifier.
1031
1032 // C++ [temp.res]p2:
1033 // A name used in a template declaration or definition and that is
1034 // dependent on a template-parameter is assumed not to name a type
1035 // unless the applicable name lookup finds a type name or the name is
1036 // qualified by the keyword typename.
1037 //
1038 // FIXME: If the next token is '<', we might want to ask the parser to
1039 // perform some heroics to see if we actually have a
1040 // template-argument-list, which would indicate a missing 'template'
1041 // keyword here.
1042 return NameClassification::DependentNonType();
1043 }
1044
1045 case LookupResult::Found:
1046 case LookupResult::FoundOverloaded:
1047 case LookupResult::FoundUnresolvedValue:
1048 break;
1049
1050 case LookupResult::Ambiguous:
1051 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1052 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1053 /*AllowDependent=*/false)) {
1054 // C++ [temp.local]p3:
1055 // A lookup that finds an injected-class-name (10.2) can result in an
1056 // ambiguity in certain cases (for example, if it is found in more than
1057 // one base class). If all of the injected-class-names that are found
1058 // refer to specializations of the same class template, and if the name
1059 // is followed by a template-argument-list, the reference refers to the
1060 // class template itself and not a specialization thereof, and is not
1061 // ambiguous.
1062 //
1063 // This filtering can make an ambiguous result into an unambiguous one,
1064 // so try again after filtering out template names.
1065 FilterAcceptableTemplateNames(Result);
1066 if (!Result.isAmbiguous()) {
1067 IsFilteredTemplateName = true;
1068 break;
1069 }
1070 }
1071
1072 // Diagnose the ambiguity and return an error.
1073 return NameClassification::Error();
1074 }
1075
1076 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1077 (IsFilteredTemplateName ||
1078 hasAnyAcceptableTemplateNames(
1079 Result, /*AllowFunctionTemplates=*/true,
1080 /*AllowDependent=*/false,
1081 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1082 getLangOpts().CPlusPlus20))) {
1083 // C++ [temp.names]p3:
1084 // After name lookup (3.4) finds that a name is a template-name or that
1085 // an operator-function-id or a literal- operator-id refers to a set of
1086 // overloaded functions any member of which is a function template if
1087 // this is followed by a <, the < is always taken as the delimiter of a
1088 // template-argument-list and never as the less-than operator.
1089 // C++2a [temp.names]p2:
1090 // A name is also considered to refer to a template if it is an
1091 // unqualified-id followed by a < and name lookup finds either one
1092 // or more functions or finds nothing.
1093 if (!IsFilteredTemplateName)
1094 FilterAcceptableTemplateNames(Result);
1095
1096 bool IsFunctionTemplate;
1097 bool IsVarTemplate;
1098 TemplateName Template;
1099 if (Result.end() - Result.begin() > 1) {
1100 IsFunctionTemplate = true;
1101 Template = Context.getOverloadedTemplateName(Result.begin(),
1102 Result.end());
1103 } else if (!Result.empty()) {
1104 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1105 *Result.begin(), /*AllowFunctionTemplates=*/true,
1106 /*AllowDependent=*/false));
1107 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1108 IsVarTemplate = isa<VarTemplateDecl>(TD);
1109
1110 if (SS.isNotEmpty())
1111 Template =
1112 Context.getQualifiedTemplateName(SS.getScopeRep(),
1113 /*TemplateKeyword=*/false, TD);
1114 else
1115 Template = TemplateName(TD);
1116 } else {
1117 // All results were non-template functions. This is a function template
1118 // name.
1119 IsFunctionTemplate = true;
1120 Template = Context.getAssumedTemplateName(NameInfo.getName());
1121 }
1122
1123 if (IsFunctionTemplate) {
1124 // Function templates always go through overload resolution, at which
1125 // point we'll perform the various checks (e.g., accessibility) we need
1126 // to based on which function we selected.
1127 Result.suppressDiagnostics();
1128
1129 return NameClassification::FunctionTemplate(Template);
1130 }
1131
1132 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1133 : NameClassification::TypeTemplate(Template);
1134 }
1135
1136 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1137 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1138 DiagnoseUseOfDecl(Type, NameLoc);
1139 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1140 QualType T = Context.getTypeDeclType(Type);
1141 if (SS.isNotEmpty())
1142 return buildNestedType(*this, SS, T, NameLoc);
1143 return ParsedType::make(T);
1144 }
1145
1146 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1147 if (!Class) {
1148 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1149 if (ObjCCompatibleAliasDecl *Alias =
1150 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1151 Class = Alias->getClassInterface();
1152 }
1153
1154 if (Class) {
1155 DiagnoseUseOfDecl(Class, NameLoc);
1156
1157 if (NextToken.is(tok::period)) {
1158 // Interface. <something> is parsed as a property reference expression.
1159 // Just return "unknown" as a fall-through for now.
1160 Result.suppressDiagnostics();
1161 return NameClassification::Unknown();
1162 }
1163
1164 QualType T = Context.getObjCInterfaceType(Class);
1165 return ParsedType::make(T);
1166 }
1167
1168 if (isa<ConceptDecl>(FirstDecl))
1169 return NameClassification::Concept(
1170 TemplateName(cast<TemplateDecl>(FirstDecl)));
1171
1172 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1173 (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1174 return NameClassification::Error();
1175 }
1176
1177 // We can have a type template here if we're classifying a template argument.
1178 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1179 !isa<VarTemplateDecl>(FirstDecl))
1180 return NameClassification::TypeTemplate(
1181 TemplateName(cast<TemplateDecl>(FirstDecl)));
1182
1183 // Check for a tag type hidden by a non-type decl in a few cases where it
1184 // seems likely a type is wanted instead of the non-type that was found.
1185 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1186 if ((NextToken.is(tok::identifier) ||
1187 (NextIsOp &&
1188 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1189 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1190 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1191 DiagnoseUseOfDecl(Type, NameLoc);
1192 QualType T = Context.getTypeDeclType(Type);
1193 if (SS.isNotEmpty())
1194 return buildNestedType(*this, SS, T, NameLoc);
1195 return ParsedType::make(T);
1196 }
1197
1198 // If we already know which single declaration is referenced, just annotate
1199 // that declaration directly. Defer resolving even non-overloaded class
1200 // member accesses, as we need to defer certain access checks until we know
1201 // the context.
1202 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1203 if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember())
1204 return NameClassification::NonType(Result.getRepresentativeDecl());
1205
1206 // Otherwise, this is an overload set that we will need to resolve later.
1207 Result.suppressDiagnostics();
1208 return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1209 Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1210 Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
1211 Result.begin(), Result.end()));
1212}
1213
1214ExprResult
1215Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1216 SourceLocation NameLoc) {
1217 assert(getLangOpts().CPlusPlus && "ADL-only call in C?")(static_cast <bool> (getLangOpts().CPlusPlus &&
"ADL-only call in C?") ? void (0) : __assert_fail ("getLangOpts().CPlusPlus && \"ADL-only call in C?\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 1217, __extension__ __PRETTY_FUNCTION__))
;
1218 CXXScopeSpec SS;
1219 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1220 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1221}
1222
1223ExprResult
1224Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1225 IdentifierInfo *Name,
1226 SourceLocation NameLoc,
1227 bool IsAddressOfOperand) {
1228 DeclarationNameInfo NameInfo(Name, NameLoc);
1229 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1230 NameInfo, IsAddressOfOperand,
1231 /*TemplateArgs=*/nullptr);
1232}
1233
1234ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1235 NamedDecl *Found,
1236 SourceLocation NameLoc,
1237 const Token &NextToken) {
1238 if (getCurMethodDecl() && SS.isEmpty())
1239 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1240 return BuildIvarRefExpr(S, NameLoc, Ivar);
1241
1242 // Reconstruct the lookup result.
1243 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1244 Result.addDecl(Found);
1245 Result.resolveKind();
1246
1247 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1248 return BuildDeclarationNameExpr(SS, Result, ADL);
1249}
1250
1251ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1252 // For an implicit class member access, transform the result into a member
1253 // access expression if necessary.
1254 auto *ULE = cast<UnresolvedLookupExpr>(E);
1255 if ((*ULE->decls_begin())->isCXXClassMember()) {
1256 CXXScopeSpec SS;
1257 SS.Adopt(ULE->getQualifierLoc());
1258
1259 // Reconstruct the lookup result.
1260 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1261 LookupOrdinaryName);
1262 Result.setNamingClass(ULE->getNamingClass());
1263 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1264 Result.addDecl(*I, I.getAccess());
1265 Result.resolveKind();
1266 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1267 nullptr, S);
1268 }
1269
1270 // Otherwise, this is already in the form we needed, and no further checks
1271 // are necessary.
1272 return ULE;
1273}
1274
1275Sema::TemplateNameKindForDiagnostics
1276Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1277 auto *TD = Name.getAsTemplateDecl();
1278 if (!TD)
1279 return TemplateNameKindForDiagnostics::DependentTemplate;
1280 if (isa<ClassTemplateDecl>(TD))
1281 return TemplateNameKindForDiagnostics::ClassTemplate;
1282 if (isa<FunctionTemplateDecl>(TD))
1283 return TemplateNameKindForDiagnostics::FunctionTemplate;
1284 if (isa<VarTemplateDecl>(TD))
1285 return TemplateNameKindForDiagnostics::VarTemplate;
1286 if (isa<TypeAliasTemplateDecl>(TD))
1287 return TemplateNameKindForDiagnostics::AliasTemplate;
1288 if (isa<TemplateTemplateParmDecl>(TD))
1289 return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1290 if (isa<ConceptDecl>(TD))
1291 return TemplateNameKindForDiagnostics::Concept;
1292 return TemplateNameKindForDiagnostics::DependentTemplate;
1293}
1294
1295void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1296 assert(DC->getLexicalParent() == CurContext &&(static_cast <bool> (DC->getLexicalParent() == CurContext
&& "The next DeclContext should be lexically contained in the current one."
) ? void (0) : __assert_fail ("DC->getLexicalParent() == CurContext && \"The next DeclContext should be lexically contained in the current one.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 1297, __extension__ __PRETTY_FUNCTION__))
1297 "The next DeclContext should be lexically contained in the current one.")(static_cast <bool> (DC->getLexicalParent() == CurContext
&& "The next DeclContext should be lexically contained in the current one."
) ? void (0) : __assert_fail ("DC->getLexicalParent() == CurContext && \"The next DeclContext should be lexically contained in the current one.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 1297, __extension__ __PRETTY_FUNCTION__))
;
1298 CurContext = DC;
1299 S->setEntity(DC);
1300}
1301
1302void Sema::PopDeclContext() {
1303 assert(CurContext && "DeclContext imbalance!")(static_cast <bool> (CurContext && "DeclContext imbalance!"
) ? void (0) : __assert_fail ("CurContext && \"DeclContext imbalance!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 1303, __extension__ __PRETTY_FUNCTION__))
;
1304
1305 CurContext = CurContext->getLexicalParent();
1306 assert(CurContext && "Popped translation unit!")(static_cast <bool> (CurContext && "Popped translation unit!"
) ? void (0) : __assert_fail ("CurContext && \"Popped translation unit!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 1306, __extension__ __PRETTY_FUNCTION__))
;
1307}
1308
1309Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1310 Decl *D) {
1311 // Unlike PushDeclContext, the context to which we return is not necessarily
1312 // the containing DC of TD, because the new context will be some pre-existing
1313 // TagDecl definition instead of a fresh one.
1314 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1315 CurContext = cast<TagDecl>(D)->getDefinition();
1316 assert(CurContext && "skipping definition of undefined tag")(static_cast <bool> (CurContext && "skipping definition of undefined tag"
) ? void (0) : __assert_fail ("CurContext && \"skipping definition of undefined tag\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 1316, __extension__ __PRETTY_FUNCTION__))
;
1317 // Start lookups from the parent of the current context; we don't want to look
1318 // into the pre-existing complete definition.
1319 S->setEntity(CurContext->getLookupParent());
1320 return Result;
1321}
1322
1323void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1324 CurContext = static_cast<decltype(CurContext)>(Context);
1325}
1326
1327/// EnterDeclaratorContext - Used when we must lookup names in the context
1328/// of a declarator's nested name specifier.
1329///
1330void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1331 // C++0x [basic.lookup.unqual]p13:
1332 // A name used in the definition of a static data member of class
1333 // X (after the qualified-id of the static member) is looked up as
1334 // if the name was used in a member function of X.
1335 // C++0x [basic.lookup.unqual]p14:
1336 // If a variable member of a namespace is defined outside of the
1337 // scope of its namespace then any name used in the definition of
1338 // the variable member (after the declarator-id) is looked up as
1339 // if the definition of the variable member occurred in its
1340 // namespace.
1341 // Both of these imply that we should push a scope whose context
1342 // is the semantic context of the declaration. We can't use
1343 // PushDeclContext here because that context is not necessarily
1344 // lexically contained in the current context. Fortunately,
1345 // the containing scope should have the appropriate information.
1346
1347 assert(!S->getEntity() && "scope already has entity")(static_cast <bool> (!S->getEntity() && "scope already has entity"
) ? void (0) : __assert_fail ("!S->getEntity() && \"scope already has entity\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 1347, __extension__ __PRETTY_FUNCTION__))
;
1348
1349#ifndef NDEBUG
1350 Scope *Ancestor = S->getParent();
1351 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1352 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch")(static_cast <bool> (Ancestor->getEntity() == CurContext
&& "ancestor context mismatch") ? void (0) : __assert_fail
("Ancestor->getEntity() == CurContext && \"ancestor context mismatch\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 1352, __extension__ __PRETTY_FUNCTION__))
;
1353#endif
1354
1355 CurContext = DC;
1356 S->setEntity(DC);
1357
1358 if (S->getParent()->isTemplateParamScope()) {
1359 // Also set the corresponding entities for all immediately-enclosing
1360 // template parameter scopes.
1361 EnterTemplatedContext(S->getParent(), DC);
1362 }
1363}
1364
1365void Sema::ExitDeclaratorContext(Scope *S) {
1366 assert(S->getEntity() == CurContext && "Context imbalance!")(static_cast <bool> (S->getEntity() == CurContext &&
"Context imbalance!") ? void (0) : __assert_fail ("S->getEntity() == CurContext && \"Context imbalance!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 1366, __extension__ __PRETTY_FUNCTION__))
;
1367
1368 // Switch back to the lexical context. The safety of this is
1369 // enforced by an assert in EnterDeclaratorContext.
1370 Scope *Ancestor = S->getParent();
1371 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1372 CurContext = Ancestor->getEntity();
1373
1374 // We don't need to do anything with the scope, which is going to
1375 // disappear.
1376}
1377
1378void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1379 assert(S->isTemplateParamScope() &&(static_cast <bool> (S->isTemplateParamScope() &&
"expected to be initializing a template parameter scope") ? void
(0) : __assert_fail ("S->isTemplateParamScope() && \"expected to be initializing a template parameter scope\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 1380, __extension__ __PRETTY_FUNCTION__))
1380 "expected to be initializing a template parameter scope")(static_cast <bool> (S->isTemplateParamScope() &&
"expected to be initializing a template parameter scope") ? void
(0) : __assert_fail ("S->isTemplateParamScope() && \"expected to be initializing a template parameter scope\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 1380, __extension__ __PRETTY_FUNCTION__))
;
1381
1382 // C++20 [temp.local]p7:
1383 // In the definition of a member of a class template that appears outside
1384 // of the class template definition, the name of a member of the class
1385 // template hides the name of a template-parameter of any enclosing class
1386 // templates (but not a template-parameter of the member if the member is a
1387 // class or function template).
1388 // C++20 [temp.local]p9:
1389 // In the definition of a class template or in the definition of a member
1390 // of such a template that appears outside of the template definition, for
1391 // each non-dependent base class (13.8.2.1), if the name of the base class
1392 // or the name of a member of the base class is the same as the name of a
1393 // template-parameter, the base class name or member name hides the
1394 // template-parameter name (6.4.10).
1395 //
1396 // This means that a template parameter scope should be searched immediately
1397 // after searching the DeclContext for which it is a template parameter
1398 // scope. For example, for
1399 // template<typename T> template<typename U> template<typename V>
1400 // void N::A<T>::B<U>::f(...)
1401 // we search V then B<U> (and base classes) then U then A<T> (and base
1402 // classes) then T then N then ::.
1403 unsigned ScopeDepth = getTemplateDepth(S);
1404 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1405 DeclContext *SearchDCAfterScope = DC;
1406 for (; DC; DC = DC->getLookupParent()) {
1407 if (const TemplateParameterList *TPL =
1408 cast<Decl>(DC)->getDescribedTemplateParams()) {
1409 unsigned DCDepth = TPL->getDepth() + 1;
1410 if (DCDepth > ScopeDepth)
1411 continue;
1412 if (ScopeDepth == DCDepth)
1413 SearchDCAfterScope = DC = DC->getLookupParent();
1414 break;
1415 }
1416 }
1417 S->setLookupEntity(SearchDCAfterScope);
1418 }
1419}
1420
1421void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1422 // We assume that the caller has already called
1423 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1424 FunctionDecl *FD = D->getAsFunction();
1425 if (!FD)
1426 return;
1427
1428 // Same implementation as PushDeclContext, but enters the context
1429 // from the lexical parent, rather than the top-level class.
1430 assert(CurContext == FD->getLexicalParent() &&(static_cast <bool> (CurContext == FD->getLexicalParent
() && "The next DeclContext should be lexically contained in the current one."
) ? void (0) : __assert_fail ("CurContext == FD->getLexicalParent() && \"The next DeclContext should be lexically contained in the current one.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 1431, __extension__ __PRETTY_FUNCTION__))
1431 "The next DeclContext should be lexically contained in the current one.")(static_cast <bool> (CurContext == FD->getLexicalParent
() && "The next DeclContext should be lexically contained in the current one."
) ? void (0) : __assert_fail ("CurContext == FD->getLexicalParent() && \"The next DeclContext should be lexically contained in the current one.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 1431, __extension__ __PRETTY_FUNCTION__))
;
1432 CurContext = FD;
1433 S->setEntity(CurContext);
1434
1435 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1436 ParmVarDecl *Param = FD->getParamDecl(P);
1437 // If the parameter has an identifier, then add it to the scope
1438 if (Param->getIdentifier()) {
1439 S->AddDecl(Param);
1440 IdResolver.AddDecl(Param);
1441 }
1442 }
1443}
1444
1445void Sema::ActOnExitFunctionContext() {
1446 // Same implementation as PopDeclContext, but returns to the lexical parent,
1447 // rather than the top-level class.
1448 assert(CurContext && "DeclContext imbalance!")(static_cast <bool> (CurContext && "DeclContext imbalance!"
) ? void (0) : __assert_fail ("CurContext && \"DeclContext imbalance!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 1448, __extension__ __PRETTY_FUNCTION__))
;
1449 CurContext = CurContext->getLexicalParent();
1450 assert(CurContext && "Popped translation unit!")(static_cast <bool> (CurContext && "Popped translation unit!"
) ? void (0) : __assert_fail ("CurContext && \"Popped translation unit!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 1450, __extension__ __PRETTY_FUNCTION__))
;
1451}
1452
1453/// Determine whether we allow overloading of the function
1454/// PrevDecl with another declaration.
1455///
1456/// This routine determines whether overloading is possible, not
1457/// whether some new function is actually an overload. It will return
1458/// true in C++ (where we can always provide overloads) or, as an
1459/// extension, in C when the previous function is already an
1460/// overloaded function declaration or has the "overloadable"
1461/// attribute.
1462static bool AllowOverloadingOfFunction(LookupResult &Previous,
1463 ASTContext &Context,
1464 const FunctionDecl *New) {
1465 if (Context.getLangOpts().CPlusPlus)
1466 return true;
1467
1468 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1469 return true;
1470
1471 return Previous.getResultKind() == LookupResult::Found &&
1472 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1473 New->hasAttr<OverloadableAttr>());
1474}
1475
1476/// Add this decl to the scope shadowed decl chains.
1477void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1478 // Move up the scope chain until we find the nearest enclosing
1479 // non-transparent context. The declaration will be introduced into this
1480 // scope.
1481 while (S->getEntity() && S->getEntity()->isTransparentContext())
1482 S = S->getParent();
1483
1484 // Add scoped declarations into their context, so that they can be
1485 // found later. Declarations without a context won't be inserted
1486 // into any context.
1487 if (AddToContext)
1488 CurContext->addDecl(D);
1489
1490 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1491 // are function-local declarations.
1492 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1493 return;
1494
1495 // Template instantiations should also not be pushed into scope.
1496 if (isa<FunctionDecl>(D) &&
1497 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1498 return;
1499
1500 // If this replaces anything in the current scope,
1501 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1502 IEnd = IdResolver.end();
1503 for (; I != IEnd; ++I) {
1504 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1505 S->RemoveDecl(*I);
1506 IdResolver.RemoveDecl(*I);
1507
1508 // Should only need to replace one decl.
1509 break;
1510 }
1511 }
1512
1513 S->AddDecl(D);
1514
1515 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1516 // Implicitly-generated labels may end up getting generated in an order that
1517 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1518 // the label at the appropriate place in the identifier chain.
1519 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1520 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1521 if (IDC == CurContext) {
1522 if (!S->isDeclScope(*I))
1523 continue;
1524 } else if (IDC->Encloses(CurContext))
1525 break;
1526 }
1527
1528 IdResolver.InsertDeclAfter(I, D);
1529 } else {
1530 IdResolver.AddDecl(D);
1531 }
1532 warnOnReservedIdentifier(D);
1533}
1534
1535bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1536 bool AllowInlineNamespace) {
1537 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1538}
1539
1540Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1541 DeclContext *TargetDC = DC->getPrimaryContext();
1542 do {
1543 if (DeclContext *ScopeDC = S->getEntity())
1544 if (ScopeDC->getPrimaryContext() == TargetDC)
1545 return S;
1546 } while ((S = S->getParent()));
1547
1548 return nullptr;
1549}
1550
1551static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1552 DeclContext*,
1553 ASTContext&);
1554
1555/// Filters out lookup results that don't fall within the given scope
1556/// as determined by isDeclInScope.
1557void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1558 bool ConsiderLinkage,
1559 bool AllowInlineNamespace) {
1560 LookupResult::Filter F = R.makeFilter();
1561 while (F.hasNext()) {
1562 NamedDecl *D = F.next();
1563
1564 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1565 continue;
1566
1567 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1568 continue;
1569
1570 F.erase();
1571 }
1572
1573 F.done();
1574}
1575
1576/// We've determined that \p New is a redeclaration of \p Old. Check that they
1577/// have compatible owning modules.
1578bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1579 // FIXME: The Modules TS is not clear about how friend declarations are
1580 // to be treated. It's not meaningful to have different owning modules for
1581 // linkage in redeclarations of the same entity, so for now allow the
1582 // redeclaration and change the owning modules to match.
1583 if (New->getFriendObjectKind() &&
1584 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1585 New->setLocalOwningModule(Old->getOwningModule());
1586 makeMergedDefinitionVisible(New);
1587 return false;
1588 }
1589
1590 Module *NewM = New->getOwningModule();
1591 Module *OldM = Old->getOwningModule();
1592
1593 if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1594 NewM = NewM->Parent;
1595 if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1596 OldM = OldM->Parent;
1597
1598 if (NewM == OldM)
1599 return false;
1600
1601 bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1602 bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1603 if (NewIsModuleInterface || OldIsModuleInterface) {
1604 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1605 // if a declaration of D [...] appears in the purview of a module, all
1606 // other such declarations shall appear in the purview of the same module
1607 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1608 << New
1609 << NewIsModuleInterface
1610 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1611 << OldIsModuleInterface
1612 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1613 Diag(Old->getLocation(), diag::note_previous_declaration);
1614 New->setInvalidDecl();
1615 return true;
1616 }
1617
1618 return false;
1619}
1620
1621static bool isUsingDecl(NamedDecl *D) {
1622 return isa<UsingShadowDecl>(D) ||
1623 isa<UnresolvedUsingTypenameDecl>(D) ||
1624 isa<UnresolvedUsingValueDecl>(D);
1625}
1626
1627/// Removes using shadow declarations from the lookup results.
1628static void RemoveUsingDecls(LookupResult &R) {
1629 LookupResult::Filter F = R.makeFilter();
1630 while (F.hasNext())
1631 if (isUsingDecl(F.next()))
1632 F.erase();
1633
1634 F.done();
1635}
1636
1637/// Check for this common pattern:
1638/// @code
1639/// class S {
1640/// S(const S&); // DO NOT IMPLEMENT
1641/// void operator=(const S&); // DO NOT IMPLEMENT
1642/// };
1643/// @endcode
1644static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1645 // FIXME: Should check for private access too but access is set after we get
1646 // the decl here.
1647 if (D->doesThisDeclarationHaveABody())
1648 return false;
1649
1650 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1651 return CD->isCopyConstructor();
1652 return D->isCopyAssignmentOperator();
1653}
1654
1655// We need this to handle
1656//
1657// typedef struct {
1658// void *foo() { return 0; }
1659// } A;
1660//
1661// When we see foo we don't know if after the typedef we will get 'A' or '*A'
1662// for example. If 'A', foo will have external linkage. If we have '*A',
1663// foo will have no linkage. Since we can't know until we get to the end
1664// of the typedef, this function finds out if D might have non-external linkage.
1665// Callers should verify at the end of the TU if it D has external linkage or
1666// not.
1667bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1668 const DeclContext *DC = D->getDeclContext();
1669 while (!DC->isTranslationUnit()) {
1670 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1671 if (!RD->hasNameForLinkage())
1672 return true;
1673 }
1674 DC = DC->getParent();
1675 }
1676
1677 return !D->isExternallyVisible();
1678}
1679
1680// FIXME: This needs to be refactored; some other isInMainFile users want
1681// these semantics.
1682static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1683 if (S.TUKind != TU_Complete)
1684 return false;
1685 return S.SourceMgr.isInMainFile(Loc);
1686}
1687
1688bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1689 assert(D)(static_cast <bool> (D) ? void (0) : __assert_fail ("D"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 1689, __extension__ __PRETTY_FUNCTION__))
;
1690
1691 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1692 return false;
1693
1694 // Ignore all entities declared within templates, and out-of-line definitions
1695 // of members of class templates.
1696 if (D->getDeclContext()->isDependentContext() ||
1697 D->getLexicalDeclContext()->isDependentContext())
1698 return false;
1699
1700 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1701 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1702 return false;
1703 // A non-out-of-line declaration of a member specialization was implicitly
1704 // instantiated; it's the out-of-line declaration that we're interested in.
1705 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1706 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1707 return false;
1708
1709 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1710 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1711 return false;
1712 } else {
1713 // 'static inline' functions are defined in headers; don't warn.
1714 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1715 return false;
1716 }
1717
1718 if (FD->doesThisDeclarationHaveABody() &&
1719 Context.DeclMustBeEmitted(FD))
1720 return false;
1721 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1722 // Constants and utility variables are defined in headers with internal
1723 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1724 // like "inline".)
1725 if (!isMainFileLoc(*this, VD->getLocation()))
1726 return false;
1727
1728 if (Context.DeclMustBeEmitted(VD))
1729 return false;
1730
1731 if (VD->isStaticDataMember() &&
1732 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1733 return false;
1734 if (VD->isStaticDataMember() &&
1735 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1736 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1737 return false;
1738
1739 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1740 return false;
1741 } else {
1742 return false;
1743 }
1744
1745 // Only warn for unused decls internal to the translation unit.
1746 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1747 // for inline functions defined in the main source file, for instance.
1748 return mightHaveNonExternalLinkage(D);
1749}
1750
1751void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1752 if (!D)
1753 return;
1754
1755 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1756 const FunctionDecl *First = FD->getFirstDecl();
1757 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1758 return; // First should already be in the vector.
1759 }
1760
1761 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1762 const VarDecl *First = VD->getFirstDecl();
1763 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1764 return; // First should already be in the vector.
1765 }
1766
1767 if (ShouldWarnIfUnusedFileScopedDecl(D))
1768 UnusedFileScopedDecls.push_back(D);
1769}
1770
1771static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1772 if (D->isInvalidDecl())
1773 return false;
1774
1775 if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1776 // For a decomposition declaration, warn if none of the bindings are
1777 // referenced, instead of if the variable itself is referenced (which
1778 // it is, by the bindings' expressions).
1779 for (auto *BD : DD->bindings())
1780 if (BD->isReferenced())
1781 return false;
1782 } else if (!D->getDeclName()) {
1783 return false;
1784 } else if (D->isReferenced() || D->isUsed()) {
1785 return false;
1786 }
1787
1788 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>())
1789 return false;
1790
1791 if (isa<LabelDecl>(D))
1792 return true;
1793
1794 // Except for labels, we only care about unused decls that are local to
1795 // functions.
1796 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1797 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1798 // For dependent types, the diagnostic is deferred.
1799 WithinFunction =
1800 WithinFunction || (R->isLocalClass() && !R->isDependentType());
1801 if (!WithinFunction)
1802 return false;
1803
1804 if (isa<TypedefNameDecl>(D))
1805 return true;
1806
1807 // White-list anything that isn't a local variable.
1808 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1809 return false;
1810
1811 // Types of valid local variables should be complete, so this should succeed.
1812 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1813
1814 // White-list anything with an __attribute__((unused)) type.
1815 const auto *Ty = VD->getType().getTypePtr();
1816
1817 // Only look at the outermost level of typedef.
1818 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1819 if (TT->getDecl()->hasAttr<UnusedAttr>())
1820 return false;
1821 }
1822
1823 // If we failed to complete the type for some reason, or if the type is
1824 // dependent, don't diagnose the variable.
1825 if (Ty->isIncompleteType() || Ty->isDependentType())
1826 return false;
1827
1828 // Look at the element type to ensure that the warning behaviour is
1829 // consistent for both scalars and arrays.
1830 Ty = Ty->getBaseElementTypeUnsafe();
1831
1832 if (const TagType *TT = Ty->getAs<TagType>()) {
1833 const TagDecl *Tag = TT->getDecl();
1834 if (Tag->hasAttr<UnusedAttr>())
1835 return false;
1836
1837 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1838 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1839 return false;
1840
1841 if (const Expr *Init = VD->getInit()) {
1842 if (const ExprWithCleanups *Cleanups =
1843 dyn_cast<ExprWithCleanups>(Init))
1844 Init = Cleanups->getSubExpr();
1845 const CXXConstructExpr *Construct =
1846 dyn_cast<CXXConstructExpr>(Init);
1847 if (Construct && !Construct->isElidable()) {
1848 CXXConstructorDecl *CD = Construct->getConstructor();
1849 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1850 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1851 return false;
1852 }
1853
1854 // Suppress the warning if we don't know how this is constructed, and
1855 // it could possibly be non-trivial constructor.
1856 if (Init->isTypeDependent())
1857 for (const CXXConstructorDecl *Ctor : RD->ctors())
1858 if (!Ctor->isTrivial())
1859 return false;
1860 }
1861 }
1862 }
1863
1864 // TODO: __attribute__((unused)) templates?
1865 }
1866
1867 return true;
1868}
1869
1870static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1871 FixItHint &Hint) {
1872 if (isa<LabelDecl>(D)) {
1873 SourceLocation AfterColon = Lexer::findLocationAfterToken(
1874 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1875 true);
1876 if (AfterColon.isInvalid())
1877 return;
1878 Hint = FixItHint::CreateRemoval(
1879 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1880 }
1881}
1882
1883void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1884 if (D->getTypeForDecl()->isDependentType())
1885 return;
1886
1887 for (auto *TmpD : D->decls()) {
1888 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1889 DiagnoseUnusedDecl(T);
1890 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1891 DiagnoseUnusedNestedTypedefs(R);
1892 }
1893}
1894
1895/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1896/// unless they are marked attr(unused).
1897void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1898 if (!ShouldDiagnoseUnusedDecl(D))
1899 return;
1900
1901 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1902 // typedefs can be referenced later on, so the diagnostics are emitted
1903 // at end-of-translation-unit.
1904 UnusedLocalTypedefNameCandidates.insert(TD);
1905 return;
1906 }
1907
1908 FixItHint Hint;
1909 GenerateFixForUnusedDecl(D, Context, Hint);
1910
1911 unsigned DiagID;
1912 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1913 DiagID = diag::warn_unused_exception_param;
1914 else if (isa<LabelDecl>(D))
1915 DiagID = diag::warn_unused_label;
1916 else
1917 DiagID = diag::warn_unused_variable;
1918
1919 Diag(D->getLocation(), DiagID) << D << Hint;
1920}
1921
1922void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD) {
1923 // If it's not referenced, it can't be set.
1924 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>())
1925 return;
1926
1927 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
1928
1929 if (Ty->isReferenceType() || Ty->isDependentType())
1930 return;
1931
1932 if (const TagType *TT = Ty->getAs<TagType>()) {
1933 const TagDecl *Tag = TT->getDecl();
1934 if (Tag->hasAttr<UnusedAttr>())
1935 return;
1936 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
1937 // mimic gcc's behavior.
1938 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1939 if (!RD->hasAttr<WarnUnusedAttr>())
1940 return;
1941 }
1942 }
1943
1944 auto iter = RefsMinusAssignments.find(VD);
1945 if (iter == RefsMinusAssignments.end())
1946 return;
1947
1948 assert(iter->getSecond() >= 0 &&(static_cast <bool> (iter->getSecond() >= 0 &&
"Found a negative number of references to a VarDecl") ? void
(0) : __assert_fail ("iter->getSecond() >= 0 && \"Found a negative number of references to a VarDecl\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 1949, __extension__ __PRETTY_FUNCTION__))
1949 "Found a negative number of references to a VarDecl")(static_cast <bool> (iter->getSecond() >= 0 &&
"Found a negative number of references to a VarDecl") ? void
(0) : __assert_fail ("iter->getSecond() >= 0 && \"Found a negative number of references to a VarDecl\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 1949, __extension__ __PRETTY_FUNCTION__))
;
1950 if (iter->getSecond() != 0)
1951 return;
1952 unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
1953 : diag::warn_unused_but_set_variable;
1954 Diag(VD->getLocation(), DiagID) << VD;
1955}
1956
1957static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1958 // Verify that we have no forward references left. If so, there was a goto
1959 // or address of a label taken, but no definition of it. Label fwd
1960 // definitions are indicated with a null substmt which is also not a resolved
1961 // MS inline assembly label name.
1962 bool Diagnose = false;
1963 if (L->isMSAsmLabel())
1964 Diagnose = !L->isResolvedMSAsmLabel();
1965 else
1966 Diagnose = L->getStmt() == nullptr;
1967 if (Diagnose)
1968 S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L;
1969}
1970
1971void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1972 S->mergeNRVOIntoParent();
1973
1974 if (S->decl_empty()) return;
1975 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&(static_cast <bool> ((S->getFlags() & (Scope::DeclScope
| Scope::TemplateParamScope)) && "Scope shouldn't contain decls!"
) ? void (0) : __assert_fail ("(S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && \"Scope shouldn't contain decls!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 1976, __extension__ __PRETTY_FUNCTION__))
1976 "Scope shouldn't contain decls!")(static_cast <bool> ((S->getFlags() & (Scope::DeclScope
| Scope::TemplateParamScope)) && "Scope shouldn't contain decls!"
) ? void (0) : __assert_fail ("(S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && \"Scope shouldn't contain decls!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 1976, __extension__ __PRETTY_FUNCTION__))
;
1977
1978 for (auto *TmpD : S->decls()) {
1979 assert(TmpD && "This decl didn't get pushed??")(static_cast <bool> (TmpD && "This decl didn't get pushed??"
) ? void (0) : __assert_fail ("TmpD && \"This decl didn't get pushed??\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 1979, __extension__ __PRETTY_FUNCTION__))
;
1980
1981 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?")(static_cast <bool> (isa<NamedDecl>(TmpD) &&
"Decl isn't NamedDecl?") ? void (0) : __assert_fail ("isa<NamedDecl>(TmpD) && \"Decl isn't NamedDecl?\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 1981, __extension__ __PRETTY_FUNCTION__))
;
1982 NamedDecl *D = cast<NamedDecl>(TmpD);
1983
1984 // Diagnose unused variables in this scope.
1985 if (!S->hasUnrecoverableErrorOccurred()) {
1986 DiagnoseUnusedDecl(D);
1987 if (const auto *RD = dyn_cast<RecordDecl>(D))
1988 DiagnoseUnusedNestedTypedefs(RD);
1989 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1990 DiagnoseUnusedButSetDecl(VD);
1991 RefsMinusAssignments.erase(VD);
1992 }
1993 }
1994
1995 if (!D->getDeclName()) continue;
1996
1997 // If this was a forward reference to a label, verify it was defined.
1998 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1999 CheckPoppedLabel(LD, *this);
2000
2001 // Remove this name from our lexical scope, and warn on it if we haven't
2002 // already.
2003 IdResolver.RemoveDecl(D);
2004 auto ShadowI = ShadowingDecls.find(D);
2005 if (ShadowI != ShadowingDecls.end()) {
2006 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2007 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
2008 << D << FD << FD->getParent();
2009 Diag(FD->getLocation(), diag::note_previous_declaration);
2010 }
2011 ShadowingDecls.erase(ShadowI);
2012 }
2013 }
2014}
2015
2016/// Look for an Objective-C class in the translation unit.
2017///
2018/// \param Id The name of the Objective-C class we're looking for. If
2019/// typo-correction fixes this name, the Id will be updated
2020/// to the fixed name.
2021///
2022/// \param IdLoc The location of the name in the translation unit.
2023///
2024/// \param DoTypoCorrection If true, this routine will attempt typo correction
2025/// if there is no class with the given name.
2026///
2027/// \returns The declaration of the named Objective-C class, or NULL if the
2028/// class could not be found.
2029ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
2030 SourceLocation IdLoc,
2031 bool DoTypoCorrection) {
2032 // The third "scope" argument is 0 since we aren't enabling lazy built-in
2033 // creation from this context.
2034 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
2035
2036 if (!IDecl && DoTypoCorrection) {
2037 // Perform typo correction at the given location, but only if we
2038 // find an Objective-C class name.
2039 DeclFilterCCC<ObjCInterfaceDecl> CCC{};
2040 if (TypoCorrection C =
2041 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
2042 TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
2043 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
2044 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
2045 Id = IDecl->getIdentifier();
2046 }
2047 }
2048 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
2049 // This routine must always return a class definition, if any.
2050 if (Def && Def->getDefinition())
2051 Def = Def->getDefinition();
2052 return Def;
2053}
2054
2055/// getNonFieldDeclScope - Retrieves the innermost scope, starting
2056/// from S, where a non-field would be declared. This routine copes
2057/// with the difference between C and C++ scoping rules in structs and
2058/// unions. For example, the following code is well-formed in C but
2059/// ill-formed in C++:
2060/// @code
2061/// struct S6 {
2062/// enum { BAR } e;
2063/// };
2064///
2065/// void test_S6() {
2066/// struct S6 a;
2067/// a.e = BAR;
2068/// }
2069/// @endcode
2070/// For the declaration of BAR, this routine will return a different
2071/// scope. The scope S will be the scope of the unnamed enumeration
2072/// within S6. In C++, this routine will return the scope associated
2073/// with S6, because the enumeration's scope is a transparent
2074/// context but structures can contain non-field names. In C, this
2075/// routine will return the translation unit scope, since the
2076/// enumeration's scope is a transparent context and structures cannot
2077/// contain non-field names.
2078Scope *Sema::getNonFieldDeclScope(Scope *S) {
2079 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2080 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2081 (S->isClassScope() && !getLangOpts().CPlusPlus))
2082 S = S->getParent();
2083 return S;
2084}
2085
2086static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2087 ASTContext::GetBuiltinTypeError Error) {
2088 switch (Error) {
2089 case ASTContext::GE_None:
2090 return "";
2091 case ASTContext::GE_Missing_type:
2092 return BuiltinInfo.getHeaderName(ID);
2093 case ASTContext::GE_Missing_stdio:
2094 return "stdio.h";
2095 case ASTContext::GE_Missing_setjmp:
2096 return "setjmp.h";
2097 case ASTContext::GE_Missing_ucontext:
2098 return "ucontext.h";
2099 }
2100 llvm_unreachable("unhandled error kind")::llvm::llvm_unreachable_internal("unhandled error kind", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 2100)
;
2101}
2102
2103FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2104 unsigned ID, SourceLocation Loc) {
2105 DeclContext *Parent = Context.getTranslationUnitDecl();
2106
2107 if (getLangOpts().CPlusPlus) {
2108 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2109 Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
2110 CLinkageDecl->setImplicit();
2111 Parent->addDecl(CLinkageDecl);
2112 Parent = CLinkageDecl;
2113 }
2114
2115 FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2116 /*TInfo=*/nullptr, SC_Extern,
2117 getCurFPFeatures().isFPConstrained(),
2118 false, Type->isFunctionProtoType());
2119 New->setImplicit();
2120 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2121
2122 // Create Decl objects for each parameter, adding them to the
2123 // FunctionDecl.
2124 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2125 SmallVector<ParmVarDecl *, 16> Params;
2126 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2127 ParmVarDecl *parm = ParmVarDecl::Create(
2128 Context, New, SourceLocation(), SourceLocation(), nullptr,
2129 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2130 parm->setScopeInfo(0, i);
2131 Params.push_back(parm);
2132 }
2133 New->setParams(Params);
2134 }
2135
2136 AddKnownFunctionAttributes(New);
2137 return New;
2138}
2139
2140/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2141/// file scope. lazily create a decl for it. ForRedeclaration is true
2142/// if we're creating this built-in in anticipation of redeclaring the
2143/// built-in.
2144NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2145 Scope *S, bool ForRedeclaration,
2146 SourceLocation Loc) {
2147 LookupNecessaryTypesForBuiltin(S, ID);
2148
2149 ASTContext::GetBuiltinTypeError Error;
2150 QualType R = Context.GetBuiltinType(ID, Error);
2151 if (Error) {
2152 if (!ForRedeclaration)
2153 return nullptr;
2154
2155 // If we have a builtin without an associated type we should not emit a
2156 // warning when we were not able to find a type for it.
2157 if (Error == ASTContext::GE_Missing_type ||
2158 Context.BuiltinInfo.allowTypeMismatch(ID))
2159 return nullptr;
2160
2161 // If we could not find a type for setjmp it is because the jmp_buf type was
2162 // not defined prior to the setjmp declaration.
2163 if (Error == ASTContext::GE_Missing_setjmp) {
2164 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2165 << Context.BuiltinInfo.getName(ID);
2166 return nullptr;
2167 }
2168
2169 // Generally, we emit a warning that the declaration requires the
2170 // appropriate header.
2171 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2172 << getHeaderName(Context.BuiltinInfo, ID, Error)
2173 << Context.BuiltinInfo.getName(ID);
2174 return nullptr;
2175 }
2176
2177 if (!ForRedeclaration &&
2178 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2179 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2180 Diag(Loc, diag::ext_implicit_lib_function_decl)
2181 << Context.BuiltinInfo.getName(ID) << R;
2182 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2183 Diag(Loc, diag::note_include_header_or_declare)
2184 << Header << Context.BuiltinInfo.getName(ID);
2185 }
2186
2187 if (R.isNull())
2188 return nullptr;
2189
2190 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2191 RegisterLocallyScopedExternCDecl(New, S);
2192
2193 // TUScope is the translation-unit scope to insert this function into.
2194 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2195 // relate Scopes to DeclContexts, and probably eliminate CurContext
2196 // entirely, but we're not there yet.
2197 DeclContext *SavedContext = CurContext;
2198 CurContext = New->getDeclContext();
2199 PushOnScopeChains(New, TUScope);
2200 CurContext = SavedContext;
2201 return New;
2202}
2203
2204/// Typedef declarations don't have linkage, but they still denote the same
2205/// entity if their types are the same.
2206/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2207/// isSameEntity.
2208static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2209 TypedefNameDecl *Decl,
2210 LookupResult &Previous) {
2211 // This is only interesting when modules are enabled.
2212 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2213 return;
2214
2215 // Empty sets are uninteresting.
2216 if (Previous.empty())
2217 return;
2218
2219 LookupResult::Filter Filter = Previous.makeFilter();
2220 while (Filter.hasNext()) {
2221 NamedDecl *Old = Filter.next();
2222
2223 // Non-hidden declarations are never ignored.
2224 if (S.isVisible(Old))
2225 continue;
2226
2227 // Declarations of the same entity are not ignored, even if they have
2228 // different linkages.
2229 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2230 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2231 Decl->getUnderlyingType()))
2232 continue;
2233
2234 // If both declarations give a tag declaration a typedef name for linkage
2235 // purposes, then they declare the same entity.
2236 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2237 Decl->getAnonDeclWithTypedefName())
2238 continue;
2239 }
2240
2241 Filter.erase();
2242 }
2243
2244 Filter.done();
2245}
2246
2247bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2248 QualType OldType;
2249 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2250 OldType = OldTypedef->getUnderlyingType();
2251 else
2252 OldType = Context.getTypeDeclType(Old);
2253 QualType NewType = New->getUnderlyingType();
2254
2255 if (NewType->isVariablyModifiedType()) {
2256 // Must not redefine a typedef with a variably-modified type.
2257 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2258 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2259 << Kind << NewType;
2260 if (Old->getLocation().isValid())
2261 notePreviousDefinition(Old, New->getLocation());
2262 New->setInvalidDecl();
2263 return true;
2264 }
2265
2266 if (OldType != NewType &&
2267 !OldType->isDependentType() &&
2268 !NewType->isDependentType() &&
2269 !Context.hasSameType(OldType, NewType)) {
2270 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2271 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2272 << Kind << NewType << OldType;
2273 if (Old->getLocation().isValid())
2274 notePreviousDefinition(Old, New->getLocation());
2275 New->setInvalidDecl();
2276 return true;
2277 }
2278 return false;
2279}
2280
2281/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2282/// same name and scope as a previous declaration 'Old'. Figure out
2283/// how to resolve this situation, merging decls or emitting
2284/// diagnostics as appropriate. If there was an error, set New to be invalid.
2285///
2286void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2287 LookupResult &OldDecls) {
2288 // If the new decl is known invalid already, don't bother doing any
2289 // merging checks.
2290 if (New->isInvalidDecl()) return;
2291
2292 // Allow multiple definitions for ObjC built-in typedefs.
2293 // FIXME: Verify the underlying types are equivalent!
2294 if (getLangOpts().ObjC) {
2295 const IdentifierInfo *TypeID = New->getIdentifier();
2296 switch (TypeID->getLength()) {
2297 default: break;
2298 case 2:
2299 {
2300 if (!TypeID->isStr("id"))
2301 break;
2302 QualType T = New->getUnderlyingType();
2303 if (!T->isPointerType())
2304 break;
2305 if (!T->isVoidPointerType()) {
2306 QualType PT = T->castAs<PointerType>()->getPointeeType();
2307 if (!PT->isStructureType())
2308 break;
2309 }
2310 Context.setObjCIdRedefinitionType(T);
2311 // Install the built-in type for 'id', ignoring the current definition.
2312 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2313 return;
2314 }
2315 case 5:
2316 if (!TypeID->isStr("Class"))
2317 break;
2318 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2319 // Install the built-in type for 'Class', ignoring the current definition.
2320 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2321 return;
2322 case 3:
2323 if (!TypeID->isStr("SEL"))
2324 break;
2325 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2326 // Install the built-in type for 'SEL', ignoring the current definition.
2327 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2328 return;
2329 }
2330 // Fall through - the typedef name was not a builtin type.
2331 }
2332
2333 // Verify the old decl was also a type.
2334 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2335 if (!Old) {
2336 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2337 << New->getDeclName();
2338
2339 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2340 if (OldD->getLocation().isValid())
2341 notePreviousDefinition(OldD, New->getLocation());
2342
2343 return New->setInvalidDecl();
2344 }
2345
2346 // If the old declaration is invalid, just give up here.
2347 if (Old->isInvalidDecl())
2348 return New->setInvalidDecl();
2349
2350 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2351 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2352 auto *NewTag = New->getAnonDeclWithTypedefName();
2353 NamedDecl *Hidden = nullptr;
2354 if (OldTag && NewTag &&
2355 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2356 !hasVisibleDefinition(OldTag, &Hidden)) {
2357 // There is a definition of this tag, but it is not visible. Use it
2358 // instead of our tag.
2359 New->setTypeForDecl(OldTD->getTypeForDecl());
2360 if (OldTD->isModed())
2361 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2362 OldTD->getUnderlyingType());
2363 else
2364 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2365
2366 // Make the old tag definition visible.
2367 makeMergedDefinitionVisible(Hidden);
2368
2369 // If this was an unscoped enumeration, yank all of its enumerators
2370 // out of the scope.
2371 if (isa<EnumDecl>(NewTag)) {
2372 Scope *EnumScope = getNonFieldDeclScope(S);
2373 for (auto *D : NewTag->decls()) {
2374 auto *ED = cast<EnumConstantDecl>(D);
2375 assert(EnumScope->isDeclScope(ED))(static_cast <bool> (EnumScope->isDeclScope(ED)) ? void
(0) : __assert_fail ("EnumScope->isDeclScope(ED)", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 2375, __extension__ __PRETTY_FUNCTION__))
;
2376 EnumScope->RemoveDecl(ED);
2377 IdResolver.RemoveDecl(ED);
2378 ED->getLexicalDeclContext()->removeDecl(ED);
2379 }
2380 }
2381 }
2382 }
2383
2384 // If the typedef types are not identical, reject them in all languages and
2385 // with any extensions enabled.
2386 if (isIncompatibleTypedef(Old, New))
2387 return;
2388
2389 // The types match. Link up the redeclaration chain and merge attributes if
2390 // the old declaration was a typedef.
2391 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2392 New->setPreviousDecl(Typedef);
2393 mergeDeclAttributes(New, Old);
2394 }
2395
2396 if (getLangOpts().MicrosoftExt)
2397 return;
2398
2399 if (getLangOpts().CPlusPlus) {
2400 // C++ [dcl.typedef]p2:
2401 // In a given non-class scope, a typedef specifier can be used to
2402 // redefine the name of any type declared in that scope to refer
2403 // to the type to which it already refers.
2404 if (!isa<CXXRecordDecl>(CurContext))
2405 return;
2406
2407 // C++0x [dcl.typedef]p4:
2408 // In a given class scope, a typedef specifier can be used to redefine
2409 // any class-name declared in that scope that is not also a typedef-name
2410 // to refer to the type to which it already refers.
2411 //
2412 // This wording came in via DR424, which was a correction to the
2413 // wording in DR56, which accidentally banned code like:
2414 //
2415 // struct S {
2416 // typedef struct A { } A;
2417 // };
2418 //
2419 // in the C++03 standard. We implement the C++0x semantics, which
2420 // allow the above but disallow
2421 //
2422 // struct S {
2423 // typedef int I;
2424 // typedef int I;
2425 // };
2426 //
2427 // since that was the intent of DR56.
2428 if (!isa<TypedefNameDecl>(Old))
2429 return;
2430
2431 Diag(New->getLocation(), diag::err_redefinition)
2432 << New->getDeclName();
2433 notePreviousDefinition(Old, New->getLocation());
2434 return New->setInvalidDecl();
2435 }
2436
2437 // Modules always permit redefinition of typedefs, as does C11.
2438 if (getLangOpts().Modules || getLangOpts().C11)
2439 return;
2440
2441 // If we have a redefinition of a typedef in C, emit a warning. This warning
2442 // is normally mapped to an error, but can be controlled with
2443 // -Wtypedef-redefinition. If either the original or the redefinition is
2444 // in a system header, don't emit this for compatibility with GCC.
2445 if (getDiagnostics().getSuppressSystemWarnings() &&
2446 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2447 (Old->isImplicit() ||
2448 Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2449 Context.getSourceManager().isInSystemHeader(New->getLocation())))
2450 return;
2451
2452 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2453 << New->getDeclName();
2454 notePreviousDefinition(Old, New->getLocation());
2455}
2456
2457/// DeclhasAttr - returns true if decl Declaration already has the target
2458/// attribute.
2459static bool DeclHasAttr(const Decl *D, const Attr *A) {
2460 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2461 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2462 for (const auto *i : D->attrs())
2463 if (i->getKind() == A->getKind()) {
2464 if (Ann) {
2465 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2466 return true;
2467 continue;
2468 }
2469 // FIXME: Don't hardcode this check
2470 if (OA && isa<OwnershipAttr>(i))
2471 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2472 return true;
2473 }
2474
2475 return false;
2476}
2477
2478static bool isAttributeTargetADefinition(Decl *D) {
2479 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2480 return VD->isThisDeclarationADefinition();
2481 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2482 return TD->isCompleteDefinition() || TD->isBeingDefined();
2483 return true;
2484}
2485
2486/// Merge alignment attributes from \p Old to \p New, taking into account the
2487/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2488///
2489/// \return \c true if any attributes were added to \p New.
2490static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2491 // Look for alignas attributes on Old, and pick out whichever attribute
2492 // specifies the strictest alignment requirement.
2493 AlignedAttr *OldAlignasAttr = nullptr;
2494 AlignedAttr *OldStrictestAlignAttr = nullptr;
2495 unsigned OldAlign = 0;
2496 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2497 // FIXME: We have no way of representing inherited dependent alignments
2498 // in a case like:
2499 // template<int A, int B> struct alignas(A) X;
2500 // template<int A, int B> struct alignas(B) X {};
2501 // For now, we just ignore any alignas attributes which are not on the
2502 // definition in such a case.
2503 if (I->isAlignmentDependent())
2504 return false;
2505
2506 if (I->isAlignas())
2507 OldAlignasAttr = I;
2508
2509 unsigned Align = I->getAlignment(S.Context);
2510 if (Align > OldAlign) {
2511 OldAlign = Align;
2512 OldStrictestAlignAttr = I;
2513 }
2514 }
2515
2516 // Look for alignas attributes on New.
2517 AlignedAttr *NewAlignasAttr = nullptr;
2518 unsigned NewAlign = 0;
2519 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2520 if (I->isAlignmentDependent())
2521 return false;
2522
2523 if (I->isAlignas())
2524 NewAlignasAttr = I;
2525
2526 unsigned Align = I->getAlignment(S.Context);
2527 if (Align > NewAlign)
2528 NewAlign = Align;
2529 }
2530
2531 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2532 // Both declarations have 'alignas' attributes. We require them to match.
2533 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2534 // fall short. (If two declarations both have alignas, they must both match
2535 // every definition, and so must match each other if there is a definition.)
2536
2537 // If either declaration only contains 'alignas(0)' specifiers, then it
2538 // specifies the natural alignment for the type.
2539 if (OldAlign == 0 || NewAlign == 0) {
2540 QualType Ty;
2541 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2542 Ty = VD->getType();
2543 else
2544 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2545
2546 if (OldAlign == 0)
2547 OldAlign = S.Context.getTypeAlign(Ty);
2548 if (NewAlign == 0)
2549 NewAlign = S.Context.getTypeAlign(Ty);
2550 }
2551
2552 if (OldAlign != NewAlign) {
2553 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2554 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2555 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2556 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2557 }
2558 }
2559
2560 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2561 // C++11 [dcl.align]p6:
2562 // if any declaration of an entity has an alignment-specifier,
2563 // every defining declaration of that entity shall specify an
2564 // equivalent alignment.
2565 // C11 6.7.5/7:
2566 // If the definition of an object does not have an alignment
2567 // specifier, any other declaration of that object shall also
2568 // have no alignment specifier.
2569 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2570 << OldAlignasAttr;
2571 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2572 << OldAlignasAttr;
2573 }
2574
2575 bool AnyAdded = false;
2576
2577 // Ensure we have an attribute representing the strictest alignment.
2578 if (OldAlign > NewAlign) {
2579 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2580 Clone->setInherited(true);
2581 New->addAttr(Clone);
2582 AnyAdded = true;
2583 }
2584
2585 // Ensure we have an alignas attribute if the old declaration had one.
2586 if (OldAlignasAttr && !NewAlignasAttr &&
2587 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2588 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2589 Clone->setInherited(true);
2590 New->addAttr(Clone);
2591 AnyAdded = true;
2592 }
2593
2594 return AnyAdded;
2595}
2596
2597#define WANT_DECL_MERGE_LOGIC
2598#include "clang/Sema/AttrParsedAttrImpl.inc"
2599#undef WANT_DECL_MERGE_LOGIC
2600
2601static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2602 const InheritableAttr *Attr,
2603 Sema::AvailabilityMergeKind AMK) {
2604 // Diagnose any mutual exclusions between the attribute that we want to add
2605 // and attributes that already exist on the declaration.
2606 if (!DiagnoseMutualExclusions(S, D, Attr))
2607 return false;
2608
2609 // This function copies an attribute Attr from a previous declaration to the
2610 // new declaration D if the new declaration doesn't itself have that attribute
2611 // yet or if that attribute allows duplicates.
2612 // If you're adding a new attribute that requires logic different from
2613 // "use explicit attribute on decl if present, else use attribute from
2614 // previous decl", for example if the attribute needs to be consistent
2615 // between redeclarations, you need to call a custom merge function here.
2616 InheritableAttr *NewAttr = nullptr;
2617 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2618 NewAttr = S.mergeAvailabilityAttr(
2619 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2620 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2621 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2622 AA->getPriority());
2623 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2624 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2625 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2626 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2627 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2628 NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2629 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2630 NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2631 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2632 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2633 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2634 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2635 FA->getFirstArg());
2636 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2637 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2638 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2639 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2640 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2641 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2642 IA->getInheritanceModel());
2643 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2644 NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2645 &S.Context.Idents.get(AA->getSpelling()));
2646 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2647 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2648 isa<CUDAGlobalAttr>(Attr))) {
2649 // CUDA target attributes are part of function signature for
2650 // overloading purposes and must not be merged.
2651 return false;
2652 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2653 NewAttr = S.mergeMinSizeAttr(D, *MA);
2654 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2655 NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2656 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2657 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2658 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2659 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2660 else if (isa<AlignedAttr>(Attr))
2661 // AlignedAttrs are handled separately, because we need to handle all
2662 // such attributes on a declaration at the same time.
2663 NewAttr = nullptr;
2664 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2665 (AMK == Sema::AMK_Override ||
2666 AMK == Sema::AMK_ProtocolImplementation ||
2667 AMK == Sema::AMK_OptionalProtocolImplementation))
2668 NewAttr = nullptr;
2669 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2670 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2671 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2672 NewAttr = S.mergeImportModuleAttr(D, *IMA);
2673 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2674 NewAttr = S.mergeImportNameAttr(D, *INA);
2675 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2676 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2677 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2678 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2679 else if (const auto *BTFA = dyn_cast<BTFTagAttr>(Attr))
2680 NewAttr = S.mergeBTFTagAttr(D, *BTFA);
2681 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2682 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2683
2684 if (NewAttr) {
2685 NewAttr->setInherited(true);
2686 D->addAttr(NewAttr);
2687 if (isa<MSInheritanceAttr>(NewAttr))
2688 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2689 return true;
2690 }
2691
2692 return false;
2693}
2694
2695static const NamedDecl *getDefinition(const Decl *D) {
2696 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2697 return TD->getDefinition();
2698 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2699 const VarDecl *Def = VD->getDefinition();
2700 if (Def)
2701 return Def;
2702 return VD->getActingDefinition();
2703 }
2704 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2705 const FunctionDecl *Def = nullptr;
2706 if (FD->isDefined(Def, true))
2707 return Def;
2708 }
2709 return nullptr;
2710}
2711
2712static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2713 for (const auto *Attribute : D->attrs())
2714 if (Attribute->getKind() == Kind)
2715 return true;
2716 return false;
2717}
2718
2719/// checkNewAttributesAfterDef - If we already have a definition, check that
2720/// there are no new attributes in this declaration.
2721static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2722 if (!New->hasAttrs())
2723 return;
2724
2725 const NamedDecl *Def = getDefinition(Old);
2726 if (!Def || Def == New)
2727 return;
2728
2729 AttrVec &NewAttributes = New->getAttrs();
2730 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2731 const Attr *NewAttribute = NewAttributes[I];
2732
2733 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2734 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2735 Sema::SkipBodyInfo SkipBody;
2736 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2737
2738 // If we're skipping this definition, drop the "alias" attribute.
2739 if (SkipBody.ShouldSkip) {
2740 NewAttributes.erase(NewAttributes.begin() + I);
2741 --E;
2742 continue;
2743 }
2744 } else {
2745 VarDecl *VD = cast<VarDecl>(New);
2746 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2747 VarDecl::TentativeDefinition
2748 ? diag::err_alias_after_tentative
2749 : diag::err_redefinition;
2750 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2751 if (Diag == diag::err_redefinition)
2752 S.notePreviousDefinition(Def, VD->getLocation());
2753 else
2754 S.Diag(Def->getLocation(), diag::note_previous_definition);
2755 VD->setInvalidDecl();
2756 }
2757 ++I;
2758 continue;
2759 }
2760
2761 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2762 // Tentative definitions are only interesting for the alias check above.
2763 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2764 ++I;
2765 continue;
2766 }
2767 }
2768
2769 if (hasAttribute(Def, NewAttribute->getKind())) {
2770 ++I;
2771 continue; // regular attr merging will take care of validating this.
2772 }
2773
2774 if (isa<C11NoReturnAttr>(NewAttribute)) {
2775 // C's _Noreturn is allowed to be added to a function after it is defined.
2776 ++I;
2777 continue;
2778 } else if (isa<UuidAttr>(NewAttribute)) {
2779 // msvc will allow a subsequent definition to add an uuid to a class
2780 ++I;
2781 continue;
2782 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2783 if (AA->isAlignas()) {
2784 // C++11 [dcl.align]p6:
2785 // if any declaration of an entity has an alignment-specifier,
2786 // every defining declaration of that entity shall specify an
2787 // equivalent alignment.
2788 // C11 6.7.5/7:
2789 // If the definition of an object does not have an alignment
2790 // specifier, any other declaration of that object shall also
2791 // have no alignment specifier.
2792 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2793 << AA;
2794 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2795 << AA;
2796 NewAttributes.erase(NewAttributes.begin() + I);
2797 --E;
2798 continue;
2799 }
2800 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2801 // If there is a C definition followed by a redeclaration with this
2802 // attribute then there are two different definitions. In C++, prefer the
2803 // standard diagnostics.
2804 if (!S.getLangOpts().CPlusPlus) {
2805 S.Diag(NewAttribute->getLocation(),
2806 diag::err_loader_uninitialized_redeclaration);
2807 S.Diag(Def->getLocation(), diag::note_previous_definition);
2808 NewAttributes.erase(NewAttributes.begin() + I);
2809 --E;
2810 continue;
2811 }
2812 } else if (isa<SelectAnyAttr>(NewAttribute) &&
2813 cast<VarDecl>(New)->isInline() &&
2814 !cast<VarDecl>(New)->isInlineSpecified()) {
2815 // Don't warn about applying selectany to implicitly inline variables.
2816 // Older compilers and language modes would require the use of selectany
2817 // to make such variables inline, and it would have no effect if we
2818 // honored it.
2819 ++I;
2820 continue;
2821 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
2822 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
2823 // declarations after defintions.
2824 ++I;
2825 continue;
2826 }
2827
2828 S.Diag(NewAttribute->getLocation(),
2829 diag::warn_attribute_precede_definition);
2830 S.Diag(Def->getLocation(), diag::note_previous_definition);
2831 NewAttributes.erase(NewAttributes.begin() + I);
2832 --E;
2833 }
2834}
2835
2836static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2837 const ConstInitAttr *CIAttr,
2838 bool AttrBeforeInit) {
2839 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2840
2841 // Figure out a good way to write this specifier on the old declaration.
2842 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2843 // enough of the attribute list spelling information to extract that without
2844 // heroics.
2845 std::string SuitableSpelling;
2846 if (S.getLangOpts().CPlusPlus20)
2847 SuitableSpelling = std::string(
2848 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2849 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2850 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2851 InsertLoc, {tok::l_square, tok::l_square,
2852 S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2853 S.PP.getIdentifierInfo("require_constant_initialization"),
2854 tok::r_square, tok::r_square}));
2855 if (SuitableSpelling.empty())
2856 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2857 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2858 S.PP.getIdentifierInfo("require_constant_initialization"),
2859 tok::r_paren, tok::r_paren}));
2860 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
2861 SuitableSpelling = "constinit";
2862 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2863 SuitableSpelling = "[[clang::require_constant_initialization]]";
2864 if (SuitableSpelling.empty())
2865 SuitableSpelling = "__attribute__((require_constant_initialization))";
2866 SuitableSpelling += " ";
2867
2868 if (AttrBeforeInit) {
2869 // extern constinit int a;
2870 // int a = 0; // error (missing 'constinit'), accepted as extension
2871 assert(CIAttr->isConstinit() && "should not diagnose this for attribute")(static_cast <bool> (CIAttr->isConstinit() &&
"should not diagnose this for attribute") ? void (0) : __assert_fail
("CIAttr->isConstinit() && \"should not diagnose this for attribute\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 2871, __extension__ __PRETTY_FUNCTION__))
;
2872 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2873 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2874 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2875 } else {
2876 // int a = 0;
2877 // constinit extern int a; // error (missing 'constinit')
2878 S.Diag(CIAttr->getLocation(),
2879 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2880 : diag::warn_require_const_init_added_too_late)
2881 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2882 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2883 << CIAttr->isConstinit()
2884 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2885 }
2886}
2887
2888/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2889void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2890 AvailabilityMergeKind AMK) {
2891 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2892 UsedAttr *NewAttr = OldAttr->clone(Context);
2893 NewAttr->setInherited(true);
2894 New->addAttr(NewAttr);
2895 }
2896 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
2897 RetainAttr *NewAttr = OldAttr->clone(Context);
2898 NewAttr->setInherited(true);
2899 New->addAttr(NewAttr);
2900 }
2901
2902 if (!Old->hasAttrs() && !New->hasAttrs())
2903 return;
2904
2905 // [dcl.constinit]p1:
2906 // If the [constinit] specifier is applied to any declaration of a
2907 // variable, it shall be applied to the initializing declaration.
2908 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
2909 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
2910 if (bool(OldConstInit) != bool(NewConstInit)) {
2911 const auto *OldVD = cast<VarDecl>(Old);
2912 auto *NewVD = cast<VarDecl>(New);
2913
2914 // Find the initializing declaration. Note that we might not have linked
2915 // the new declaration into the redeclaration chain yet.
2916 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
2917 if (!InitDecl &&
2918 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
2919 InitDecl = NewVD;
2920
2921 if (InitDecl == NewVD) {
2922 // This is the initializing declaration. If it would inherit 'constinit',
2923 // that's ill-formed. (Note that we do not apply this to the attribute
2924 // form).
2925 if (OldConstInit && OldConstInit->isConstinit())
2926 diagnoseMissingConstinit(*this, NewVD, OldConstInit,
2927 /*AttrBeforeInit=*/true);
2928 } else if (NewConstInit) {
2929 // This is the first time we've been told that this declaration should
2930 // have a constant initializer. If we already saw the initializing
2931 // declaration, this is too late.
2932 if (InitDecl && InitDecl != NewVD) {
2933 diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
2934 /*AttrBeforeInit=*/false);
2935 NewVD->dropAttr<ConstInitAttr>();
2936 }
2937 }
2938 }
2939
2940 // Attributes declared post-definition are currently ignored.
2941 checkNewAttributesAfterDef(*this, New, Old);
2942
2943 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2944 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2945 if (!OldA->isEquivalent(NewA)) {
2946 // This redeclaration changes __asm__ label.
2947 Diag(New->getLocation(), diag::err_different_asm_label);
2948 Diag(OldA->getLocation(), diag::note_previous_declaration);
2949 }
2950 } else if (Old->isUsed()) {
2951 // This redeclaration adds an __asm__ label to a declaration that has
2952 // already been ODR-used.
2953 Diag(New->getLocation(), diag::err_late_asm_label_name)
2954 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2955 }
2956 }
2957
2958 // Re-declaration cannot add abi_tag's.
2959 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2960 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2961 for (const auto &NewTag : NewAbiTagAttr->tags()) {
2962 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2963 NewTag) == OldAbiTagAttr->tags_end()) {
2964 Diag(NewAbiTagAttr->getLocation(),
2965 diag::err_new_abi_tag_on_redeclaration)
2966 << NewTag;
2967 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2968 }
2969 }
2970 } else {
2971 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2972 Diag(Old->getLocation(), diag::note_previous_declaration);
2973 }
2974 }
2975
2976 // This redeclaration adds a section attribute.
2977 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2978 if (auto *VD = dyn_cast<VarDecl>(New)) {
2979 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2980 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2981 Diag(Old->getLocation(), diag::note_previous_declaration);
2982 }
2983 }
2984 }
2985
2986 // Redeclaration adds code-seg attribute.
2987 const auto *NewCSA = New->getAttr<CodeSegAttr>();
2988 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2989 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2990 Diag(New->getLocation(), diag::warn_mismatched_section)
2991 << 0 /*codeseg*/;
2992 Diag(Old->getLocation(), diag::note_previous_declaration);
2993 }
2994
2995 if (!Old->hasAttrs())
2996 return;
2997
2998 bool foundAny = New->hasAttrs();
2999
3000 // Ensure that any moving of objects within the allocated map is done before
3001 // we process them.
3002 if (!foundAny) New->setAttrs(AttrVec());
3003
3004 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3005 // Ignore deprecated/unavailable/availability attributes if requested.
3006 AvailabilityMergeKind LocalAMK = AMK_None;
3007 if (isa<DeprecatedAttr>(I) ||
3008 isa<UnavailableAttr>(I) ||
3009 isa<AvailabilityAttr>(I)) {
3010 switch (AMK) {
3011 case AMK_None:
3012 continue;
3013
3014 case AMK_Redeclaration:
3015 case AMK_Override:
3016 case AMK_ProtocolImplementation:
3017 case AMK_OptionalProtocolImplementation:
3018 LocalAMK = AMK;
3019 break;
3020 }
3021 }
3022
3023 // Already handled.
3024 if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3025 continue;
3026
3027 if (mergeDeclAttribute(*this, New, I, LocalAMK))
3028 foundAny = true;
3029 }
3030
3031 if (mergeAlignedAttrs(*this, New, Old))
3032 foundAny = true;
3033
3034 if (!foundAny) New->dropAttrs();
3035}
3036
3037/// mergeParamDeclAttributes - Copy attributes from the old parameter
3038/// to the new one.
3039static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3040 const ParmVarDecl *oldDecl,
3041 Sema &S) {
3042 // C++11 [dcl.attr.depend]p2:
3043 // The first declaration of a function shall specify the
3044 // carries_dependency attribute for its declarator-id if any declaration
3045 // of the function specifies the carries_dependency attribute.
3046 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3047 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3048 S.Diag(CDA->getLocation(),
3049 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3050 // Find the first declaration of the parameter.
3051 // FIXME: Should we build redeclaration chains for function parameters?
3052 const FunctionDecl *FirstFD =
3053 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3054 const ParmVarDecl *FirstVD =
3055 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3056 S.Diag(FirstVD->getLocation(),
3057 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3058 }
3059
3060 if (!oldDecl->hasAttrs())
3061 return;
3062
3063 bool foundAny = newDecl->hasAttrs();
3064
3065 // Ensure that any moving of objects within the allocated map is
3066 // done before we process them.
3067 if (!foundAny) newDecl->setAttrs(AttrVec());
3068
3069 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3070 if (!DeclHasAttr(newDecl, I)) {
3071 InheritableAttr *newAttr =
3072 cast<InheritableParamAttr>(I->clone(S.Context));
3073 newAttr->setInherited(true);
3074 newDecl->addAttr(newAttr);
3075 foundAny = true;
3076 }
3077 }
3078
3079 if (!foundAny) newDecl->dropAttrs();
3080}
3081
3082static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3083 const ParmVarDecl *OldParam,
3084 Sema &S) {
3085 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3086 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3087 if (*Oldnullability != *Newnullability) {
3088 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3089 << DiagNullabilityKind(
3090 *Newnullability,
3091 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3092 != 0))
3093 << DiagNullabilityKind(
3094 *Oldnullability,
3095 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3096 != 0));
3097 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3098 }
3099 } else {
3100 QualType NewT = NewParam->getType();
3101 NewT = S.Context.getAttributedType(
3102 AttributedType::getNullabilityAttrKind(*Oldnullability),
3103 NewT, NewT);
3104 NewParam->setType(NewT);
3105 }
3106 }
3107}
3108
3109namespace {
3110
3111/// Used in MergeFunctionDecl to keep track of function parameters in
3112/// C.
3113struct GNUCompatibleParamWarning {
3114 ParmVarDecl *OldParm;
3115 ParmVarDecl *NewParm;
3116 QualType PromotedType;
3117};
3118
3119} // end anonymous namespace
3120
3121// Determine whether the previous declaration was a definition, implicit
3122// declaration, or a declaration.
3123template <typename T>
3124static std::pair<diag::kind, SourceLocation>
3125getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3126 diag::kind PrevDiag;
3127 SourceLocation OldLocation = Old->getLocation();
3128 if (Old->isThisDeclarationADefinition())
3129 PrevDiag = diag::note_previous_definition;
3130 else if (Old->isImplicit()) {
3131 PrevDiag = diag::note_previous_implicit_declaration;
3132 if (OldLocation.isInvalid())
3133 OldLocation = New->getLocation();
3134 } else
3135 PrevDiag = diag::note_previous_declaration;
3136 return std::make_pair(PrevDiag, OldLocation);
3137}
3138
3139/// canRedefineFunction - checks if a function can be redefined. Currently,
3140/// only extern inline functions can be redefined, and even then only in
3141/// GNU89 mode.
3142static bool canRedefineFunction(const FunctionDecl *FD,
3143 const LangOptions& LangOpts) {
3144 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3145 !LangOpts.CPlusPlus &&
3146 FD->isInlineSpecified() &&
3147 FD->getStorageClass() == SC_Extern);
3148}
3149
3150const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3151 const AttributedType *AT = T->getAs<AttributedType>();
3152 while (AT && !AT->isCallingConv())
3153 AT = AT->getModifiedType()->getAs<AttributedType>();
3154 return AT;
3155}
3156
3157template <typename T>
3158static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3159 const DeclContext *DC = Old->getDeclContext();
3160 if (DC->isRecord())
3161 return false;
3162
3163 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3164 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3165 return true;
3166 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3167 return true;
3168 return false;
3169}
3170
3171template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3172static bool isExternC(VarTemplateDecl *) { return false; }
3173static bool isExternC(FunctionTemplateDecl *) { return false; }
3174
3175/// Check whether a redeclaration of an entity introduced by a
3176/// using-declaration is valid, given that we know it's not an overload
3177/// (nor a hidden tag declaration).
3178template<typename ExpectedDecl>
3179static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3180 ExpectedDecl *New) {
3181 // C++11 [basic.scope.declarative]p4:
3182 // Given a set of declarations in a single declarative region, each of
3183 // which specifies the same unqualified name,
3184 // -- they shall all refer to the same entity, or all refer to functions
3185 // and function templates; or
3186 // -- exactly one declaration shall declare a class name or enumeration
3187 // name that is not a typedef name and the other declarations shall all
3188 // refer to the same variable or enumerator, or all refer to functions
3189 // and function templates; in this case the class name or enumeration
3190 // name is hidden (3.3.10).
3191
3192 // C++11 [namespace.udecl]p14:
3193 // If a function declaration in namespace scope or block scope has the
3194 // same name and the same parameter-type-list as a function introduced
3195 // by a using-declaration, and the declarations do not declare the same
3196 // function, the program is ill-formed.
3197
3198 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3199 if (Old &&
3200 !Old->getDeclContext()->getRedeclContext()->Equals(
3201 New->getDeclContext()->getRedeclContext()) &&
3202 !(isExternC(Old) && isExternC(New)))
3203 Old = nullptr;
3204
3205 if (!Old) {
3206 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3207 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3208 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3209 return true;
3210 }
3211 return false;
3212}
3213
3214static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3215 const FunctionDecl *B) {
3216 assert(A->getNumParams() == B->getNumParams())(static_cast <bool> (A->getNumParams() == B->getNumParams
()) ? void (0) : __assert_fail ("A->getNumParams() == B->getNumParams()"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 3216, __extension__ __PRETTY_FUNCTION__))
;
3217
3218 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3219 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3220 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3221 if (AttrA == AttrB)
3222 return true;
3223 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3224 AttrA->isDynamic() == AttrB->isDynamic();
3225 };
3226
3227 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3228}
3229
3230/// If necessary, adjust the semantic declaration context for a qualified
3231/// declaration to name the correct inline namespace within the qualifier.
3232static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3233 DeclaratorDecl *OldD) {
3234 // The only case where we need to update the DeclContext is when
3235 // redeclaration lookup for a qualified name finds a declaration
3236 // in an inline namespace within the context named by the qualifier:
3237 //
3238 // inline namespace N { int f(); }
3239 // int ::f(); // Sema DC needs adjusting from :: to N::.
3240 //
3241 // For unqualified declarations, the semantic context *can* change
3242 // along the redeclaration chain (for local extern declarations,
3243 // extern "C" declarations, and friend declarations in particular).
3244 if (!NewD->getQualifier())
3245 return;
3246
3247 // NewD is probably already in the right context.
3248 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3249 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3250 if (NamedDC->Equals(SemaDC))
3251 return;
3252
3253 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||(static_cast <bool> ((NamedDC->InEnclosingNamespaceSetOf
(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl
()) && "unexpected context for redeclaration") ? void
(0) : __assert_fail ("(NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl()) && \"unexpected context for redeclaration\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 3255, __extension__ __PRETTY_FUNCTION__))
3254 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&(static_cast <bool> ((NamedDC->InEnclosingNamespaceSetOf
(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl
()) && "unexpected context for redeclaration") ? void
(0) : __assert_fail ("(NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl()) && \"unexpected context for redeclaration\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 3255, __extension__ __PRETTY_FUNCTION__))
3255 "unexpected context for redeclaration")(static_cast <bool> ((NamedDC->InEnclosingNamespaceSetOf
(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl
()) && "unexpected context for redeclaration") ? void
(0) : __assert_fail ("(NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl()) && \"unexpected context for redeclaration\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 3255, __extension__ __PRETTY_FUNCTION__))
;
3256
3257 auto *LexDC = NewD->getLexicalDeclContext();
3258 auto FixSemaDC = [=](NamedDecl *D) {
3259 if (!D)
3260 return;
3261 D->setDeclContext(SemaDC);
3262 D->setLexicalDeclContext(LexDC);
3263 };
3264
3265 FixSemaDC(NewD);
3266 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3267 FixSemaDC(FD->getDescribedFunctionTemplate());
3268 else if (auto *VD = dyn_cast<VarDecl>(NewD))
3269 FixSemaDC(VD->getDescribedVarTemplate());
3270}
3271
3272/// MergeFunctionDecl - We just parsed a function 'New' from
3273/// declarator D which has the same name and scope as a previous
3274/// declaration 'Old'. Figure out how to resolve this situation,
3275/// merging decls or emitting diagnostics as appropriate.
3276///
3277/// In C++, New and Old must be declarations that are not
3278/// overloaded. Use IsOverload to determine whether New and Old are
3279/// overloaded, and to select the Old declaration that New should be
3280/// merged with.
3281///
3282/// Returns true if there was an error, false otherwise.
3283bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3284 Scope *S, bool MergeTypeWithOld) {
3285 // Verify the old decl was also a function.
3286 FunctionDecl *Old = OldD->getAsFunction();
3287 if (!Old) {
3288 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3289 if (New->getFriendObjectKind()) {
3290 Diag(New->getLocation(), diag::err_using_decl_friend);
3291 Diag(Shadow->getTargetDecl()->getLocation(),
3292 diag::note_using_decl_target);
3293 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3294 << 0;
3295 return true;
3296 }
3297
3298 // Check whether the two declarations might declare the same function or
3299 // function template.
3300 if (FunctionTemplateDecl *NewTemplate =
3301 New->getDescribedFunctionTemplate()) {
3302 if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3303 NewTemplate))
3304 return true;
3305 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3306 ->getAsFunction();
3307 } else {
3308 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3309 return true;
3310 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3311 }
3312 } else {
3313 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3314 << New->getDeclName();
3315 notePreviousDefinition(OldD, New->getLocation());
3316 return true;
3317 }
3318 }
3319
3320 // If the old declaration was found in an inline namespace and the new
3321 // declaration was qualified, update the DeclContext to match.
3322 adjustDeclContextForDeclaratorDecl(New, Old);
3323
3324 // If the old declaration is invalid, just give up here.
3325 if (Old->isInvalidDecl())
3326 return true;
3327
3328 // Disallow redeclaration of some builtins.
3329 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3330 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3331 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3332 << Old << Old->getType();
3333 return true;
3334 }
3335
3336 diag::kind PrevDiag;
3337 SourceLocation OldLocation;
3338 std::tie(PrevDiag, OldLocation) =
3339 getNoteDiagForInvalidRedeclaration(Old, New);
3340
3341 // Don't complain about this if we're in GNU89 mode and the old function
3342 // is an extern inline function.
3343 // Don't complain about specializations. They are not supposed to have
3344 // storage classes.
3345 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3346 New->getStorageClass() == SC_Static &&
3347 Old->hasExternalFormalLinkage() &&
3348 !New->getTemplateSpecializationInfo() &&
3349 !canRedefineFunction(Old, getLangOpts())) {
3350 if (getLangOpts().MicrosoftExt) {
3351 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3352 Diag(OldLocation, PrevDiag);
3353 } else {
3354 Diag(New->getLocation(), diag::err_static_non_static) << New;
3355 Diag(OldLocation, PrevDiag);
3356 return true;
3357 }
3358 }
3359
3360 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3361 if (!Old->hasAttr<InternalLinkageAttr>()) {
3362 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3363 << ILA;
3364 Diag(Old->getLocation(), diag::note_previous_declaration);
3365 New->dropAttr<InternalLinkageAttr>();
3366 }
3367
3368 if (auto *EA = New->getAttr<ErrorAttr>()) {
3369 if (!Old->hasAttr<ErrorAttr>()) {
3370 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3371 Diag(Old->getLocation(), diag::note_previous_declaration);
3372 New->dropAttr<ErrorAttr>();
3373 }
3374 }
3375
3376 if (CheckRedeclarationModuleOwnership(New, Old))
3377 return true;
3378
3379 if (!getLangOpts().CPlusPlus) {
3380 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3381 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3382 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3383 << New << OldOvl;
3384
3385 // Try our best to find a decl that actually has the overloadable
3386 // attribute for the note. In most cases (e.g. programs with only one
3387 // broken declaration/definition), this won't matter.
3388 //
3389 // FIXME: We could do this if we juggled some extra state in
3390 // OverloadableAttr, rather than just removing it.
3391 const Decl *DiagOld = Old;
3392 if (OldOvl) {
3393 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3394 const auto *A = D->getAttr<OverloadableAttr>();
3395 return A && !A->isImplicit();
3396 });
3397 // If we've implicitly added *all* of the overloadable attrs to this
3398 // chain, emitting a "previous redecl" note is pointless.
3399 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3400 }
3401
3402 if (DiagOld)
3403 Diag(DiagOld->getLocation(),
3404 diag::note_attribute_overloadable_prev_overload)
3405 << OldOvl;
3406
3407 if (OldOvl)
3408 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3409 else
3410 New->dropAttr<OverloadableAttr>();
3411 }
3412 }
3413
3414 // If a function is first declared with a calling convention, but is later
3415 // declared or defined without one, all following decls assume the calling
3416 // convention of the first.
3417 //
3418 // It's OK if a function is first declared without a calling convention,
3419 // but is later declared or defined with the default calling convention.
3420 //
3421 // To test if either decl has an explicit calling convention, we look for
3422 // AttributedType sugar nodes on the type as written. If they are missing or
3423 // were canonicalized away, we assume the calling convention was implicit.
3424 //
3425 // Note also that we DO NOT return at this point, because we still have
3426 // other tests to run.
3427 QualType OldQType = Context.getCanonicalType(Old->getType());
3428 QualType NewQType = Context.getCanonicalType(New->getType());
3429 const FunctionType *OldType = cast<FunctionType>(OldQType);
3430 const FunctionType *NewType = cast<FunctionType>(NewQType);
3431 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3432 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3433 bool RequiresAdjustment = false;
3434
3435 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3436 FunctionDecl *First = Old->getFirstDecl();
3437 const FunctionType *FT =
3438 First->getType().getCanonicalType()->castAs<FunctionType>();
3439 FunctionType::ExtInfo FI = FT->getExtInfo();
3440 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3441 if (!NewCCExplicit) {
3442 // Inherit the CC from the previous declaration if it was specified
3443 // there but not here.
3444 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3445 RequiresAdjustment = true;
3446 } else if (Old->getBuiltinID()) {
3447 // Builtin attribute isn't propagated to the new one yet at this point,
3448 // so we check if the old one is a builtin.
3449
3450 // Calling Conventions on a Builtin aren't really useful and setting a
3451 // default calling convention and cdecl'ing some builtin redeclarations is
3452 // common, so warn and ignore the calling convention on the redeclaration.
3453 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3454 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3455 << (int)CallingConventionIgnoredReason::BuiltinFunction;
3456 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3457 RequiresAdjustment = true;
3458 } else {
3459 // Calling conventions aren't compatible, so complain.
3460 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3461 Diag(New->getLocation(), diag::err_cconv_change)
3462 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3463 << !FirstCCExplicit
3464 << (!FirstCCExplicit ? "" :
3465 FunctionType::getNameForCallConv(FI.getCC()));
3466
3467 // Put the note on the first decl, since it is the one that matters.
3468 Diag(First->getLocation(), diag::note_previous_declaration);
3469 return true;
3470 }
3471 }
3472
3473 // FIXME: diagnose the other way around?
3474 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3475 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3476 RequiresAdjustment = true;
3477 }
3478
3479 // Merge regparm attribute.
3480 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3481 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3482 if (NewTypeInfo.getHasRegParm()) {
3483 Diag(New->getLocation(), diag::err_regparm_mismatch)
3484 << NewType->getRegParmType()
3485 << OldType->getRegParmType();
3486 Diag(OldLocation, diag::note_previous_declaration);
3487 return true;
3488 }
3489
3490 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3491 RequiresAdjustment = true;
3492 }
3493
3494 // Merge ns_returns_retained attribute.
3495 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3496 if (NewTypeInfo.getProducesResult()) {
3497 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3498 << "'ns_returns_retained'";
3499 Diag(OldLocation, diag::note_previous_declaration);
3500 return true;
3501 }
3502
3503 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3504 RequiresAdjustment = true;
3505 }
3506
3507 if (OldTypeInfo.getNoCallerSavedRegs() !=
3508 NewTypeInfo.getNoCallerSavedRegs()) {
3509 if (NewTypeInfo.getNoCallerSavedRegs()) {
3510 AnyX86NoCallerSavedRegistersAttr *Attr =
3511 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3512 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3513 Diag(OldLocation, diag::note_previous_declaration);
3514 return true;
3515 }
3516
3517 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3518 RequiresAdjustment = true;
3519 }
3520
3521 if (RequiresAdjustment) {
3522 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3523 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3524 New->setType(QualType(AdjustedType, 0));
3525 NewQType = Context.getCanonicalType(New->getType());
3526 }
3527
3528 // If this redeclaration makes the function inline, we may need to add it to
3529 // UndefinedButUsed.
3530 if (!Old->isInlined() && New->isInlined() &&
3531 !New->hasAttr<GNUInlineAttr>() &&
3532 !getLangOpts().GNUInline &&
3533 Old->isUsed(false) &&
3534 !Old->isDefined() && !New->isThisDeclarationADefinition())
3535 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3536 SourceLocation()));
3537
3538 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3539 // about it.
3540 if (New->hasAttr<GNUInlineAttr>() &&
3541 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3542 UndefinedButUsed.erase(Old->getCanonicalDecl());
3543 }
3544
3545 // If pass_object_size params don't match up perfectly, this isn't a valid
3546 // redeclaration.
3547 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3548 !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3549 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3550 << New->getDeclName();
3551 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3552 return true;
3553 }
3554
3555 if (getLangOpts().CPlusPlus) {
3556 // C++1z [over.load]p2
3557 // Certain function declarations cannot be overloaded:
3558 // -- Function declarations that differ only in the return type,
3559 // the exception specification, or both cannot be overloaded.
3560
3561 // Check the exception specifications match. This may recompute the type of
3562 // both Old and New if it resolved exception specifications, so grab the
3563 // types again after this. Because this updates the type, we do this before
3564 // any of the other checks below, which may update the "de facto" NewQType
3565 // but do not necessarily update the type of New.
3566 if (CheckEquivalentExceptionSpec(Old, New))
3567 return true;
3568 OldQType = Context.getCanonicalType(Old->getType());
3569 NewQType = Context.getCanonicalType(New->getType());
3570
3571 // Go back to the type source info to compare the declared return types,
3572 // per C++1y [dcl.type.auto]p13:
3573 // Redeclarations or specializations of a function or function template
3574 // with a declared return type that uses a placeholder type shall also
3575 // use that placeholder, not a deduced type.
3576 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3577 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3578 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3579 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3580 OldDeclaredReturnType)) {
3581 QualType ResQT;
3582 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3583 OldDeclaredReturnType->isObjCObjectPointerType())
3584 // FIXME: This does the wrong thing for a deduced return type.
3585 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3586 if (ResQT.isNull()) {
3587 if (New->isCXXClassMember() && New->isOutOfLine())
3588 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3589 << New << New->getReturnTypeSourceRange();
3590 else
3591 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3592 << New->getReturnTypeSourceRange();
3593 Diag(OldLocation, PrevDiag) << Old << Old->getType()
3594 << Old->getReturnTypeSourceRange();
3595 return true;
3596 }
3597 else
3598 NewQType = ResQT;
3599 }
3600
3601 QualType OldReturnType = OldType->getReturnType();
3602 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3603 if (OldReturnType != NewReturnType) {
3604 // If this function has a deduced return type and has already been
3605 // defined, copy the deduced value from the old declaration.
3606 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3607 if (OldAT && OldAT->isDeduced()) {
3608 New->setType(
3609 SubstAutoType(New->getType(),
3610 OldAT->isDependentType() ? Context.DependentTy
3611 : OldAT->getDeducedType()));
3612 NewQType = Context.getCanonicalType(
3613 SubstAutoType(NewQType,
3614 OldAT->isDependentType() ? Context.DependentTy
3615 : OldAT->getDeducedType()));
3616 }
3617 }
3618
3619 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3620 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3621 if (OldMethod && NewMethod) {
3622 // Preserve triviality.
3623 NewMethod->setTrivial(OldMethod->isTrivial());
3624
3625 // MSVC allows explicit template specialization at class scope:
3626 // 2 CXXMethodDecls referring to the same function will be injected.
3627 // We don't want a redeclaration error.
3628 bool IsClassScopeExplicitSpecialization =
3629 OldMethod->isFunctionTemplateSpecialization() &&
3630 NewMethod->isFunctionTemplateSpecialization();
3631 bool isFriend = NewMethod->getFriendObjectKind();
3632
3633 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3634 !IsClassScopeExplicitSpecialization) {
3635 // -- Member function declarations with the same name and the
3636 // same parameter types cannot be overloaded if any of them
3637 // is a static member function declaration.
3638 if (OldMethod->isStatic() != NewMethod->isStatic()) {
3639 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3640 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3641 return true;
3642 }
3643
3644 // C++ [class.mem]p1:
3645 // [...] A member shall not be declared twice in the
3646 // member-specification, except that a nested class or member
3647 // class template can be declared and then later defined.
3648 if (!inTemplateInstantiation()) {
3649 unsigned NewDiag;
3650 if (isa<CXXConstructorDecl>(OldMethod))
3651 NewDiag = diag::err_constructor_redeclared;
3652 else if (isa<CXXDestructorDecl>(NewMethod))
3653 NewDiag = diag::err_destructor_redeclared;
3654 else if (isa<CXXConversionDecl>(NewMethod))
3655 NewDiag = diag::err_conv_function_redeclared;
3656 else
3657 NewDiag = diag::err_member_redeclared;
3658
3659 Diag(New->getLocation(), NewDiag);
3660 } else {
3661 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3662 << New << New->getType();
3663 }
3664 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3665 return true;
3666
3667 // Complain if this is an explicit declaration of a special
3668 // member that was initially declared implicitly.
3669 //
3670 // As an exception, it's okay to befriend such methods in order
3671 // to permit the implicit constructor/destructor/operator calls.
3672 } else if (OldMethod->isImplicit()) {
3673 if (isFriend) {
3674 NewMethod->setImplicit();
3675 } else {
3676 Diag(NewMethod->getLocation(),
3677 diag::err_definition_of_implicitly_declared_member)
3678 << New << getSpecialMember(OldMethod);
3679 return true;
3680 }
3681 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3682 Diag(NewMethod->getLocation(),
3683 diag::err_definition_of_explicitly_defaulted_member)
3684 << getSpecialMember(OldMethod);
3685 return true;
3686 }
3687 }
3688
3689 // C++11 [dcl.attr.noreturn]p1:
3690 // The first declaration of a function shall specify the noreturn
3691 // attribute if any declaration of that function specifies the noreturn
3692 // attribute.
3693 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
3694 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
3695 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
3696 << NRA;
3697 Diag(Old->getLocation(), diag::note_previous_declaration);
3698 }
3699
3700 // C++11 [dcl.attr.depend]p2:
3701 // The first declaration of a function shall specify the
3702 // carries_dependency attribute for its declarator-id if any declaration
3703 // of the function specifies the carries_dependency attribute.
3704 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3705 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3706 Diag(CDA->getLocation(),
3707 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3708 Diag(Old->getFirstDecl()->getLocation(),
3709 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3710 }
3711
3712 // (C++98 8.3.5p3):
3713 // All declarations for a function shall agree exactly in both the
3714 // return type and the parameter-type-list.
3715 // We also want to respect all the extended bits except noreturn.
3716
3717 // noreturn should now match unless the old type info didn't have it.
3718 QualType OldQTypeForComparison = OldQType;
3719 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3720 auto *OldType = OldQType->castAs<FunctionProtoType>();
3721 const FunctionType *OldTypeForComparison
3722 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3723 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3724 assert(OldQTypeForComparison.isCanonical())(static_cast <bool> (OldQTypeForComparison.isCanonical(
)) ? void (0) : __assert_fail ("OldQTypeForComparison.isCanonical()"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 3724, __extension__ __PRETTY_FUNCTION__))
;
3725 }
3726
3727 if (haveIncompatibleLanguageLinkages(Old, New)) {
3728 // As a special case, retain the language linkage from previous
3729 // declarations of a friend function as an extension.
3730 //
3731 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3732 // and is useful because there's otherwise no way to specify language
3733 // linkage within class scope.
3734 //
3735 // Check cautiously as the friend object kind isn't yet complete.
3736 if (New->getFriendObjectKind() != Decl::FOK_None) {
3737 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3738 Diag(OldLocation, PrevDiag);
3739 } else {
3740 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3741 Diag(OldLocation, PrevDiag);
3742 return true;
3743 }
3744 }
3745
3746 // If the function types are compatible, merge the declarations. Ignore the
3747 // exception specifier because it was already checked above in
3748 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3749 // about incompatible types under -fms-compatibility.
3750 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3751 NewQType))
3752 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3753
3754 // If the types are imprecise (due to dependent constructs in friends or
3755 // local extern declarations), it's OK if they differ. We'll check again
3756 // during instantiation.
3757 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3758 return false;
3759
3760 // Fall through for conflicting redeclarations and redefinitions.
3761 }
3762
3763 // C: Function types need to be compatible, not identical. This handles
3764 // duplicate function decls like "void f(int); void f(enum X);" properly.
3765 if (!getLangOpts().CPlusPlus &&
3766 Context.typesAreCompatible(OldQType, NewQType)) {
3767 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3768 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3769 const FunctionProtoType *OldProto = nullptr;
3770 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3771 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3772 // The old declaration provided a function prototype, but the
3773 // new declaration does not. Merge in the prototype.
3774 assert(!OldProto->hasExceptionSpec() && "Exception spec in C")(static_cast <bool> (!OldProto->hasExceptionSpec() &&
"Exception spec in C") ? void (0) : __assert_fail ("!OldProto->hasExceptionSpec() && \"Exception spec in C\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 3774, __extension__ __PRETTY_FUNCTION__))
;
3775 SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3776 NewQType =
3777 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3778 OldProto->getExtProtoInfo());
3779 New->setType(NewQType);
3780 New->setHasInheritedPrototype();
3781
3782 // Synthesize parameters with the same types.
3783 SmallVector<ParmVarDecl*, 16> Params;
3784 for (const auto &ParamType : OldProto->param_types()) {
3785 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3786 SourceLocation(), nullptr,
3787 ParamType, /*TInfo=*/nullptr,
3788 SC_None, nullptr);
3789 Param->setScopeInfo(0, Params.size());
3790 Param->setImplicit();
3791 Params.push_back(Param);
3792 }
3793
3794 New->setParams(Params);
3795 }
3796
3797 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3798 }
3799
3800 // Check if the function types are compatible when pointer size address
3801 // spaces are ignored.
3802 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
3803 return false;
3804
3805 // GNU C permits a K&R definition to follow a prototype declaration
3806 // if the declared types of the parameters in the K&R definition
3807 // match the types in the prototype declaration, even when the
3808 // promoted types of the parameters from the K&R definition differ
3809 // from the types in the prototype. GCC then keeps the types from
3810 // the prototype.
3811 //
3812 // If a variadic prototype is followed by a non-variadic K&R definition,
3813 // the K&R definition becomes variadic. This is sort of an edge case, but
3814 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3815 // C99 6.9.1p8.
3816 if (!getLangOpts().CPlusPlus &&
3817 Old->hasPrototype() && !New->hasPrototype() &&
3818 New->getType()->getAs<FunctionProtoType>() &&
3819 Old->getNumParams() == New->getNumParams()) {
3820 SmallVector<QualType, 16> ArgTypes;
3821 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3822 const FunctionProtoType *OldProto
3823 = Old->getType()->getAs<FunctionProtoType>();
3824 const FunctionProtoType *NewProto
3825 = New->getType()->getAs<FunctionProtoType>();
3826
3827 // Determine whether this is the GNU C extension.
3828 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3829 NewProto->getReturnType());
3830 bool LooseCompatible = !MergedReturn.isNull();
3831 for (unsigned Idx = 0, End = Old->getNumParams();
3832 LooseCompatible && Idx != End; ++Idx) {
3833 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3834 ParmVarDecl *NewParm = New->getParamDecl(Idx);
3835 if (Context.typesAreCompatible(OldParm->getType(),
3836 NewProto->getParamType(Idx))) {
3837 ArgTypes.push_back(NewParm->getType());
3838 } else if (Context.typesAreCompatible(OldParm->getType(),
3839 NewParm->getType(),
3840 /*CompareUnqualified=*/true)) {
3841 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3842 NewProto->getParamType(Idx) };
3843 Warnings.push_back(Warn);
3844 ArgTypes.push_back(NewParm->getType());
3845 } else
3846 LooseCompatible = false;
3847 }
3848
3849 if (LooseCompatible) {
3850 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3851 Diag(Warnings[Warn].NewParm->getLocation(),
3852 diag::ext_param_promoted_not_compatible_with_prototype)
3853 << Warnings[Warn].PromotedType
3854 << Warnings[Warn].OldParm->getType();
3855 if (Warnings[Warn].OldParm->getLocation().isValid())
3856 Diag(Warnings[Warn].OldParm->getLocation(),
3857 diag::note_previous_declaration);
3858 }
3859
3860 if (MergeTypeWithOld)
3861 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3862 OldProto->getExtProtoInfo()));
3863 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3864 }
3865
3866 // Fall through to diagnose conflicting types.
3867 }
3868
3869 // A function that has already been declared has been redeclared or
3870 // defined with a different type; show an appropriate diagnostic.
3871
3872 // If the previous declaration was an implicitly-generated builtin
3873 // declaration, then at the very least we should use a specialized note.
3874 unsigned BuiltinID;
3875 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3876 // If it's actually a library-defined builtin function like 'malloc'
3877 // or 'printf', just warn about the incompatible redeclaration.
3878 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3879 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3880 Diag(OldLocation, diag::note_previous_builtin_declaration)
3881 << Old << Old->getType();
3882 return false;
3883 }
3884
3885 PrevDiag = diag::note_previous_builtin_declaration;
3886 }
3887
3888 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3889 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3890 return true;
3891}
3892
3893/// Completes the merge of two function declarations that are
3894/// known to be compatible.
3895///
3896/// This routine handles the merging of attributes and other
3897/// properties of function declarations from the old declaration to
3898/// the new declaration, once we know that New is in fact a
3899/// redeclaration of Old.
3900///
3901/// \returns false
3902bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3903 Scope *S, bool MergeTypeWithOld) {
3904 // Merge the attributes
3905 mergeDeclAttributes(New, Old);
3906
3907 // Merge "pure" flag.
3908 if (Old->isPure())
3909 New->setPure();
3910
3911 // Merge "used" flag.
3912 if (Old->getMostRecentDecl()->isUsed(false))
3913 New->setIsUsed();
3914
3915 // Merge attributes from the parameters. These can mismatch with K&R
3916 // declarations.
3917 if (New->getNumParams() == Old->getNumParams())
3918 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3919 ParmVarDecl *NewParam = New->getParamDecl(i);
3920 ParmVarDecl *OldParam = Old->getParamDecl(i);
3921 mergeParamDeclAttributes(NewParam, OldParam, *this);
3922 mergeParamDeclTypes(NewParam, OldParam, *this);
3923 }
3924
3925 if (getLangOpts().CPlusPlus)
3926 return MergeCXXFunctionDecl(New, Old, S);
3927
3928 // Merge the function types so the we get the composite types for the return
3929 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3930 // was visible.
3931 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3932 if (!Merged.isNull() && MergeTypeWithOld)
3933 New->setType(Merged);
3934
3935 return false;
3936}
3937
3938void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3939 ObjCMethodDecl *oldMethod) {
3940 // Merge the attributes, including deprecated/unavailable
3941 AvailabilityMergeKind MergeKind =
3942 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3943 ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
3944 : AMK_ProtocolImplementation)
3945 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3946 : AMK_Override;
3947
3948 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3949
3950 // Merge attributes from the parameters.
3951 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3952 oe = oldMethod->param_end();
3953 for (ObjCMethodDecl::param_iterator
3954 ni = newMethod->param_begin(), ne = newMethod->param_end();
3955 ni != ne && oi != oe; ++ni, ++oi)
3956 mergeParamDeclAttributes(*ni, *oi, *this);
3957
3958 CheckObjCMethodOverride(newMethod, oldMethod);
3959}
3960
3961static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3962 assert(!S.Context.hasSameType(New->getType(), Old->getType()))(static_cast <bool> (!S.Context.hasSameType(New->getType
(), Old->getType())) ? void (0) : __assert_fail ("!S.Context.hasSameType(New->getType(), Old->getType())"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 3962, __extension__ __PRETTY_FUNCTION__))
;
3963
3964 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3965 ? diag::err_redefinition_different_type
3966 : diag::err_redeclaration_different_type)
3967 << New->getDeclName() << New->getType() << Old->getType();
3968
3969 diag::kind PrevDiag;
3970 SourceLocation OldLocation;
3971 std::tie(PrevDiag, OldLocation)
3972 = getNoteDiagForInvalidRedeclaration(Old, New);
3973 S.Diag(OldLocation, PrevDiag);
3974 New->setInvalidDecl();
3975}
3976
3977/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3978/// scope as a previous declaration 'Old'. Figure out how to merge their types,
3979/// emitting diagnostics as appropriate.
3980///
3981/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3982/// to here in AddInitializerToDecl. We can't check them before the initializer
3983/// is attached.
3984void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3985 bool MergeTypeWithOld) {
3986 if (New->isInvalidDecl() || Old->isInvalidDecl())
3987 return;
3988
3989 QualType MergedT;
3990 if (getLangOpts().CPlusPlus) {
3991 if (New->getType()->isUndeducedType()) {
3992 // We don't know what the new type is until the initializer is attached.
3993 return;
3994 } else if (Context.hasSameType(New->getType(), Old->getType())) {
3995 // These could still be something that needs exception specs checked.
3996 return MergeVarDeclExceptionSpecs(New, Old);
3997 }
3998 // C++ [basic.link]p10:
3999 // [...] the types specified by all declarations referring to a given
4000 // object or function shall be identical, except that declarations for an
4001 // array object can specify array types that differ by the presence or
4002 // absence of a major array bound (8.3.4).
4003 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4004 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4005 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4006
4007 // We are merging a variable declaration New into Old. If it has an array
4008 // bound, and that bound differs from Old's bound, we should diagnose the
4009 // mismatch.
4010 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4011 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4012 PrevVD = PrevVD->getPreviousDecl()) {
4013 QualType PrevVDTy = PrevVD->getType();
4014 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4015 continue;
4016
4017 if (!Context.hasSameType(New->getType(), PrevVDTy))
4018 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4019 }
4020 }
4021
4022 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4023 if (Context.hasSameType(OldArray->getElementType(),
4024 NewArray->getElementType()))
4025 MergedT = New->getType();
4026 }
4027 // FIXME: Check visibility. New is hidden but has a complete type. If New
4028 // has no array bound, it should not inherit one from Old, if Old is not
4029 // visible.
4030 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4031 if (Context.hasSameType(OldArray->getElementType(),
4032 NewArray->getElementType()))
4033 MergedT = Old->getType();
4034 }
4035 }
4036 else if (New->getType()->isObjCObjectPointerType() &&
4037 Old->getType()->isObjCObjectPointerType()) {
4038 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4039 Old->getType());
4040 }
4041 } else {
4042 // C 6.2.7p2:
4043 // All declarations that refer to the same object or function shall have
4044 // compatible type.
4045 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4046 }
4047 if (MergedT.isNull()) {
4048 // It's OK if we couldn't merge types if either type is dependent, for a
4049 // block-scope variable. In other cases (static data members of class
4050 // templates, variable templates, ...), we require the types to be
4051 // equivalent.
4052 // FIXME: The C++ standard doesn't say anything about this.
4053 if ((New->getType()->isDependentType() ||
4054 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4055 // If the old type was dependent, we can't merge with it, so the new type
4056 // becomes dependent for now. We'll reproduce the original type when we
4057 // instantiate the TypeSourceInfo for the variable.
4058 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4059 New->setType(Context.DependentTy);
4060 return;
4061 }
4062 return diagnoseVarDeclTypeMismatch(*this, New, Old);
4063 }
4064
4065 // Don't actually update the type on the new declaration if the old
4066 // declaration was an extern declaration in a different scope.
4067 if (MergeTypeWithOld)
4068 New->setType(MergedT);
4069}
4070
4071static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4072 LookupResult &Previous) {
4073 // C11 6.2.7p4:
4074 // For an identifier with internal or external linkage declared
4075 // in a scope in which a prior declaration of that identifier is
4076 // visible, if the prior declaration specifies internal or
4077 // external linkage, the type of the identifier at the later
4078 // declaration becomes the composite type.
4079 //
4080 // If the variable isn't visible, we do not merge with its type.
4081 if (Previous.isShadowed())
4082 return false;
4083
4084 if (S.getLangOpts().CPlusPlus) {
4085 // C++11 [dcl.array]p3:
4086 // If there is a preceding declaration of the entity in the same
4087 // scope in which the bound was specified, an omitted array bound
4088 // is taken to be the same as in that earlier declaration.
4089 return NewVD->isPreviousDeclInSameBlockScope() ||
4090 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4091 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4092 } else {
4093 // If the old declaration was function-local, don't merge with its
4094 // type unless we're in the same function.
4095 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4096 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4097 }
4098}
4099
4100/// MergeVarDecl - We just parsed a variable 'New' which has the same name
4101/// and scope as a previous declaration 'Old'. Figure out how to resolve this
4102/// situation, merging decls or emitting diagnostics as appropriate.
4103///
4104/// Tentative definition rules (C99 6.9.2p2) are checked by
4105/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4106/// definitions here, since the initializer hasn't been attached.
4107///
4108void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4109 // If the new decl is already invalid, don't do any other checking.
4110 if (New->isInvalidDecl())
4111 return;
4112
4113 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4114 return;
4115
4116 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4117
4118 // Verify the old decl was also a variable or variable template.
4119 VarDecl *Old = nullptr;
4120 VarTemplateDecl *OldTemplate = nullptr;
4121 if (Previous.isSingleResult()) {
4122 if (NewTemplate) {
4123 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4124 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4125
4126 if (auto *Shadow =
4127 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4128 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4129 return New->setInvalidDecl();
4130 } else {
4131 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4132
4133 if (auto *Shadow =
4134 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4135 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4136 return New->setInvalidDecl();
4137 }
4138 }
4139 if (!Old) {
4140 Diag(New->getLocation(), diag::err_redefinition_different_kind)
4141 << New->getDeclName();
4142 notePreviousDefinition(Previous.getRepresentativeDecl(),
4143 New->getLocation());
4144 return New->setInvalidDecl();
4145 }
4146
4147 // If the old declaration was found in an inline namespace and the new
4148 // declaration was qualified, update the DeclContext to match.
4149 adjustDeclContextForDeclaratorDecl(New, Old);
4150
4151 // Ensure the template parameters are compatible.
4152 if (NewTemplate &&
4153 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4154 OldTemplate->getTemplateParameters(),
4155 /*Complain=*/true, TPL_TemplateMatch))
4156 return New->setInvalidDecl();
4157
4158 // C++ [class.mem]p1:
4159 // A member shall not be declared twice in the member-specification [...]
4160 //
4161 // Here, we need only consider static data members.
4162 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4163 Diag(New->getLocation(), diag::err_duplicate_member)
4164 << New->getIdentifier();
4165 Diag(Old->getLocation(), diag::note_previous_declaration);
4166 New->setInvalidDecl();
4167 }
4168
4169 mergeDeclAttributes(New, Old);
4170 // Warn if an already-declared variable is made a weak_import in a subsequent
4171 // declaration
4172 if (New->hasAttr<WeakImportAttr>() &&
4173 Old->getStorageClass() == SC_None &&
4174 !Old->hasAttr<WeakImportAttr>()) {
4175 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4176 Diag(Old->getLocation(), diag::note_previous_declaration);
4177 // Remove weak_import attribute on new declaration.
4178 New->dropAttr<WeakImportAttr>();
4179 }
4180
4181 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4182 if (!Old->hasAttr<InternalLinkageAttr>()) {
4183 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4184 << ILA;
4185 Diag(Old->getLocation(), diag::note_previous_declaration);
4186 New->dropAttr<InternalLinkageAttr>();
4187 }
4188
4189 // Merge the types.
4190 VarDecl *MostRecent = Old->getMostRecentDecl();
4191 if (MostRecent != Old) {
4192 MergeVarDeclTypes(New, MostRecent,
4193 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4194 if (New->isInvalidDecl())
4195 return;
4196 }
4197
4198 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4199 if (New->isInvalidDecl())
4200 return;
4201
4202 diag::kind PrevDiag;
4203 SourceLocation OldLocation;
4204 std::tie(PrevDiag, OldLocation) =
4205 getNoteDiagForInvalidRedeclaration(Old, New);
4206
4207 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4208 if (New->getStorageClass() == SC_Static &&
4209 !New->isStaticDataMember() &&
4210 Old->hasExternalFormalLinkage()) {
4211 if (getLangOpts().MicrosoftExt) {
4212 Diag(New->getLocation(), diag::ext_static_non_static)
4213 << New->getDeclName();
4214 Diag(OldLocation, PrevDiag);
4215 } else {
4216 Diag(New->getLocation(), diag::err_static_non_static)
4217 << New->getDeclName();
4218 Diag(OldLocation, PrevDiag);
4219 return New->setInvalidDecl();
4220 }
4221 }
4222 // C99 6.2.2p4:
4223 // For an identifier declared with the storage-class specifier
4224 // extern in a scope in which a prior declaration of that
4225 // identifier is visible,23) if the prior declaration specifies
4226 // internal or external linkage, the linkage of the identifier at
4227 // the later declaration is the same as the linkage specified at
4228 // the prior declaration. If no prior declaration is visible, or
4229 // if the prior declaration specifies no linkage, then the
4230 // identifier has external linkage.
4231 if (New->hasExternalStorage() && Old->hasLinkage())
4232 /* Okay */;
4233 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4234 !New->isStaticDataMember() &&
4235 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4236 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4237 Diag(OldLocation, PrevDiag);
4238 return New->setInvalidDecl();
4239 }
4240
4241 // Check if extern is followed by non-extern and vice-versa.
4242 if (New->hasExternalStorage() &&
4243 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4244 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4245 Diag(OldLocation, PrevDiag);
4246 return New->setInvalidDecl();
4247 }
4248 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4249 !New->hasExternalStorage()) {
4250 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4251 Diag(OldLocation, PrevDiag);
4252 return New->setInvalidDecl();
4253 }
4254
4255 if (CheckRedeclarationModuleOwnership(New, Old))
4256 return;
4257
4258 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4259
4260 // FIXME: The test for external storage here seems wrong? We still
4261 // need to check for mismatches.
4262 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4263 // Don't complain about out-of-line definitions of static members.
4264 !(Old->getLexicalDeclContext()->isRecord() &&
4265 !New->getLexicalDeclContext()->isRecord())) {
4266 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4267 Diag(OldLocation, PrevDiag);
4268 return New->setInvalidDecl();
4269 }
4270
4271 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4272 if (VarDecl *Def = Old->getDefinition()) {
4273 // C++1z [dcl.fcn.spec]p4:
4274 // If the definition of a variable appears in a translation unit before
4275 // its first declaration as inline, the program is ill-formed.
4276 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4277 Diag(Def->getLocation(), diag::note_previous_definition);
4278 }
4279 }
4280
4281 // If this redeclaration makes the variable inline, we may need to add it to
4282 // UndefinedButUsed.
4283 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4284 !Old->getDefinition() && !New->isThisDeclarationADefinition())
4285 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4286 SourceLocation()));
4287
4288 if (New->getTLSKind() != Old->getTLSKind()) {
4289 if (!Old->getTLSKind()) {
4290 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4291 Diag(OldLocation, PrevDiag);
4292 } else if (!New->getTLSKind()) {
4293 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4294 Diag(OldLocation, PrevDiag);
4295 } else {
4296 // Do not allow redeclaration to change the variable between requiring
4297 // static and dynamic initialization.
4298 // FIXME: GCC allows this, but uses the TLS keyword on the first
4299 // declaration to determine the kind. Do we need to be compatible here?
4300 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4301 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4302 Diag(OldLocation, PrevDiag);
4303 }
4304 }
4305
4306 // C++ doesn't have tentative definitions, so go right ahead and check here.
4307 if (getLangOpts().CPlusPlus &&
4308 New->isThisDeclarationADefinition() == VarDecl::Definition) {
4309 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4310 Old->getCanonicalDecl()->isConstexpr()) {
4311 // This definition won't be a definition any more once it's been merged.
4312 Diag(New->getLocation(),
4313 diag::warn_deprecated_redundant_constexpr_static_def);
4314 } else if (VarDecl *Def = Old->getDefinition()) {
4315 if (checkVarDeclRedefinition(Def, New))
4316 return;
4317 }
4318 }
4319
4320 if (haveIncompatibleLanguageLinkages(Old, New)) {
4321 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4322 Diag(OldLocation, PrevDiag);
4323 New->setInvalidDecl();
4324 return;
4325 }
4326
4327 // Merge "used" flag.
4328 if (Old->getMostRecentDecl()->isUsed(false))
4329 New->setIsUsed();
4330
4331 // Keep a chain of previous declarations.
4332 New->setPreviousDecl(Old);
4333 if (NewTemplate)
4334 NewTemplate->setPreviousDecl(OldTemplate);
4335
4336 // Inherit access appropriately.
4337 New->setAccess(Old->getAccess());
4338 if (NewTemplate)
4339 NewTemplate->setAccess(New->getAccess());
4340
4341 if (Old->isInline())
4342 New->setImplicitlyInline();
4343}
4344
4345void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4346 SourceManager &SrcMgr = getSourceManager();
4347 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4348 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4349 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4350 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4351 auto &HSI = PP.getHeaderSearchInfo();
4352 StringRef HdrFilename =
4353 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4354
4355 auto noteFromModuleOrInclude = [&](Module *Mod,
4356 SourceLocation IncLoc) -> bool {
4357 // Redefinition errors with modules are common with non modular mapped
4358 // headers, example: a non-modular header H in module A that also gets
4359 // included directly in a TU. Pointing twice to the same header/definition
4360 // is confusing, try to get better diagnostics when modules is on.
4361 if (IncLoc.isValid()) {
4362 if (Mod) {
4363 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4364 << HdrFilename.str() << Mod->getFullModuleName();
4365 if (!Mod->DefinitionLoc.isInvalid())
4366 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4367 << Mod->getFullModuleName();
4368 } else {
4369 Diag(IncLoc, diag::note_redefinition_include_same_file)
4370 << HdrFilename.str();
4371 }
4372 return true;
4373 }
4374
4375 return false;
4376 };
4377
4378 // Is it the same file and same offset? Provide more information on why
4379 // this leads to a redefinition error.
4380 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4381 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4382 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4383 bool EmittedDiag =
4384 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4385 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4386
4387 // If the header has no guards, emit a note suggesting one.
4388 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4389 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4390
4391 if (EmittedDiag)
4392 return;
4393 }
4394
4395 // Redefinition coming from different files or couldn't do better above.
4396 if (Old->getLocation().isValid())
4397 Diag(Old->getLocation(), diag::note_previous_definition);
4398}
4399
4400/// We've just determined that \p Old and \p New both appear to be definitions
4401/// of the same variable. Either diagnose or fix the problem.
4402bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4403 if (!hasVisibleDefinition(Old) &&
4404 (New->getFormalLinkage() == InternalLinkage ||
4405 New->isInline() ||
4406 New->getDescribedVarTemplate() ||
4407 New->getNumTemplateParameterLists() ||
4408 New->getDeclContext()->isDependentContext())) {
4409 // The previous definition is hidden, and multiple definitions are
4410 // permitted (in separate TUs). Demote this to a declaration.
4411 New->demoteThisDefinitionToDeclaration();
4412
4413 // Make the canonical definition visible.
4414 if (auto *OldTD = Old->getDescribedVarTemplate())
4415 makeMergedDefinitionVisible(OldTD);
4416 makeMergedDefinitionVisible(Old);
4417 return false;
4418 } else {
4419 Diag(New->getLocation(), diag::err_redefinition) << New;
4420 notePreviousDefinition(Old, New->getLocation());
4421 New->setInvalidDecl();
4422 return true;
4423 }
4424}
4425
4426/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4427/// no declarator (e.g. "struct foo;") is parsed.
4428Decl *
4429Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4430 RecordDecl *&AnonRecord) {
4431 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4432 AnonRecord);
4433}
4434
4435// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4436// disambiguate entities defined in different scopes.
4437// While the VS2015 ABI fixes potential miscompiles, it is also breaks
4438// compatibility.
4439// We will pick our mangling number depending on which version of MSVC is being
4440// targeted.
4441static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4442 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4443 ? S->getMSCurManglingNumber()
4444 : S->getMSLastManglingNumber();
4445}
4446
4447void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4448 if (!Context.getLangOpts().CPlusPlus)
4449 return;
4450
4451 if (isa<CXXRecordDecl>(Tag->getParent())) {
4452 // If this tag is the direct child of a class, number it if
4453 // it is anonymous.
4454 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4455 return;
4456 MangleNumberingContext &MCtx =
4457 Context.getManglingNumberContext(Tag->getParent());
4458 Context.setManglingNumber(
4459 Tag, MCtx.getManglingNumber(
4460 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4461 return;
4462 }
4463
4464 // If this tag isn't a direct child of a class, number it if it is local.
4465 MangleNumberingContext *MCtx;
4466 Decl *ManglingContextDecl;
4467 std::tie(MCtx, ManglingContextDecl) =
4468 getCurrentMangleNumberContext(Tag->getDeclContext());
4469 if (MCtx) {
4470 Context.setManglingNumber(
4471 Tag, MCtx->getManglingNumber(
4472 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4473 }
4474}
4475
4476namespace {
4477struct NonCLikeKind {
4478 enum {
4479 None,
4480 BaseClass,
4481 DefaultMemberInit,
4482 Lambda,
4483 Friend,
4484 OtherMember,
4485 Invalid,
4486 } Kind = None;
4487 SourceRange Range;
4488
4489 explicit operator bool() { return Kind != None; }
4490};
4491}
4492
4493/// Determine whether a class is C-like, according to the rules of C++
4494/// [dcl.typedef] for anonymous classes with typedef names for linkage.
4495static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4496 if (RD->isInvalidDecl())
4497 return {NonCLikeKind::Invalid, {}};
4498
4499 // C++ [dcl.typedef]p9: [P1766R1]
4500 // An unnamed class with a typedef name for linkage purposes shall not
4501 //
4502 // -- have any base classes
4503 if (RD->getNumBases())
4504 return {NonCLikeKind::BaseClass,
4505 SourceRange(RD->bases_begin()->getBeginLoc(),
4506 RD->bases_end()[-1].getEndLoc())};
4507 bool Invalid = false;
4508 for (Decl *D : RD->decls()) {
4509 // Don't complain about things we already diagnosed.
4510 if (D->isInvalidDecl()) {
4511 Invalid = true;
4512 continue;
4513 }
4514
4515 // -- have any [...] default member initializers
4516 if (auto *FD = dyn_cast<FieldDecl>(D)) {
4517 if (FD->hasInClassInitializer()) {
4518 auto *Init = FD->getInClassInitializer();
4519 return {NonCLikeKind::DefaultMemberInit,
4520 Init ? Init->getSourceRange() : D->getSourceRange()};
4521 }
4522 continue;
4523 }
4524
4525 // FIXME: We don't allow friend declarations. This violates the wording of
4526 // P1766, but not the intent.
4527 if (isa<FriendDecl>(D))
4528 return {NonCLikeKind::Friend, D->getSourceRange()};
4529
4530 // -- declare any members other than non-static data members, member
4531 // enumerations, or member classes,
4532 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4533 isa<EnumDecl>(D))
4534 continue;
4535 auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4536 if (!MemberRD) {
4537 if (D->isImplicit())
4538 continue;
4539 return {NonCLikeKind::OtherMember, D->getSourceRange()};
4540 }
4541
4542 // -- contain a lambda-expression,
4543 if (MemberRD->isLambda())
4544 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4545
4546 // and all member classes shall also satisfy these requirements
4547 // (recursively).
4548 if (MemberRD->isThisDeclarationADefinition()) {
4549 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4550 return Kind;
4551 }
4552 }
4553
4554 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4555}
4556
4557void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4558 TypedefNameDecl *NewTD) {
4559 if (TagFromDeclSpec->isInvalidDecl())
4560 return;
4561
4562 // Do nothing if the tag already has a name for linkage purposes.
4563 if (TagFromDeclSpec->hasNameForLinkage())
4564 return;
4565
4566 // A well-formed anonymous tag must always be a TUK_Definition.
4567 assert(TagFromDeclSpec->isThisDeclarationADefinition())(static_cast <bool> (TagFromDeclSpec->isThisDeclarationADefinition
()) ? void (0) : __assert_fail ("TagFromDeclSpec->isThisDeclarationADefinition()"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 4567, __extension__ __PRETTY_FUNCTION__))
;
4568
4569 // The type must match the tag exactly; no qualifiers allowed.
4570 if (!Context.hasSameType(NewTD->getUnderlyingType(),
4571 Context.getTagDeclType(TagFromDeclSpec))) {
4572 if (getLangOpts().CPlusPlus)
4573 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4574 return;
4575 }
4576
4577 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4578 // An unnamed class with a typedef name for linkage purposes shall [be
4579 // C-like].
4580 //
4581 // FIXME: Also diagnose if we've already computed the linkage. That ideally
4582 // shouldn't happen, but there are constructs that the language rule doesn't
4583 // disallow for which we can't reasonably avoid computing linkage early.
4584 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4585 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4586 : NonCLikeKind();
4587 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4588 if (NonCLike || ChangesLinkage) {
4589 if (NonCLike.Kind == NonCLikeKind::Invalid)
4590 return;
4591
4592 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4593 if (ChangesLinkage) {
4594 // If the linkage changes, we can't accept this as an extension.
4595 if (NonCLike.Kind == NonCLikeKind::None)
4596 DiagID = diag::err_typedef_changes_linkage;
4597 else
4598 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4599 }
4600
4601 SourceLocation FixitLoc =
4602 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4603 llvm::SmallString<40> TextToInsert;
4604 TextToInsert += ' ';
4605 TextToInsert += NewTD->getIdentifier()->getName();
4606
4607 Diag(FixitLoc, DiagID)
4608 << isa<TypeAliasDecl>(NewTD)
4609 << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4610 if (NonCLike.Kind != NonCLikeKind::None) {
4611 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4612 << NonCLike.Kind - 1 << NonCLike.Range;
4613 }
4614 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4615 << NewTD << isa<TypeAliasDecl>(NewTD);
4616
4617 if (ChangesLinkage)
4618 return;
4619 }
4620
4621 // Otherwise, set this as the anon-decl typedef for the tag.
4622 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4623}
4624
4625static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4626 switch (T) {
4627 case DeclSpec::TST_class:
4628 return 0;
4629 case DeclSpec::TST_struct:
4630 return 1;
4631 case DeclSpec::TST_interface:
4632 return 2;
4633 case DeclSpec::TST_union:
4634 return 3;
4635 case DeclSpec::TST_enum:
4636 return 4;
4637 default:
4638 llvm_unreachable("unexpected type specifier")::llvm::llvm_unreachable_internal("unexpected type specifier"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 4638)
;
4639 }
4640}
4641
4642/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4643/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4644/// parameters to cope with template friend declarations.
4645Decl *
4646Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4647 MultiTemplateParamsArg TemplateParams,
4648 bool IsExplicitInstantiation,
4649 RecordDecl *&AnonRecord) {
4650 Decl *TagD = nullptr;
4651 TagDecl *Tag = nullptr;
4652 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4653 DS.getTypeSpecType() == DeclSpec::TST_struct ||
4654 DS.getTypeSpecType() == DeclSpec::TST_interface ||
4655 DS.getTypeSpecType() == DeclSpec::TST_union ||
4656 DS.getTypeSpecType() == DeclSpec::TST_enum) {
4657 TagD = DS.getRepAsDecl();
4658
4659 if (!TagD) // We probably had an error
4660 return nullptr;
4661
4662 // Note that the above type specs guarantee that the
4663 // type rep is a Decl, whereas in many of the others
4664 // it's a Type.
4665 if (isa<TagDecl>(TagD))
4666 Tag = cast<TagDecl>(TagD);
4667 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4668 Tag = CTD->getTemplatedDecl();
4669 }
4670
4671 if (Tag) {
4672 handleTagNumbering(Tag, S);
4673 Tag->setFreeStanding();
4674 if (Tag->isInvalidDecl())
4675 return Tag;
4676 }
4677
4678 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4679 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4680 // or incomplete types shall not be restrict-qualified."
4681 if (TypeQuals & DeclSpec::TQ_restrict)
4682 Diag(DS.getRestrictSpecLoc(),
4683 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4684 << DS.getSourceRange();
4685 }
4686
4687 if (DS.isInlineSpecified())
4688 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4689 << getLangOpts().CPlusPlus17;
4690
4691 if (DS.hasConstexprSpecifier()) {
4692 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4693 // and definitions of functions and variables.
4694 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4695 // the declaration of a function or function template
4696 if (Tag)
4697 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4698 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4699 << static_cast<int>(DS.getConstexprSpecifier());
4700 else
4701 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4702 << static_cast<int>(DS.getConstexprSpecifier());
4703 // Don't emit warnings after this error.
4704 return TagD;
4705 }
4706
4707 DiagnoseFunctionSpecifiers(DS);
4708
4709 if (DS.isFriendSpecified()) {
4710 // If we're dealing with a decl but not a TagDecl, assume that
4711 // whatever routines created it handled the friendship aspect.
4712 if (TagD && !Tag)
4713 return nullptr;
4714 return ActOnFriendTypeDecl(S, DS, TemplateParams);
4715 }
4716
4717 const CXXScopeSpec &SS = DS.getTypeSpecScope();
4718 bool IsExplicitSpecialization =
4719 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4720 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4721 !IsExplicitInstantiation && !IsExplicitSpecialization &&
4722 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4723 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4724 // nested-name-specifier unless it is an explicit instantiation
4725 // or an explicit specialization.
4726 //
4727 // FIXME: We allow class template partial specializations here too, per the
4728 // obvious intent of DR1819.
4729 //
4730 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4731 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4732 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4733 return nullptr;
4734 }
4735
4736 // Track whether this decl-specifier declares anything.
4737 bool DeclaresAnything = true;
4738
4739 // Handle anonymous struct definitions.
4740 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4741 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4742 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4743 if (getLangOpts().CPlusPlus ||
4744 Record->getDeclContext()->isRecord()) {
4745 // If CurContext is a DeclContext that can contain statements,
4746 // RecursiveASTVisitor won't visit the decls that
4747 // BuildAnonymousStructOrUnion() will put into CurContext.
4748 // Also store them here so that they can be part of the
4749 // DeclStmt that gets created in this case.
4750 // FIXME: Also return the IndirectFieldDecls created by
4751 // BuildAnonymousStructOr union, for the same reason?
4752 if (CurContext->isFunctionOrMethod())
4753 AnonRecord = Record;
4754 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4755 Context.getPrintingPolicy());
4756 }
4757
4758 DeclaresAnything = false;
4759 }
4760 }
4761
4762 // C11 6.7.2.1p2:
4763 // A struct-declaration that does not declare an anonymous structure or
4764 // anonymous union shall contain a struct-declarator-list.
4765 //
4766 // This rule also existed in C89 and C99; the grammar for struct-declaration
4767 // did not permit a struct-declaration without a struct-declarator-list.
4768 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4769 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4770 // Check for Microsoft C extension: anonymous struct/union member.
4771 // Handle 2 kinds of anonymous struct/union:
4772 // struct STRUCT;
4773 // union UNION;
4774 // and
4775 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
4776 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
4777 if ((Tag && Tag->getDeclName()) ||
4778 DS.getTypeSpecType() == DeclSpec::TST_typename) {
4779 RecordDecl *Record = nullptr;
4780 if (Tag)
4781 Record = dyn_cast<RecordDecl>(Tag);
4782 else if (const RecordType *RT =
4783 DS.getRepAsType().get()->getAsStructureType())
4784 Record = RT->getDecl();
4785 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4786 Record = UT->getDecl();
4787
4788 if (Record && getLangOpts().MicrosoftExt) {
4789 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4790 << Record->isUnion() << DS.getSourceRange();
4791 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4792 }
4793
4794 DeclaresAnything = false;
4795 }
4796 }
4797
4798 // Skip all the checks below if we have a type error.
4799 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4800 (TagD && TagD->isInvalidDecl()))
4801 return TagD;
4802
4803 if (getLangOpts().CPlusPlus &&
4804 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4805 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4806 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4807 !Enum->getIdentifier() && !Enum->isInvalidDecl())
4808 DeclaresAnything = false;
4809
4810 if (!DS.isMissingDeclaratorOk()) {
4811 // Customize diagnostic for a typedef missing a name.
4812 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4813 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4814 << DS.getSourceRange();
4815 else
4816 DeclaresAnything = false;
4817 }
4818
4819 if (DS.isModulePrivateSpecified() &&
4820 Tag && Tag->getDeclContext()->isFunctionOrMethod())
4821 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4822 << Tag->getTagKind()
4823 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4824
4825 ActOnDocumentableDecl(TagD);
4826
4827 // C 6.7/2:
4828 // A declaration [...] shall declare at least a declarator [...], a tag,
4829 // or the members of an enumeration.
4830 // C++ [dcl.dcl]p3:
4831 // [If there are no declarators], and except for the declaration of an
4832 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
4833 // names into the program, or shall redeclare a name introduced by a
4834 // previous declaration.
4835 if (!DeclaresAnything) {
4836 // In C, we allow this as a (popular) extension / bug. Don't bother
4837 // producing further diagnostics for redundant qualifiers after this.
4838 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
4839 ? diag::err_no_declarators
4840 : diag::ext_no_declarators)
4841 << DS.getSourceRange();
4842 return TagD;
4843 }
4844
4845 // C++ [dcl.stc]p1:
4846 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4847 // init-declarator-list of the declaration shall not be empty.
4848 // C++ [dcl.fct.spec]p1:
4849 // If a cv-qualifier appears in a decl-specifier-seq, the
4850 // init-declarator-list of the declaration shall not be empty.
4851 //
4852 // Spurious qualifiers here appear to be valid in C.
4853 unsigned DiagID = diag::warn_standalone_specifier;
4854 if (getLangOpts().CPlusPlus)
4855 DiagID = diag::ext_standalone_specifier;
4856
4857 // Note that a linkage-specification sets a storage class, but
4858 // 'extern "C" struct foo;' is actually valid and not theoretically
4859 // useless.
4860 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4861 if (SCS == DeclSpec::SCS_mutable)
4862 // Since mutable is not a viable storage class specifier in C, there is
4863 // no reason to treat it as an extension. Instead, diagnose as an error.
4864 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4865 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4866 Diag(DS.getStorageClassSpecLoc(), DiagID)
4867 << DeclSpec::getSpecifierName(SCS);
4868 }
4869
4870 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4871 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4872 << DeclSpec::getSpecifierName(TSCS);
4873 if (DS.getTypeQualifiers()) {
4874 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4875 Diag(DS.getConstSpecLoc(), DiagID) << "const";
4876 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4877 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4878 // Restrict is covered above.
4879 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4880 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4881 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4882 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4883 }
4884
4885 // Warn about ignored type attributes, for example:
4886 // __attribute__((aligned)) struct A;
4887 // Attributes should be placed after tag to apply to type declaration.
4888 if (!DS.getAttributes().empty()) {
4889 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4890 if (TypeSpecType == DeclSpec::TST_class ||
4891 TypeSpecType == DeclSpec::TST_struct ||
4892 TypeSpecType == DeclSpec::TST_interface ||
4893 TypeSpecType == DeclSpec::TST_union ||
4894 TypeSpecType == DeclSpec::TST_enum) {
4895 for (const ParsedAttr &AL : DS.getAttributes())
4896 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4897 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
4898 }
4899 }
4900
4901 return TagD;
4902}
4903
4904/// We are trying to inject an anonymous member into the given scope;
4905/// check if there's an existing declaration that can't be overloaded.
4906///
4907/// \return true if this is a forbidden redeclaration
4908static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4909 Scope *S,
4910 DeclContext *Owner,
4911 DeclarationName Name,
4912 SourceLocation NameLoc,
4913 bool IsUnion) {
4914 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4915 Sema::ForVisibleRedeclaration);
4916 if (!SemaRef.LookupName(R, S)) return false;
4917
4918 // Pick a representative declaration.
4919 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4920 assert(PrevDecl && "Expected a non-null Decl")(static_cast <bool> (PrevDecl && "Expected a non-null Decl"
) ? void (0) : __assert_fail ("PrevDecl && \"Expected a non-null Decl\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 4920, __extension__ __PRETTY_FUNCTION__))
;
4921
4922 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4923 return false;
4924
4925 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4926 << IsUnion << Name;
4927 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4928
4929 return true;
4930}
4931
4932/// InjectAnonymousStructOrUnionMembers - Inject the members of the
4933/// anonymous struct or union AnonRecord into the owning context Owner
4934/// and scope S. This routine will be invoked just after we realize
4935/// that an unnamed union or struct is actually an anonymous union or
4936/// struct, e.g.,
4937///
4938/// @code
4939/// union {
4940/// int i;
4941/// float f;
4942/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4943/// // f into the surrounding scope.x
4944/// @endcode
4945///
4946/// This routine is recursive, injecting the names of nested anonymous
4947/// structs/unions into the owning context and scope as well.
4948static bool
4949InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4950 RecordDecl *AnonRecord, AccessSpecifier AS,
4951 SmallVectorImpl<NamedDecl *> &Chaining) {
4952 bool Invalid = false;
4953
4954 // Look every FieldDecl and IndirectFieldDecl with a name.
4955 for (auto *D : AnonRecord->decls()) {
4956 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4957 cast<NamedDecl>(D)->getDeclName()) {
4958 ValueDecl *VD = cast<ValueDecl>(D);
4959 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4960 VD->getLocation(),
4961 AnonRecord->isUnion())) {
4962 // C++ [class.union]p2:
4963 // The names of the members of an anonymous union shall be
4964 // distinct from the names of any other entity in the
4965 // scope in which the anonymous union is declared.
4966 Invalid = true;
4967 } else {
4968 // C++ [class.union]p2:
4969 // For the purpose of name lookup, after the anonymous union
4970 // definition, the members of the anonymous union are
4971 // considered to have been defined in the scope in which the
4972 // anonymous union is declared.
4973 unsigned OldChainingSize = Chaining.size();
4974 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4975 Chaining.append(IF->chain_begin(), IF->chain_end());
4976 else
4977 Chaining.push_back(VD);
4978
4979 assert(Chaining.size() >= 2)(static_cast <bool> (Chaining.size() >= 2) ? void (0
) : __assert_fail ("Chaining.size() >= 2", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 4979, __extension__ __PRETTY_FUNCTION__))
;
4980 NamedDecl **NamedChain =
4981 new (SemaRef.Context)NamedDecl*[Chaining.size()];
4982 for (unsigned i = 0; i < Chaining.size(); i++)
4983 NamedChain[i] = Chaining[i];
4984
4985 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4986 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4987 VD->getType(), {NamedChain, Chaining.size()});
4988
4989 for (const auto *Attr : VD->attrs())
4990 IndirectField->addAttr(Attr->clone(SemaRef.Context));
4991
4992 IndirectField->setAccess(AS);
4993 IndirectField->setImplicit();
4994 SemaRef.PushOnScopeChains(IndirectField, S);
4995
4996 // That includes picking up the appropriate access specifier.
4997 if (AS != AS_none) IndirectField->setAccess(AS);
4998
4999 Chaining.resize(OldChainingSize);
5000 }
5001 }
5002 }
5003
5004 return Invalid;
5005}
5006
5007/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5008/// a VarDecl::StorageClass. Any error reporting is up to the caller:
5009/// illegal input values are mapped to SC_None.
5010static StorageClass
5011StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5012 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5013 assert(StorageClassSpec != DeclSpec::SCS_typedef &&(static_cast <bool> (StorageClassSpec != DeclSpec::SCS_typedef
&& "Parser allowed 'typedef' as storage class VarDecl."
) ? void (0) : __assert_fail ("StorageClassSpec != DeclSpec::SCS_typedef && \"Parser allowed 'typedef' as storage class VarDecl.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 5014, __extension__ __PRETTY_FUNCTION__))
5014 "Parser allowed 'typedef' as storage class VarDecl.")(static_cast <bool> (StorageClassSpec != DeclSpec::SCS_typedef
&& "Parser allowed 'typedef' as storage class VarDecl."
) ? void (0) : __assert_fail ("StorageClassSpec != DeclSpec::SCS_typedef && \"Parser allowed 'typedef' as storage class VarDecl.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 5014, __extension__ __PRETTY_FUNCTION__))
;
5015 switch (StorageClassSpec) {
5016 case DeclSpec::SCS_unspecified: return SC_None;
5017 case DeclSpec::SCS_extern:
5018 if (DS.isExternInLinkageSpec())
5019 return SC_None;
5020 return SC_Extern;
5021 case DeclSpec::SCS_static: return SC_Static;
5022 case DeclSpec::SCS_auto: return SC_Auto;
5023 case DeclSpec::SCS_register: return SC_Register;
5024 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5025 // Illegal SCSs map to None: error reporting is up to the caller.
5026 case DeclSpec::SCS_mutable: // Fall through.
5027 case DeclSpec::SCS_typedef: return SC_None;
5028 }
5029 llvm_unreachable("unknown storage class specifier")::llvm::llvm_unreachable_internal("unknown storage class specifier"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 5029)
;
5030}
5031
5032static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5033 assert(Record->hasInClassInitializer())(static_cast <bool> (Record->hasInClassInitializer()
) ? void (0) : __assert_fail ("Record->hasInClassInitializer()"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 5033, __extension__ __PRETTY_FUNCTION__))
;
5034
5035 for (const auto *I : Record->decls()) {
5036 const auto *FD = dyn_cast<FieldDecl>(I);
5037 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5038 FD = IFD->getAnonField();
5039 if (FD && FD->hasInClassInitializer())
5040 return FD->getLocation();
5041 }
5042
5043 llvm_unreachable("couldn't find in-class initializer")::llvm::llvm_unreachable_internal("couldn't find in-class initializer"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 5043)
;
5044}
5045
5046static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5047 SourceLocation DefaultInitLoc) {
5048 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5049 return;
5050
5051 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5052 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5053}
5054
5055static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5056 CXXRecordDecl *AnonUnion) {
5057 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5058 return;
5059
5060 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
5061}
5062
5063/// BuildAnonymousStructOrUnion - Handle the declaration of an
5064/// anonymous structure or union. Anonymous unions are a C++ feature
5065/// (C++ [class.union]) and a C11 feature; anonymous structures
5066/// are a C11 feature and GNU C++ extension.
5067Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5068 AccessSpecifier AS,
5069 RecordDecl *Record,
5070 const PrintingPolicy &Policy) {
5071 DeclContext *Owner = Record->getDeclContext();
5072
5073 // Diagnose whether this anonymous struct/union is an extension.
5074 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5075 Diag(Record->getLocation(), diag::ext_anonymous_union);
5076 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5077 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5078 else if (!Record->isUnion() && !getLangOpts().C11)
5079 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5080
5081 // C and C++ require different kinds of checks for anonymous
5082 // structs/unions.
5083 bool Invalid = false;
5084 if (getLangOpts().CPlusPlus) {
5085 const char *PrevSpec = nullptr;
5086 if (Record->isUnion()) {
5087 // C++ [class.union]p6:
5088 // C++17 [class.union.anon]p2:
5089 // Anonymous unions declared in a named namespace or in the
5090 // global namespace shall be declared static.
5091 unsigned DiagID;
5092 DeclContext *OwnerScope = Owner->getRedeclContext();
5093 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5094 (OwnerScope->isTranslationUnit() ||
5095 (OwnerScope->isNamespace() &&
5096 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5097 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5098 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5099
5100 // Recover by adding 'static'.
5101 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5102 PrevSpec, DiagID, Policy);
5103 }
5104 // C++ [class.union]p6:
5105 // A storage class is not allowed in a declaration of an
5106 // anonymous union in a class scope.
5107 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5108 isa<RecordDecl>(Owner)) {
5109 Diag(DS.getStorageClassSpecLoc(),
5110 diag::err_anonymous_union_with_storage_spec)
5111 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5112
5113 // Recover by removing the storage specifier.
5114 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5115 SourceLocation(),
5116 PrevSpec, DiagID, Context.getPrintingPolicy());
5117 }
5118 }
5119
5120 // Ignore const/volatile/restrict qualifiers.
5121 if (DS.getTypeQualifiers()) {
5122 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5123 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5124 << Record->isUnion() << "const"
5125 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5126 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5127 Diag(DS.getVolatileSpecLoc(),
5128 diag::ext_anonymous_struct_union_qualified)
5129 << Record->isUnion() << "volatile"
5130 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5131 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5132 Diag(DS.getRestrictSpecLoc(),
5133 diag::ext_anonymous_struct_union_qualified)
5134 << Record->isUnion() << "restrict"
5135 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5136 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5137 Diag(DS.getAtomicSpecLoc(),
5138 diag::ext_anonymous_struct_union_qualified)
5139 << Record->isUnion() << "_Atomic"
5140 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5141 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5142 Diag(DS.getUnalignedSpecLoc(),
5143 diag::ext_anonymous_struct_union_qualified)
5144 << Record->isUnion() << "__unaligned"
5145 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5146
5147 DS.ClearTypeQualifiers();
5148 }
5149
5150 // C++ [class.union]p2:
5151 // The member-specification of an anonymous union shall only
5152 // define non-static data members. [Note: nested types and
5153 // functions cannot be declared within an anonymous union. ]
5154 for (auto *Mem : Record->decls()) {
5155 // Ignore invalid declarations; we already diagnosed them.
5156 if (Mem->isInvalidDecl())
5157 continue;
5158
5159 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5160 // C++ [class.union]p3:
5161 // An anonymous union shall not have private or protected
5162 // members (clause 11).
5163 assert(FD->getAccess() != AS_none)(static_cast <bool> (FD->getAccess() != AS_none) ? void
(0) : __assert_fail ("FD->getAccess() != AS_none", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 5163, __extension__ __PRETTY_FUNCTION__))
;
5164 if (FD->getAccess() != AS_public) {
5165 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5166 << Record->isUnion() << (FD->getAccess() == AS_protected);
5167 Invalid = true;
5168 }
5169
5170 // C++ [class.union]p1
5171 // An object of a class with a non-trivial constructor, a non-trivial
5172 // copy constructor, a non-trivial destructor, or a non-trivial copy
5173 // assignment operator cannot be a member of a union, nor can an
5174 // array of such objects.
5175 if (CheckNontrivialField(FD))
5176 Invalid = true;
5177 } else if (Mem->isImplicit()) {
5178 // Any implicit members are fine.
5179 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5180 // This is a type that showed up in an
5181 // elaborated-type-specifier inside the anonymous struct or
5182 // union, but which actually declares a type outside of the
5183 // anonymous struct or union. It's okay.
5184 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5185 if (!MemRecord->isAnonymousStructOrUnion() &&
5186 MemRecord->getDeclName()) {
5187 // Visual C++ allows type definition in anonymous struct or union.
5188 if (getLangOpts().MicrosoftExt)
5189 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5190 << Record->isUnion();
5191 else {
5192 // This is a nested type declaration.
5193 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5194 << Record->isUnion();
5195 Invalid = true;
5196 }
5197 } else {
5198 // This is an anonymous type definition within another anonymous type.
5199 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5200 // not part of standard C++.
5201 Diag(MemRecord->getLocation(),
5202 diag::ext_anonymous_record_with_anonymous_type)
5203 << Record->isUnion();
5204 }
5205 } else if (isa<AccessSpecDecl>(Mem)) {
5206 // Any access specifier is fine.
5207 } else if (isa<StaticAssertDecl>(Mem)) {
5208 // In C++1z, static_assert declarations are also fine.
5209 } else {
5210 // We have something that isn't a non-static data
5211 // member. Complain about it.
5212 unsigned DK = diag::err_anonymous_record_bad_member;
5213 if (isa<TypeDecl>(Mem))
5214 DK = diag::err_anonymous_record_with_type;
5215 else if (isa<FunctionDecl>(Mem))
5216 DK = diag::err_anonymous_record_with_function;
5217 else if (isa<VarDecl>(Mem))
5218 DK = diag::err_anonymous_record_with_static;
5219
5220 // Visual C++ allows type definition in anonymous struct or union.
5221 if (getLangOpts().MicrosoftExt &&
5222 DK == diag::err_anonymous_record_with_type)
5223 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5224 << Record->isUnion();
5225 else {
5226 Diag(Mem->getLocation(), DK) << Record->isUnion();
5227 Invalid = true;
5228 }
5229 }
5230 }
5231
5232 // C++11 [class.union]p8 (DR1460):
5233 // At most one variant member of a union may have a
5234 // brace-or-equal-initializer.
5235 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5236 Owner->isRecord())
5237 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5238 cast<CXXRecordDecl>(Record));
5239 }
5240
5241 if (!Record->isUnion() && !Owner->isRecord()) {
5242 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5243 << getLangOpts().CPlusPlus;
5244 Invalid = true;
5245 }
5246
5247 // C++ [dcl.dcl]p3:
5248 // [If there are no declarators], and except for the declaration of an
5249 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5250 // names into the program
5251 // C++ [class.mem]p2:
5252 // each such member-declaration shall either declare at least one member
5253 // name of the class or declare at least one unnamed bit-field
5254 //
5255 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5256 if (getLangOpts().CPlusPlus && Record->field_empty())
5257 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5258
5259 // Mock up a declarator.
5260 Declarator Dc(DS, DeclaratorContext::Member);
5261 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5262 assert(TInfo && "couldn't build declarator info for anonymous struct/union")(static_cast <bool> (TInfo && "couldn't build declarator info for anonymous struct/union"
) ? void (0) : __assert_fail ("TInfo && \"couldn't build declarator info for anonymous struct/union\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 5262, __extension__ __PRETTY_FUNCTION__))
;
5263
5264 // Create a declaration for this anonymous struct/union.
5265 NamedDecl *Anon = nullptr;
5266 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5267 Anon = FieldDecl::Create(
5268 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5269 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5270 /*BitWidth=*/nullptr, /*Mutable=*/false,
5271 /*InitStyle=*/ICIS_NoInit);
5272 Anon->setAccess(AS);
5273 ProcessDeclAttributes(S, Anon, Dc);
5274
5275 if (getLangOpts().CPlusPlus)
5276 FieldCollector->Add(cast<FieldDecl>(Anon));
5277 } else {
5278 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5279 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5280 if (SCSpec == DeclSpec::SCS_mutable) {
5281 // mutable can only appear on non-static class members, so it's always
5282 // an error here
5283 Diag(Record->getLocation(), diag::err_mutable_nonmember);
5284 Invalid = true;
5285 SC = SC_None;
5286 }
5287
5288 assert(DS.getAttributes().empty() && "No attribute expected")(static_cast <bool> (DS.getAttributes().empty() &&
"No attribute expected") ? void (0) : __assert_fail ("DS.getAttributes().empty() && \"No attribute expected\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 5288, __extension__ __PRETTY_FUNCTION__))
;
5289 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5290 Record->getLocation(), /*IdentifierInfo=*/nullptr,
5291 Context.getTypeDeclType(Record), TInfo, SC);
5292
5293 // Default-initialize the implicit variable. This initialization will be
5294 // trivial in almost all cases, except if a union member has an in-class
5295 // initializer:
5296 // union { int n = 0; };
5297 if (!Invalid)
5298 ActOnUninitializedDecl(Anon);
5299 }
5300 Anon->setImplicit();
5301
5302 // Mark this as an anonymous struct/union type.
5303 Record->setAnonymousStructOrUnion(true);
5304
5305 // Add the anonymous struct/union object to the current
5306 // context. We'll be referencing this object when we refer to one of
5307 // its members.
5308 Owner->addDecl(Anon);
5309
5310 // Inject the members of the anonymous struct/union into the owning
5311 // context and into the identifier resolver chain for name lookup
5312 // purposes.
5313 SmallVector<NamedDecl*, 2> Chain;
5314 Chain.push_back(Anon);
5315
5316 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5317 Invalid = true;
5318
5319 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5320 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5321 MangleNumberingContext *MCtx;
5322 Decl *ManglingContextDecl;
5323 std::tie(MCtx, ManglingContextDecl) =
5324 getCurrentMangleNumberContext(NewVD->getDeclContext());
5325 if (MCtx) {
5326 Context.setManglingNumber(
5327 NewVD, MCtx->getManglingNumber(
5328 NewVD, getMSManglingNumber(getLangOpts(), S)));
5329 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5330 }
5331 }
5332 }
5333
5334 if (Invalid)
5335 Anon->setInvalidDecl();
5336
5337 return Anon;
5338}
5339
5340/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5341/// Microsoft C anonymous structure.
5342/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5343/// Example:
5344///
5345/// struct A { int a; };
5346/// struct B { struct A; int b; };
5347///
5348/// void foo() {
5349/// B var;
5350/// var.a = 3;
5351/// }
5352///
5353Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5354 RecordDecl *Record) {
5355 assert(Record && "expected a record!")(static_cast <bool> (Record && "expected a record!"
) ? void (0) : __assert_fail ("Record && \"expected a record!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 5355, __extension__ __PRETTY_FUNCTION__))
;
5356
5357 // Mock up a declarator.
5358 Declarator Dc(DS, DeclaratorContext::TypeName);
5359 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5360 assert(TInfo && "couldn't build declarator info for anonymous struct")(static_cast <bool> (TInfo && "couldn't build declarator info for anonymous struct"
) ? void (0) : __assert_fail ("TInfo && \"couldn't build declarator info for anonymous struct\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 5360, __extension__ __PRETTY_FUNCTION__))
;
5361
5362 auto *ParentDecl = cast<RecordDecl>(CurContext);
5363 QualType RecTy = Context.getTypeDeclType(Record);
5364
5365 // Create a declaration for this anonymous struct.
5366 NamedDecl *Anon =
5367 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5368 /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5369 /*BitWidth=*/nullptr, /*Mutable=*/false,
5370 /*InitStyle=*/ICIS_NoInit);
5371 Anon->setImplicit();
5372
5373 // Add the anonymous struct object to the current context.
5374 CurContext->addDecl(Anon);
5375
5376 // Inject the members of the anonymous struct into the current
5377 // context and into the identifier resolver chain for name lookup
5378 // purposes.
5379 SmallVector<NamedDecl*, 2> Chain;
5380 Chain.push_back(Anon);
5381
5382 RecordDecl *RecordDef = Record->getDefinition();
5383 if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5384 diag::err_field_incomplete_or_sizeless) ||
5385 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5386 AS_none, Chain)) {
5387 Anon->setInvalidDecl();
5388 ParentDecl->setInvalidDecl();
5389 }
5390
5391 return Anon;
5392}
5393
5394/// GetNameForDeclarator - Determine the full declaration name for the
5395/// given Declarator.
5396DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5397 return GetNameFromUnqualifiedId(D.getName());
9
Returning without writing to 'D.Redeclaration', which participates in a condition later
20
Returning without writing to 'D.Redeclaration', which participates in a condition later
5398}
5399
5400/// Retrieves the declaration name from a parsed unqualified-id.
5401DeclarationNameInfo
5402Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5403 DeclarationNameInfo NameInfo;
5404 NameInfo.setLoc(Name.StartLocation);
5405
5406 switch (Name.getKind()) {
5407
5408 case UnqualifiedIdKind::IK_ImplicitSelfParam:
5409 case UnqualifiedIdKind::IK_Identifier:
5410 NameInfo.setName(Name.Identifier);
5411 return NameInfo;
5412
5413 case UnqualifiedIdKind::IK_DeductionGuideName: {
5414 // C++ [temp.deduct.guide]p3:
5415 // The simple-template-id shall name a class template specialization.
5416 // The template-name shall be the same identifier as the template-name
5417 // of the simple-template-id.
5418 // These together intend to imply that the template-name shall name a
5419 // class template.
5420 // FIXME: template<typename T> struct X {};
5421 // template<typename T> using Y = X<T>;
5422 // Y(int) -> Y<int>;
5423 // satisfies these rules but does not name a class template.
5424 TemplateName TN = Name.TemplateName.get().get();
5425 auto *Template = TN.getAsTemplateDecl();
5426 if (!Template || !isa<ClassTemplateDecl>(Template)) {
5427 Diag(Name.StartLocation,
5428 diag::err_deduction_guide_name_not_class_template)
5429 << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5430 if (Template)
5431 Diag(Template->getLocation(), diag::note_template_decl_here);
5432 return DeclarationNameInfo();
5433 }
5434
5435 NameInfo.setName(
5436 Context.DeclarationNames.getCXXDeductionGuideName(Template));
5437 return NameInfo;
5438 }
5439
5440 case UnqualifiedIdKind::IK_OperatorFunctionId:
5441 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5442 Name.OperatorFunctionId.Operator));
5443 NameInfo.setCXXOperatorNameRange(SourceRange(
5444 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5445 return NameInfo;
5446
5447 case UnqualifiedIdKind::IK_LiteralOperatorId:
5448 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5449 Name.Identifier));
5450 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5451 return NameInfo;
5452
5453 case UnqualifiedIdKind::IK_ConversionFunctionId: {
5454 TypeSourceInfo *TInfo;
5455 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5456 if (Ty.isNull())
5457 return DeclarationNameInfo();
5458 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5459 Context.getCanonicalType(Ty)));
5460 NameInfo.setNamedTypeInfo(TInfo);
5461 return NameInfo;
5462 }
5463
5464 case UnqualifiedIdKind::IK_ConstructorName: {
5465 TypeSourceInfo *TInfo;
5466 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5467 if (Ty.isNull())
5468 return DeclarationNameInfo();
5469 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5470 Context.getCanonicalType(Ty)));
5471 NameInfo.setNamedTypeInfo(TInfo);
5472 return NameInfo;
5473 }
5474
5475 case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5476 // In well-formed code, we can only have a constructor
5477 // template-id that refers to the current context, so go there
5478 // to find the actual type being constructed.
5479 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5480 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5481 return DeclarationNameInfo();
5482
5483 // Determine the type of the class being constructed.
5484 QualType CurClassType = Context.getTypeDeclType(CurClass);
5485
5486 // FIXME: Check two things: that the template-id names the same type as
5487 // CurClassType, and that the template-id does not occur when the name
5488 // was qualified.
5489
5490 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5491 Context.getCanonicalType(CurClassType)));
5492 // FIXME: should we retrieve TypeSourceInfo?
5493 NameInfo.setNamedTypeInfo(nullptr);
5494 return NameInfo;
5495 }
5496
5497 case UnqualifiedIdKind::IK_DestructorName: {
5498 TypeSourceInfo *TInfo;
5499 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5500 if (Ty.isNull())
5501 return DeclarationNameInfo();
5502 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5503 Context.getCanonicalType(Ty)));
5504 NameInfo.setNamedTypeInfo(TInfo);
5505 return NameInfo;
5506 }
5507
5508 case UnqualifiedIdKind::IK_TemplateId: {
5509 TemplateName TName = Name.TemplateId->Template.get();
5510 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5511 return Context.getNameForTemplate(TName, TNameLoc);
5512 }
5513
5514 } // switch (Name.getKind())
5515
5516 llvm_unreachable("Unknown name kind")::llvm::llvm_unreachable_internal("Unknown name kind", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaDecl.cpp"
, 5516)
;
5517}
5518
5519static QualType getCoreType(QualType Ty) {
5520 do {
5521 if (Ty->isPointerType() || Ty->isReferenceType())
5522 Ty = Ty->getPointeeType();
5523 else if (Ty->isArrayType())
5524 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5525 else
5526 return Ty.withoutLocalFastQualifiers();
5527 } while (true);
5528}
5529
5530/// hasSimilarParameters - Determine whether the C++ functions Declaration
5531/// and Definition have "nearly" matching parameters. This heuristic is
5532/// used to improve diagnostics in the case where an out-of-line function
5533/// definition doesn't match any declaration within the class or namespace.
5534/// Also sets Params to the list of indices to the parameters that differ
5535/// between the declaration and the definition. If hasSimilarParameters
5536/// returns true and Params is empty, then all of the parameters match.
5537static bool hasSimilarParameters(ASTContext &Context,
5538 FunctionDecl *Declaration,
5539 FunctionDecl *Definition,
5540 SmallVectorImpl<unsigned> &Params) {
5541 Params.clear();
5542 if (Declaration->param_size() != Definition->param_size())
5543 return false;
5544 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5545 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5546 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5547
5548 // The parameter types are identical
5549 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5550 continue;
5551
5552 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5553 QualType DefParamBaseTy = getCoreType(DefParamTy);
5554 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5555 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5556
5557 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5558 (DeclTyName && DeclTyName == DefTyName))
5559 Params.push_back(Idx);
5560 else // The two parameters aren't even close
5561 return false;
5562 }
5563
5564 return true;
5565}
5566
5567/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5568/// declarator needs to be rebuilt in the current instantiation.
5569/// Any bits of declarator which appear before the name are valid for
5570/// consideration here. That's specifically the type in the decl spec
5571/// and the base type in any member-pointer chunks.
5572static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5573 DeclarationName Name) {
5574 // The types we specifically need to rebuild are:
5575 // - typenames, typeofs, and decltypes
5576 // - types which will become injected class names
5577 // Of course, we also need to rebuild any type referencing such a
5578 // type. It's safest to just say "dependent", but we call out a
5579 // few cases here.
5580
5581 DeclSpec &DS = D.getMutableDeclSpec();
5582 switch (DS.getTypeSpecType()) {
5583 case DeclSpec::TST_typename:
5584 case DeclSpec::TST_typeofType:
5585 case DeclSpec::TST_underlyingType:
5586 case DeclSpec::TST_atomic: {
5587 // Grab the type from the parser.
5588 TypeSourceInfo *TSI = nullptr;
5589 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5590 if (T.isNull() || !T->isInstantiationDependentType()) break;
5591
5592 // Make sure there's a type source info. This isn't really much
5593 // of a waste; most dependent types should have type source info
5594 // attached already.
5595 if (!TSI)
5596 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5597
5598 // Rebuild the type in the current instantiation.
5599 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5600 if (!TSI) return true;
5601
5602 // Store the new type back in the decl spec.
5603 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5604 DS.UpdateTypeRep(LocType);
5605 break;
5606 }
5607
5608 case DeclSpec::TST_decltype:
5609 case DeclSpec::TST_typeofExpr: {
5610 Expr *E = DS.getRepAsExpr();
5611 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5612 if (Result.isInvalid()) return true;
5613 DS.UpdateExprRep(Result.get());
5614 break;
5615 }
5616
5617 default:
5618 // Nothing to do for these decl specs.
5619 break;
5620 }
5621
5622 // It doesn't matter what order we do this in.
5623 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5624 DeclaratorChunk &Chunk = D.getTypeObject(I);
5625
5626 // The only type information in the declarator which can come
5627 // before the declaration name is the base type of a member
5628 // pointer.
5629 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5630 continue;
5631
5632 // Rebuild the scope specifier in-place.
5633 CXXScopeSpec &SS = Chunk.Mem.Scope();
5634 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5635 return true;
5636 }
5637
5638 return false;
5639}
5640
5641void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
5642 // Avoid warning twice on the same identifier, and don't warn on redeclaration
5643 // of system decl.
5644 if (D->getPreviousDecl() || D->isImplicit())
5645 return;
5646 ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
5647 if (Status != ReservedIdentifierStatus::NotReserved &&
5648 !Context.getSourceManager().isInSystemHeader(D->getLocation()))
5649 Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
5650 << D << static_cast<int>(Status);
5651}
5652
5653Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5654 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
5655 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5656
5657 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5658 Dcl && Dcl->getDeclContext()->isFileContext())
5659 Dcl->setTopLevelDeclInObjCContainer();
5660
5661 return Dcl;
5662}
5663
5664/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5665/// If T is the name of a class, then each of the following shall have a
5666/// name different from T:
5667/// - every static data member of class T;
5668/// - every member function of class T
5669/// - every member of class T that is itself a type;
5670/// \returns true if the declaration name violates these rules.
5671bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5672 DeclarationNameInfo NameInfo) {
5673 DeclarationName Name = NameInfo.getName();
5674
5675 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5676 while (Record && Record->isAnonymousStructOrUnion())
5677 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5678 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5679 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5680 return true;
5681 }
5682
5683 return false;
5684}
5685
5686/// Diagnose a declaration whose declarator-id has the given
5687/// nested-name-specifier.
5688///
5689/// \param SS The nested-name-specifier of the declarator-id.
5690///
5691/// \param DC The declaration context to which the nested-name-specifier
5692/// resolves.
5693///
5694/// \param Name The name of the entity being declared.
5695///
5696/// \param Loc The location of the name of the entity being declared.
5697///
5698/// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5699/// we're declaring an explicit / partial specialization / instantiation.
5700///
5701/// \returns true if we cannot safely recover from this error, false otherwise.
5702bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5703 DeclarationName Name,
5704 SourceLocation Loc, bool IsTemplateId) {
5705 DeclContext *Cur = CurContext;
5706 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5707 Cur = Cur->getParent();
5708
5709 // If the user provided a superfluous scope specifier that refers back to the
5710 // class in which the entity is already declared, diagnose and ignore it.
5711 //
5712 // class X {
5713 // void X::f();
5714 // };
5715 //
5716 // Note, it was once ill-formed to give redundant qualification in all
5717 // contexts, but that rule was removed by DR482.
5718 if (Cur->Equals(DC)) {
5719 if (Cur->isRecord()) {
5720 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5721 : diag::err_member_extra_qualification)
5722 << Name << FixItHint::CreateRemoval(SS.getRange());
5723 SS.clear();
5724 } else {
5725 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5726 }
5727 return false;
5728 }
5729
5730 // Check whether the qualifying scope encloses the scope of the original
5731 // declaration. For a template-id, we perform the checks in
5732 // CheckTemplateSpecializationScope.
5733 if (!Cur->Encloses(DC) && !IsTemplateId) {
5734 if (Cur->isRecord())
5735 Diag(Loc, diag::err_member_qualification)
5736 << Name << SS.getRange();
5737 else if (isa<TranslationUnitDecl>(DC))
5738 Diag(Loc, diag::err_invalid_declarator_global_scope)
5739 << Name << SS.getRange();
5740 else if (isa<FunctionDecl>(Cur))
5741 Diag(Loc, diag::err_invalid_declarator_in_function)
5742 << Name << SS.getRange();
5743 else if (isa<BlockDecl>(Cur))
5744 Diag(Loc, diag::err_invalid_declarator_in_block)
5745 << Name << SS.getRange();
5746 else
5747 Diag(Loc, diag::err_invalid_declarator_scope)
5748 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5749
5750 return true;
5751 }
5752
5753 if (Cur->isRecord()) {
5754 // Cannot qualify members within a class.
5755 Diag(Loc, diag::err_member_qualification)
5756 << Name << SS.getRange();
5757 SS.clear();
5758
5759 // C++ constructors and destructors with incorrect scopes can break
5760 // our AST invariants by having the wrong underlying types. If
5761 // that's the case, then drop this declaration entirely.
5762 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5763 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5764 !Context.hasSameType(Name.getCXXNameType(),
5765 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5766 return true;
5767
5768 return false;
5769 }
5770
5771 // C++11 [dcl.meaning]p1:
5772 // [...] "The nested-name-specifier of the qualified declarator-id shall
5773 // not begin with a decltype-specifer"
5774 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5775 while (SpecLoc.getPrefix())
5776 SpecLoc = SpecLoc.getPrefix();
5777 if (dyn_cast_or_null<DecltypeType>(
5778 SpecLoc.getNestedNameSpecifier()->getAsType()))
5779 Diag(Loc, diag::err_decltype_in_declarator)
5780 << SpecLoc.getTypeLoc().getSourceRange();
5781
5782 return false;
5783}
5784
5785NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5786 MultiTemplateParamsArg TemplateParamLists) {
5787 // TODO: consider using NameInfo for diagnostic.
5788 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5789 DeclarationName Name = NameInfo.getName();
5790
5791 // All of these full declarators require an identifier. If it doesn't have
5792 // one, the ParsedFreeStandingDeclSpec action should be used.
5793 if (D.isDecompositionDeclarator()) {
5794 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5795 } else if (!Name) {
5796 if (!D.isInvalidType()) // Reject this if we think it is valid.
5797 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5798 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5799 return nullptr;
5800 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5801 return nullptr;
5802
5803 // The scope passed in may not be a decl scope. Zip up the scope tree until
5804 // we find one that is.
5805 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5806 (S->getFlags() & Scope::TemplateParamScope) != 0)
5807 S = S->getParent();
5808
5809 DeclContext *DC = CurContext;
5810 if (D.getCXXScopeSpec().isInvalid())
5811 D.setInvalidType();
5812 else if (D.getCXXScopeSpec().isSet()) {
5813 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5814 UPPC_DeclarationQualifier))
5815 return nullptr;
5816
5817 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5818 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5819 if (!DC || isa<EnumDecl>(DC)) {
5820 // If we could not compute the declaration context, it's because the
5821 // declaration context is dependent but does not refer to a class,
5822 // class template, or class template partial specialization. Complain
5823 // and return early, to avoid the coming semantic disaster.
5824 Diag(D.getIdentifierLoc(),
5825 diag::err_template_qualified_declarator_no_match)
5826 << D.getCXXScopeSpec().getScopeRep()
5827 << D.getCXXScopeSpec().getRange();
5828 return nullptr;
5829 }
5830 bool IsDependentContext = DC->isDependentContext();
5831
5832 if (!IsDependentContext &&
5833 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5834 return nullptr;
5835
5836 // If a class is incomplete, do not parse entities inside it.
5837 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5838 Diag(D.getIdentifierLoc(),
5839 diag::err_member_def_undefined_record)
5840 << Name << DC << D.getCXXScopeSpec().getRange();
5841 return nullptr;
5842 }
5843 if (!D.getDeclSpec().isFriendSpecified()) {
5844 if (diagnoseQualifiedDeclaration(
5845 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5846 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5847 if (DC->isRecord())
5848 return nullptr;
5849
5850 D.setInvalidType();
5851 }
5852 }
5853
5854 // Check whether we need to rebuild the type of the given
5855 // declaration in the current instantiation.
5856 if (EnteringContext && IsDependentContext &&
5857 TemplateParamLists.size() != 0) {
5858 ContextRAII SavedContext(*this, DC);
5859 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5860 D.setInvalidType();
5861 }
5862 }
5863
5864 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5865 QualType R = TInfo->getType();
5866
5867 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5868 UPPC_DeclarationType))
5869 D.setInvalidType();
5870
5871 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5872 forRedeclarationInCurContext());
5873
5874