Bug Summary

File:clang/lib/Sema/SemaDecl.cpp
Warning:line 3767, column 35
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~++20210825111122+868bd9938db1/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~++20210825111122+868bd9938db1/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema -I /build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/include -I /build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/build-llvm/include -I /build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/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~++20210825111122+868bd9938db1/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1=. -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-25-171901-26424-1 -x c++ /build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp

/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/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~++20210825111122+868bd9938db1/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~++20210825111122+868bd9938db1/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~++20210825111122+868bd9938db1/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~++20210825111122+868bd9938db1/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~++20210825111122+868bd9938db1/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~++20210825111122+868bd9938db1/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~++20210825111122+868bd9938db1/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~++20210825111122+868bd9938db1/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~++20210825111122+868bd9938db1/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~++20210825111122+868bd9938db1/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~++20210825111122+868bd9938db1/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~++20210825111122+868bd9938db1/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~++20210825111122+868bd9938db1/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~++20210825111122+868bd9938db1/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~++20210825111122+868bd9938db1/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~++20210825111122+868bd9938db1/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~++20210825111122+868bd9938db1/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~++20210825111122+868bd9938db1/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~++20210825111122+868bd9938db1/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~++20210825111122+868bd9938db1/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~++20210825111122+868bd9938db1/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~++20210825111122+868bd9938db1/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~++20210825111122+868bd9938db1/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() &&
16
Calling 'Decl::getFriendObjectKind'
22
Returning from 'Decl::getFriendObjectKind'
24
Taking false branch
1584 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
23
Assuming the condition is false
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
24.1
'NewM' is null
24.1
'NewM' is null
&& NewM->Kind == Module::PrivateModuleFragment)
1594 NewM = NewM->Parent;
1595 if (OldM
24.2
'OldM' is null
24.2
'OldM' is null
&& OldM->Kind == Module::PrivateModuleFragment)
1596 OldM = OldM->Parent;
1597
1598 if (NewM
24.3
'NewM' is equal to 'OldM'
24.3
'NewM' is equal to 'OldM'
== OldM)
25
Taking true branch
1599 return false;
26
Returning zero, which participates in a condition later
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~++20210825111122+868bd9938db1/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~++20210825111122+868bd9938db1/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~++20210825111122+868bd9938db1/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~++20210825111122+868bd9938db1/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~++20210825111122+868bd9938db1/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~++20210825111122+868bd9938db1/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~++20210825111122+868bd9938db1/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~++20210825111122+868bd9938db1/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~++20210825111122+868bd9938db1/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 *FA = dyn_cast<FormatAttr>(Attr))
2632 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2633 FA->getFirstArg());
2634 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2635 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2636 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2637 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2638 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2639 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2640 IA->getInheritanceModel());
2641 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2642 NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2643 &S.Context.Idents.get(AA->getSpelling()));
2644 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2645 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2646 isa<CUDAGlobalAttr>(Attr))) {
2647 // CUDA target attributes are part of function signature for
2648 // overloading purposes and must not be merged.
2649 return false;
2650 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2651 NewAttr = S.mergeMinSizeAttr(D, *MA);
2652 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2653 NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2654 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2655 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2656 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2657 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2658 else if (isa<AlignedAttr>(Attr))
2659 // AlignedAttrs are handled separately, because we need to handle all
2660 // such attributes on a declaration at the same time.
2661 NewAttr = nullptr;
2662 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2663 (AMK == Sema::AMK_Override ||
2664 AMK == Sema::AMK_ProtocolImplementation ||
2665 AMK == Sema::AMK_OptionalProtocolImplementation))
2666 NewAttr = nullptr;
2667 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2668 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2669 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2670 NewAttr = S.mergeImportModuleAttr(D, *IMA);
2671 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2672 NewAttr = S.mergeImportNameAttr(D, *INA);
2673 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2674 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2675 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2676 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2677 else if (const auto *BTFA = dyn_cast<BTFTagAttr>(Attr))
2678 NewAttr = S.mergeBTFTagAttr(D, *BTFA);
2679 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2680 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2681
2682 if (NewAttr) {
2683 NewAttr->setInherited(true);
2684 D->addAttr(NewAttr);
2685 if (isa<MSInheritanceAttr>(NewAttr))
2686 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2687 return true;
2688 }
2689
2690 return false;
2691}
2692
2693static const NamedDecl *getDefinition(const Decl *D) {
2694 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2695 return TD->getDefinition();
2696 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2697 const VarDecl *Def = VD->getDefinition();
2698 if (Def)
2699 return Def;
2700 return VD->getActingDefinition();
2701 }
2702 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2703 const FunctionDecl *Def = nullptr;
2704 if (FD->isDefined(Def, true))
2705 return Def;
2706 }
2707 return nullptr;
2708}
2709
2710static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2711 for (const auto *Attribute : D->attrs())
2712 if (Attribute->getKind() == Kind)
2713 return true;
2714 return false;
2715}
2716
2717/// checkNewAttributesAfterDef - If we already have a definition, check that
2718/// there are no new attributes in this declaration.
2719static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2720 if (!New->hasAttrs())
2721 return;
2722
2723 const NamedDecl *Def = getDefinition(Old);
2724 if (!Def || Def == New)
2725 return;
2726
2727 AttrVec &NewAttributes = New->getAttrs();
2728 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2729 const Attr *NewAttribute = NewAttributes[I];
2730
2731 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2732 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2733 Sema::SkipBodyInfo SkipBody;
2734 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2735
2736 // If we're skipping this definition, drop the "alias" attribute.
2737 if (SkipBody.ShouldSkip) {
2738 NewAttributes.erase(NewAttributes.begin() + I);
2739 --E;
2740 continue;
2741 }
2742 } else {
2743 VarDecl *VD = cast<VarDecl>(New);
2744 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2745 VarDecl::TentativeDefinition
2746 ? diag::err_alias_after_tentative
2747 : diag::err_redefinition;
2748 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2749 if (Diag == diag::err_redefinition)
2750 S.notePreviousDefinition(Def, VD->getLocation());
2751 else
2752 S.Diag(Def->getLocation(), diag::note_previous_definition);
2753 VD->setInvalidDecl();
2754 }
2755 ++I;
2756 continue;
2757 }
2758
2759 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2760 // Tentative definitions are only interesting for the alias check above.
2761 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2762 ++I;
2763 continue;
2764 }
2765 }
2766
2767 if (hasAttribute(Def, NewAttribute->getKind())) {
2768 ++I;
2769 continue; // regular attr merging will take care of validating this.
2770 }
2771
2772 if (isa<C11NoReturnAttr>(NewAttribute)) {
2773 // C's _Noreturn is allowed to be added to a function after it is defined.
2774 ++I;
2775 continue;
2776 } else if (isa<UuidAttr>(NewAttribute)) {
2777 // msvc will allow a subsequent definition to add an uuid to a class
2778 ++I;
2779 continue;
2780 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2781 if (AA->isAlignas()) {
2782 // C++11 [dcl.align]p6:
2783 // if any declaration of an entity has an alignment-specifier,
2784 // every defining declaration of that entity shall specify an
2785 // equivalent alignment.
2786 // C11 6.7.5/7:
2787 // If the definition of an object does not have an alignment
2788 // specifier, any other declaration of that object shall also
2789 // have no alignment specifier.
2790 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2791 << AA;
2792 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2793 << AA;
2794 NewAttributes.erase(NewAttributes.begin() + I);
2795 --E;
2796 continue;
2797 }
2798 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2799 // If there is a C definition followed by a redeclaration with this
2800 // attribute then there are two different definitions. In C++, prefer the
2801 // standard diagnostics.
2802 if (!S.getLangOpts().CPlusPlus) {
2803 S.Diag(NewAttribute->getLocation(),
2804 diag::err_loader_uninitialized_redeclaration);
2805 S.Diag(Def->getLocation(), diag::note_previous_definition);
2806 NewAttributes.erase(NewAttributes.begin() + I);
2807 --E;
2808 continue;
2809 }
2810 } else if (isa<SelectAnyAttr>(NewAttribute) &&
2811 cast<VarDecl>(New)->isInline() &&
2812 !cast<VarDecl>(New)->isInlineSpecified()) {
2813 // Don't warn about applying selectany to implicitly inline variables.
2814 // Older compilers and language modes would require the use of selectany
2815 // to make such variables inline, and it would have no effect if we
2816 // honored it.
2817 ++I;
2818 continue;
2819 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
2820 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
2821 // declarations after defintions.
2822 ++I;
2823 continue;
2824 }
2825
2826 S.Diag(NewAttribute->getLocation(),
2827 diag::warn_attribute_precede_definition);
2828 S.Diag(Def->getLocation(), diag::note_previous_definition);
2829 NewAttributes.erase(NewAttributes.begin() + I);
2830 --E;
2831 }
2832}
2833
2834static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2835 const ConstInitAttr *CIAttr,
2836 bool AttrBeforeInit) {
2837 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2838
2839 // Figure out a good way to write this specifier on the old declaration.
2840 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2841 // enough of the attribute list spelling information to extract that without
2842 // heroics.
2843 std::string SuitableSpelling;
2844 if (S.getLangOpts().CPlusPlus20)
2845 SuitableSpelling = std::string(
2846 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2847 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2848 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2849 InsertLoc, {tok::l_square, tok::l_square,
2850 S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2851 S.PP.getIdentifierInfo("require_constant_initialization"),
2852 tok::r_square, tok::r_square}));
2853 if (SuitableSpelling.empty())
2854 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2855 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2856 S.PP.getIdentifierInfo("require_constant_initialization"),
2857 tok::r_paren, tok::r_paren}));
2858 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
2859 SuitableSpelling = "constinit";
2860 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2861 SuitableSpelling = "[[clang::require_constant_initialization]]";
2862 if (SuitableSpelling.empty())
2863 SuitableSpelling = "__attribute__((require_constant_initialization))";
2864 SuitableSpelling += " ";
2865
2866 if (AttrBeforeInit) {
2867 // extern constinit int a;
2868 // int a = 0; // error (missing 'constinit'), accepted as extension
2869 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~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 2869, __extension__ __PRETTY_FUNCTION__))
;
2870 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2871 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2872 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2873 } else {
2874 // int a = 0;
2875 // constinit extern int a; // error (missing 'constinit')
2876 S.Diag(CIAttr->getLocation(),
2877 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2878 : diag::warn_require_const_init_added_too_late)
2879 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2880 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2881 << CIAttr->isConstinit()
2882 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2883 }
2884}
2885
2886/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2887void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2888 AvailabilityMergeKind AMK) {
2889 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2890 UsedAttr *NewAttr = OldAttr->clone(Context);
2891 NewAttr->setInherited(true);
2892 New->addAttr(NewAttr);
2893 }
2894 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
2895 RetainAttr *NewAttr = OldAttr->clone(Context);
2896 NewAttr->setInherited(true);
2897 New->addAttr(NewAttr);
2898 }
2899
2900 if (!Old->hasAttrs() && !New->hasAttrs())
2901 return;
2902
2903 // [dcl.constinit]p1:
2904 // If the [constinit] specifier is applied to any declaration of a
2905 // variable, it shall be applied to the initializing declaration.
2906 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
2907 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
2908 if (bool(OldConstInit) != bool(NewConstInit)) {
2909 const auto *OldVD = cast<VarDecl>(Old);
2910 auto *NewVD = cast<VarDecl>(New);
2911
2912 // Find the initializing declaration. Note that we might not have linked
2913 // the new declaration into the redeclaration chain yet.
2914 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
2915 if (!InitDecl &&
2916 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
2917 InitDecl = NewVD;
2918
2919 if (InitDecl == NewVD) {
2920 // This is the initializing declaration. If it would inherit 'constinit',
2921 // that's ill-formed. (Note that we do not apply this to the attribute
2922 // form).
2923 if (OldConstInit && OldConstInit->isConstinit())
2924 diagnoseMissingConstinit(*this, NewVD, OldConstInit,
2925 /*AttrBeforeInit=*/true);
2926 } else if (NewConstInit) {
2927 // This is the first time we've been told that this declaration should
2928 // have a constant initializer. If we already saw the initializing
2929 // declaration, this is too late.
2930 if (InitDecl && InitDecl != NewVD) {
2931 diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
2932 /*AttrBeforeInit=*/false);
2933 NewVD->dropAttr<ConstInitAttr>();
2934 }
2935 }
2936 }
2937
2938 // Attributes declared post-definition are currently ignored.
2939 checkNewAttributesAfterDef(*this, New, Old);
2940
2941 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2942 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2943 if (!OldA->isEquivalent(NewA)) {
2944 // This redeclaration changes __asm__ label.
2945 Diag(New->getLocation(), diag::err_different_asm_label);
2946 Diag(OldA->getLocation(), diag::note_previous_declaration);
2947 }
2948 } else if (Old->isUsed()) {
2949 // This redeclaration adds an __asm__ label to a declaration that has
2950 // already been ODR-used.
2951 Diag(New->getLocation(), diag::err_late_asm_label_name)
2952 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2953 }
2954 }
2955
2956 // Re-declaration cannot add abi_tag's.
2957 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2958 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2959 for (const auto &NewTag : NewAbiTagAttr->tags()) {
2960 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2961 NewTag) == OldAbiTagAttr->tags_end()) {
2962 Diag(NewAbiTagAttr->getLocation(),
2963 diag::err_new_abi_tag_on_redeclaration)
2964 << NewTag;
2965 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2966 }
2967 }
2968 } else {
2969 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2970 Diag(Old->getLocation(), diag::note_previous_declaration);
2971 }
2972 }
2973
2974 // This redeclaration adds a section attribute.
2975 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2976 if (auto *VD = dyn_cast<VarDecl>(New)) {
2977 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2978 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2979 Diag(Old->getLocation(), diag::note_previous_declaration);
2980 }
2981 }
2982 }
2983
2984 // Redeclaration adds code-seg attribute.
2985 const auto *NewCSA = New->getAttr<CodeSegAttr>();
2986 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2987 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2988 Diag(New->getLocation(), diag::warn_mismatched_section)
2989 << 0 /*codeseg*/;
2990 Diag(Old->getLocation(), diag::note_previous_declaration);
2991 }
2992
2993 if (!Old->hasAttrs())
2994 return;
2995
2996 bool foundAny = New->hasAttrs();
2997
2998 // Ensure that any moving of objects within the allocated map is done before
2999 // we process them.
3000 if (!foundAny) New->setAttrs(AttrVec());
3001
3002 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3003 // Ignore deprecated/unavailable/availability attributes if requested.
3004 AvailabilityMergeKind LocalAMK = AMK_None;
3005 if (isa<DeprecatedAttr>(I) ||
3006 isa<UnavailableAttr>(I) ||
3007 isa<AvailabilityAttr>(I)) {
3008 switch (AMK) {
3009 case AMK_None:
3010 continue;
3011
3012 case AMK_Redeclaration:
3013 case AMK_Override:
3014 case AMK_ProtocolImplementation:
3015 case AMK_OptionalProtocolImplementation:
3016 LocalAMK = AMK;
3017 break;
3018 }
3019 }
3020
3021 // Already handled.
3022 if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3023 continue;
3024
3025 if (mergeDeclAttribute(*this, New, I, LocalAMK))
3026 foundAny = true;
3027 }
3028
3029 if (mergeAlignedAttrs(*this, New, Old))
3030 foundAny = true;
3031
3032 if (!foundAny) New->dropAttrs();
3033}
3034
3035/// mergeParamDeclAttributes - Copy attributes from the old parameter
3036/// to the new one.
3037static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3038 const ParmVarDecl *oldDecl,
3039 Sema &S) {
3040 // C++11 [dcl.attr.depend]p2:
3041 // The first declaration of a function shall specify the
3042 // carries_dependency attribute for its declarator-id if any declaration
3043 // of the function specifies the carries_dependency attribute.
3044 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3045 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3046 S.Diag(CDA->getLocation(),
3047 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3048 // Find the first declaration of the parameter.
3049 // FIXME: Should we build redeclaration chains for function parameters?
3050 const FunctionDecl *FirstFD =
3051 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3052 const ParmVarDecl *FirstVD =
3053 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3054 S.Diag(FirstVD->getLocation(),
3055 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3056 }
3057
3058 if (!oldDecl->hasAttrs())
3059 return;
3060
3061 bool foundAny = newDecl->hasAttrs();
3062
3063 // Ensure that any moving of objects within the allocated map is
3064 // done before we process them.
3065 if (!foundAny) newDecl->setAttrs(AttrVec());
3066
3067 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3068 if (!DeclHasAttr(newDecl, I)) {
3069 InheritableAttr *newAttr =
3070 cast<InheritableParamAttr>(I->clone(S.Context));
3071 newAttr->setInherited(true);
3072 newDecl->addAttr(newAttr);
3073 foundAny = true;
3074 }
3075 }
3076
3077 if (!foundAny) newDecl->dropAttrs();
3078}
3079
3080static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3081 const ParmVarDecl *OldParam,
3082 Sema &S) {
3083 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3084 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3085 if (*Oldnullability != *Newnullability) {
3086 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3087 << DiagNullabilityKind(
3088 *Newnullability,
3089 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3090 != 0))
3091 << DiagNullabilityKind(
3092 *Oldnullability,
3093 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3094 != 0));
3095 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3096 }
3097 } else {
3098 QualType NewT = NewParam->getType();
3099 NewT = S.Context.getAttributedType(
3100 AttributedType::getNullabilityAttrKind(*Oldnullability),
3101 NewT, NewT);
3102 NewParam->setType(NewT);
3103 }
3104 }
3105}
3106
3107namespace {
3108
3109/// Used in MergeFunctionDecl to keep track of function parameters in
3110/// C.
3111struct GNUCompatibleParamWarning {
3112 ParmVarDecl *OldParm;
3113 ParmVarDecl *NewParm;
3114 QualType PromotedType;
3115};
3116
3117} // end anonymous namespace
3118
3119// Determine whether the previous declaration was a definition, implicit
3120// declaration, or a declaration.
3121template <typename T>
3122static std::pair<diag::kind, SourceLocation>
3123getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3124 diag::kind PrevDiag;
3125 SourceLocation OldLocation = Old->getLocation();
3126 if (Old->isThisDeclarationADefinition())
3127 PrevDiag = diag::note_previous_definition;
3128 else if (Old->isImplicit()) {
3129 PrevDiag = diag::note_previous_implicit_declaration;
3130 if (OldLocation.isInvalid())
3131 OldLocation = New->getLocation();
3132 } else
3133 PrevDiag = diag::note_previous_declaration;
3134 return std::make_pair(PrevDiag, OldLocation);
3135}
3136
3137/// canRedefineFunction - checks if a function can be redefined. Currently,
3138/// only extern inline functions can be redefined, and even then only in
3139/// GNU89 mode.
3140static bool canRedefineFunction(const FunctionDecl *FD,
3141 const LangOptions& LangOpts) {
3142 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3143 !LangOpts.CPlusPlus &&
3144 FD->isInlineSpecified() &&
3145 FD->getStorageClass() == SC_Extern);
3146}
3147
3148const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3149 const AttributedType *AT = T->getAs<AttributedType>();
3150 while (AT && !AT->isCallingConv())
3151 AT = AT->getModifiedType()->getAs<AttributedType>();
3152 return AT;
3153}
3154
3155template <typename T>
3156static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3157 const DeclContext *DC = Old->getDeclContext();
3158 if (DC->isRecord())
51
Calling 'DeclContext::isRecord'
54
Returning from 'DeclContext::isRecord'
55
Taking false branch
3159 return false;
3160
3161 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3162 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
56
Assuming 'OldLinkage' is not equal to CXXLanguageLinkage
3163 return true;
3164 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
57
Assuming 'OldLinkage' is not equal to CLanguageLinkage
3165 return true;
3166 return false;
58
Returning zero, which participates in a condition later
3167}
3168
3169template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3170static bool isExternC(VarTemplateDecl *) { return false; }
3171static bool isExternC(FunctionTemplateDecl *) { return false; }
3172
3173/// Check whether a redeclaration of an entity introduced by a
3174/// using-declaration is valid, given that we know it's not an overload
3175/// (nor a hidden tag declaration).
3176template<typename ExpectedDecl>
3177static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3178 ExpectedDecl *New) {
3179 // C++11 [basic.scope.declarative]p4:
3180 // Given a set of declarations in a single declarative region, each of
3181 // which specifies the same unqualified name,
3182 // -- they shall all refer to the same entity, or all refer to functions
3183 // and function templates; or
3184 // -- exactly one declaration shall declare a class name or enumeration
3185 // name that is not a typedef name and the other declarations shall all
3186 // refer to the same variable or enumerator, or all refer to functions
3187 // and function templates; in this case the class name or enumeration
3188 // name is hidden (3.3.10).
3189
3190 // C++11 [namespace.udecl]p14:
3191 // If a function declaration in namespace scope or block scope has the
3192 // same name and the same parameter-type-list as a function introduced
3193 // by a using-declaration, and the declarations do not declare the same
3194 // function, the program is ill-formed.
3195
3196 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3197 if (Old &&
3198 !Old->getDeclContext()->getRedeclContext()->Equals(
3199 New->getDeclContext()->getRedeclContext()) &&
3200 !(isExternC(Old) && isExternC(New)))
3201 Old = nullptr;
3202
3203 if (!Old) {
3204 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3205 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3206 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3207 return true;
3208 }
3209 return false;
3210}
3211
3212static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3213 const FunctionDecl *B) {
3214 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~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 3214, __extension__ __PRETTY_FUNCTION__))
;
3215
3216 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3217 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3218 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3219 if (AttrA == AttrB)
3220 return true;
3221 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3222 AttrA->isDynamic() == AttrB->isDynamic();
3223 };
3224
3225 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3226}
3227
3228/// If necessary, adjust the semantic declaration context for a qualified
3229/// declaration to name the correct inline namespace within the qualifier.
3230static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3231 DeclaratorDecl *OldD) {
3232 // The only case where we need to update the DeclContext is when
3233 // redeclaration lookup for a qualified name finds a declaration
3234 // in an inline namespace within the context named by the qualifier:
3235 //
3236 // inline namespace N { int f(); }
3237 // int ::f(); // Sema DC needs adjusting from :: to N::.
3238 //
3239 // For unqualified declarations, the semantic context *can* change
3240 // along the redeclaration chain (for local extern declarations,
3241 // extern "C" declarations, and friend declarations in particular).
3242 if (!NewD->getQualifier())
4
Taking true branch
3243 return;
5
Returning without writing to 'OldD->InvalidDecl', which participates in a condition later
3244
3245 // NewD is probably already in the right context.
3246 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3247 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3248 if (NamedDC->Equals(SemaDC))
3249 return;
3250
3251 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~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 3253, __extension__ __PRETTY_FUNCTION__))
3252 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~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 3253, __extension__ __PRETTY_FUNCTION__))
3253 "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~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 3253, __extension__ __PRETTY_FUNCTION__))
;
3254
3255 auto *LexDC = NewD->getLexicalDeclContext();
3256 auto FixSemaDC = [=](NamedDecl *D) {
3257 if (!D)
3258 return;
3259 D->setDeclContext(SemaDC);
3260 D->setLexicalDeclContext(LexDC);
3261 };
3262
3263 FixSemaDC(NewD);
3264 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3265 FixSemaDC(FD->getDescribedFunctionTemplate());
3266 else if (auto *VD = dyn_cast<VarDecl>(NewD))
3267 FixSemaDC(VD->getDescribedVarTemplate());
3268}
3269
3270/// MergeFunctionDecl - We just parsed a function 'New' from
3271/// declarator D which has the same name and scope as a previous
3272/// declaration 'Old'. Figure out how to resolve this situation,
3273/// merging decls or emitting diagnostics as appropriate.
3274///
3275/// In C++, New and Old must be declarations that are not
3276/// overloaded. Use IsOverload to determine whether New and Old are
3277/// overloaded, and to select the Old declaration that New should be
3278/// merged with.
3279///
3280/// Returns true if there was an error, false otherwise.
3281bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3282 Scope *S, bool MergeTypeWithOld) {
3283 // Verify the old decl was also a function.
3284 FunctionDecl *Old = OldD->getAsFunction();
3285 if (!Old) {
1
Assuming 'Old' is non-null
2
Taking false branch
3286 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3287 if (New->getFriendObjectKind()) {
3288 Diag(New->getLocation(), diag::err_using_decl_friend);
3289 Diag(Shadow->getTargetDecl()->getLocation(),
3290 diag::note_using_decl_target);
3291 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3292 << 0;
3293 return true;
3294 }
3295
3296 // Check whether the two declarations might declare the same function or
3297 // function template.
3298 if (FunctionTemplateDecl *NewTemplate =
3299 New->getDescribedFunctionTemplate()) {
3300 if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3301 NewTemplate))
3302 return true;
3303 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3304 ->getAsFunction();
3305 } else {
3306 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3307 return true;
3308 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3309 }
3310 } else {
3311 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3312 << New->getDeclName();
3313 notePreviousDefinition(OldD, New->getLocation());
3314 return true;
3315 }
3316 }
3317
3318 // If the old declaration was found in an inline namespace and the new
3319 // declaration was qualified, update the DeclContext to match.
3320 adjustDeclContextForDeclaratorDecl(New, Old);
3
Calling 'adjustDeclContextForDeclaratorDecl'
6
Returning from 'adjustDeclContextForDeclaratorDecl'
3321
3322 // If the old declaration is invalid, just give up here.
3323 if (Old->isInvalidDecl())
7
Assuming the condition is false
8
Taking false branch
3324 return true;
3325
3326 // Disallow redeclaration of some builtins.
3327 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
9
Assuming the condition is false
10
Taking false branch
3328 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3329 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3330 << Old << Old->getType();
3331 return true;
3332 }
3333
3334 diag::kind PrevDiag;
3335 SourceLocation OldLocation;
3336 std::tie(PrevDiag, OldLocation) =
3337 getNoteDiagForInvalidRedeclaration(Old, New);
3338
3339 // Don't complain about this if we're in GNU89 mode and the old function
3340 // is an extern inline function.
3341 // Don't complain about specializations. They are not supposed to have
3342 // storage classes.
3343 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
11
Assuming 'New' is not a 'CXXMethodDecl'
12
Assuming 'Old' is not a 'CXXMethodDecl'
3344 New->getStorageClass() == SC_Static &&
13
Assuming the condition is false
3345 Old->hasExternalFormalLinkage() &&
3346 !New->getTemplateSpecializationInfo() &&
3347 !canRedefineFunction(Old, getLangOpts())) {
3348 if (getLangOpts().MicrosoftExt) {
3349 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3350 Diag(OldLocation, PrevDiag);
3351 } else {
3352 Diag(New->getLocation(), diag::err_static_non_static) << New;
3353 Diag(OldLocation, PrevDiag);
3354 return true;
3355 }
3356 }
3357
3358 if (const auto *ILA
13.1
'ILA' is null
13.1
'ILA' is null
= New->getAttr<InternalLinkageAttr>())
14
Taking false branch
3359 if (!Old->hasAttr<InternalLinkageAttr>()) {
3360 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3361 << ILA;
3362 Diag(Old->getLocation(), diag::note_previous_declaration);
3363 New->dropAttr<InternalLinkageAttr>();
3364 }
3365
3366 if (CheckRedeclarationModuleOwnership(New, Old))
15
Calling 'Sema::CheckRedeclarationModuleOwnership'
27
Returning from 'Sema::CheckRedeclarationModuleOwnership'
28
Taking false branch
3367 return true;
3368
3369 if (!getLangOpts().CPlusPlus) {
29
Assuming field 'CPlusPlus' is not equal to 0
30
Taking false branch
3370 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3371 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3372 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3373 << New << OldOvl;
3374
3375 // Try our best to find a decl that actually has the overloadable
3376 // attribute for the note. In most cases (e.g. programs with only one
3377 // broken declaration/definition), this won't matter.
3378 //
3379 // FIXME: We could do this if we juggled some extra state in
3380 // OverloadableAttr, rather than just removing it.
3381 const Decl *DiagOld = Old;
3382 if (OldOvl) {
3383 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3384 const auto *A = D->getAttr<OverloadableAttr>();
3385 return A && !A->isImplicit();
3386 });
3387 // If we've implicitly added *all* of the overloadable attrs to this
3388 // chain, emitting a "previous redecl" note is pointless.
3389 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3390 }
3391
3392 if (DiagOld)
3393 Diag(DiagOld->getLocation(),
3394 diag::note_attribute_overloadable_prev_overload)
3395 << OldOvl;
3396
3397 if (OldOvl)
3398 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3399 else
3400 New->dropAttr<OverloadableAttr>();
3401 }
3402 }
3403
3404 // If a function is first declared with a calling convention, but is later
3405 // declared or defined without one, all following decls assume the calling
3406 // convention of the first.
3407 //
3408 // It's OK if a function is first declared without a calling convention,
3409 // but is later declared or defined with the default calling convention.
3410 //
3411 // To test if either decl has an explicit calling convention, we look for
3412 // AttributedType sugar nodes on the type as written. If they are missing or
3413 // were canonicalized away, we assume the calling convention was implicit.
3414 //
3415 // Note also that we DO NOT return at this point, because we still have
3416 // other tests to run.
3417 QualType OldQType = Context.getCanonicalType(Old->getType());
3418 QualType NewQType = Context.getCanonicalType(New->getType());
3419 const FunctionType *OldType = cast<FunctionType>(OldQType);
3420 const FunctionType *NewType = cast<FunctionType>(NewQType);
3421 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3422 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3423 bool RequiresAdjustment = false;
3424
3425 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
31
Assuming the condition is false
3426 FunctionDecl *First = Old->getFirstDecl();
3427 const FunctionType *FT =
3428 First->getType().getCanonicalType()->castAs<FunctionType>();
3429 FunctionType::ExtInfo FI = FT->getExtInfo();
3430 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3431 if (!NewCCExplicit) {
3432 // Inherit the CC from the previous declaration if it was specified
3433 // there but not here.
3434 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3435 RequiresAdjustment = true;
3436 } else if (Old->getBuiltinID()) {
3437 // Builtin attribute isn't propagated to the new one yet at this point,
3438 // so we check if the old one is a builtin.
3439
3440 // Calling Conventions on a Builtin aren't really useful and setting a
3441 // default calling convention and cdecl'ing some builtin redeclarations is
3442 // common, so warn and ignore the calling convention on the redeclaration.
3443 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3444 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3445 << (int)CallingConventionIgnoredReason::BuiltinFunction;
3446 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3447 RequiresAdjustment = true;
3448 } else {
3449 // Calling conventions aren't compatible, so complain.
3450 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3451 Diag(New->getLocation(), diag::err_cconv_change)
3452 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3453 << !FirstCCExplicit
3454 << (!FirstCCExplicit ? "" :
3455 FunctionType::getNameForCallConv(FI.getCC()));
3456
3457 // Put the note on the first decl, since it is the one that matters.
3458 Diag(First->getLocation(), diag::note_previous_declaration);
3459 return true;
3460 }
3461 }
3462
3463 // FIXME: diagnose the other way around?
3464 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
32
Assuming the condition is false
3465 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3466 RequiresAdjustment = true;
3467 }
3468
3469 // Merge regparm attribute.
3470 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
33
Taking false branch
3471 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3472 if (NewTypeInfo.getHasRegParm()) {
3473 Diag(New->getLocation(), diag::err_regparm_mismatch)
3474 << NewType->getRegParmType()
3475 << OldType->getRegParmType();
3476 Diag(OldLocation, diag::note_previous_declaration);
3477 return true;
3478 }
3479
3480 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3481 RequiresAdjustment = true;
3482 }
3483
3484 // Merge ns_returns_retained attribute.
3485 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
34
Assuming the condition is false
35
Taking false branch
3486 if (NewTypeInfo.getProducesResult()) {
3487 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3488 << "'ns_returns_retained'";
3489 Diag(OldLocation, diag::note_previous_declaration);
3490 return true;
3491 }
3492
3493 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3494 RequiresAdjustment = true;
3495 }
3496
3497 if (OldTypeInfo.getNoCallerSavedRegs() !=
36
Assuming the condition is false
37
Taking false branch
3498 NewTypeInfo.getNoCallerSavedRegs()) {
3499 if (NewTypeInfo.getNoCallerSavedRegs()) {
3500 AnyX86NoCallerSavedRegistersAttr *Attr =
3501 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3502 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3503 Diag(OldLocation, diag::note_previous_declaration);
3504 return true;
3505 }
3506
3507 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3508 RequiresAdjustment = true;
3509 }
3510
3511 if (RequiresAdjustment
37.1
'RequiresAdjustment' is false
37.1
'RequiresAdjustment' is false
) {
3512 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3513 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3514 New->setType(QualType(AdjustedType, 0));
3515 NewQType = Context.getCanonicalType(New->getType());
3516 }
3517
3518 // If this redeclaration makes the function inline, we may need to add it to
3519 // UndefinedButUsed.
3520 if (!Old->isInlined() && New->isInlined() &&
38
Assuming the condition is false
3521 !New->hasAttr<GNUInlineAttr>() &&
3522 !getLangOpts().GNUInline &&
3523 Old->isUsed(false) &&
3524 !Old->isDefined() && !New->isThisDeclarationADefinition())
3525 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3526 SourceLocation()));
3527
3528 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3529 // about it.
3530 if (New->hasAttr<GNUInlineAttr>() &&
3531 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3532 UndefinedButUsed.erase(Old->getCanonicalDecl());
3533 }
3534
3535 // If pass_object_size params don't match up perfectly, this isn't a valid
3536 // redeclaration.
3537 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
39
Assuming the condition is false
3538 !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3539 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3540 << New->getDeclName();
3541 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3542 return true;
3543 }
3544
3545 if (getLangOpts().CPlusPlus
39.1
Field 'CPlusPlus' is not equal to 0
39.1
Field 'CPlusPlus' is not equal to 0
) {
40
Taking true branch
3546 // C++1z [over.load]p2
3547 // Certain function declarations cannot be overloaded:
3548 // -- Function declarations that differ only in the return type,
3549 // the exception specification, or both cannot be overloaded.
3550
3551 // Check the exception specifications match. This may recompute the type of
3552 // both Old and New if it resolved exception specifications, so grab the
3553 // types again after this. Because this updates the type, we do this before
3554 // any of the other checks below, which may update the "de facto" NewQType
3555 // but do not necessarily update the type of New.
3556 if (CheckEquivalentExceptionSpec(Old, New))
41
Assuming the condition is false
42
Taking false branch
3557 return true;
3558 OldQType = Context.getCanonicalType(Old->getType());
3559 NewQType = Context.getCanonicalType(New->getType());
3560
3561 // Go back to the type source info to compare the declared return types,
3562 // per C++1y [dcl.type.auto]p13:
3563 // Redeclarations or specializations of a function or function template
3564 // with a declared return type that uses a placeholder type shall also
3565 // use that placeholder, not a deduced type.
3566 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3567 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3568 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
43
Assuming the condition is false
3569 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3570 OldDeclaredReturnType)) {
3571 QualType ResQT;
3572 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3573 OldDeclaredReturnType->isObjCObjectPointerType())
3574 // FIXME: This does the wrong thing for a deduced return type.
3575 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3576 if (ResQT.isNull()) {
3577 if (New->isCXXClassMember() && New->isOutOfLine())
3578 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3579 << New << New->getReturnTypeSourceRange();
3580 else
3581 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3582 << New->getReturnTypeSourceRange();
3583 Diag(OldLocation, PrevDiag) << Old << Old->getType()
3584 << Old->getReturnTypeSourceRange();
3585 return true;
3586 }
3587 else
3588 NewQType = ResQT;
3589 }
3590
3591 QualType OldReturnType = OldType->getReturnType();
3592 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3593 if (OldReturnType != NewReturnType) {
44
Taking false branch
3594 // If this function has a deduced return type and has already been
3595 // defined, copy the deduced value from the old declaration.
3596 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3597 if (OldAT && OldAT->isDeduced()) {
3598 New->setType(
3599 SubstAutoType(New->getType(),
3600 OldAT->isDependentType() ? Context.DependentTy
3601 : OldAT->getDeducedType()));
3602 NewQType = Context.getCanonicalType(
3603 SubstAutoType(NewQType,
3604 OldAT->isDependentType() ? Context.DependentTy
3605 : OldAT->getDeducedType()));
3606 }
3607 }
3608
3609 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
45
Assuming 'Old' is not a 'CXXMethodDecl'
3610 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
46
Assuming 'New' is not a 'CXXMethodDecl'
3611 if (OldMethod
46.1
'OldMethod' is null
46.1
'OldMethod' is null
&& NewMethod) {
3612 // Preserve triviality.
3613 NewMethod->setTrivial(OldMethod->isTrivial());
3614
3615 // MSVC allows explicit template specialization at class scope:
3616 // 2 CXXMethodDecls referring to the same function will be injected.
3617 // We don't want a redeclaration error.
3618 bool IsClassScopeExplicitSpecialization =
3619 OldMethod->isFunctionTemplateSpecialization() &&
3620 NewMethod->isFunctionTemplateSpecialization();
3621 bool isFriend = NewMethod->getFriendObjectKind();
3622
3623 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3624 !IsClassScopeExplicitSpecialization) {
3625 // -- Member function declarations with the same name and the
3626 // same parameter types cannot be overloaded if any of them
3627 // is a static member function declaration.
3628 if (OldMethod->isStatic() != NewMethod->isStatic()) {
3629 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3630 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3631 return true;
3632 }
3633
3634 // C++ [class.mem]p1:
3635 // [...] A member shall not be declared twice in the
3636 // member-specification, except that a nested class or member
3637 // class template can be declared and then later defined.
3638 if (!inTemplateInstantiation()) {
3639 unsigned NewDiag;
3640 if (isa<CXXConstructorDecl>(OldMethod))
3641 NewDiag = diag::err_constructor_redeclared;
3642 else if (isa<CXXDestructorDecl>(NewMethod))
3643 NewDiag = diag::err_destructor_redeclared;
3644 else if (isa<CXXConversionDecl>(NewMethod))
3645 NewDiag = diag::err_conv_function_redeclared;
3646 else
3647 NewDiag = diag::err_member_redeclared;
3648
3649 Diag(New->getLocation(), NewDiag);
3650 } else {
3651 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3652 << New << New->getType();
3653 }
3654 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3655 return true;
3656
3657 // Complain if this is an explicit declaration of a special
3658 // member that was initially declared implicitly.
3659 //
3660 // As an exception, it's okay to befriend such methods in order
3661 // to permit the implicit constructor/destructor/operator calls.
3662 } else if (OldMethod->isImplicit()) {
3663 if (isFriend) {
3664 NewMethod->setImplicit();
3665 } else {
3666 Diag(NewMethod->getLocation(),
3667 diag::err_definition_of_implicitly_declared_member)
3668 << New << getSpecialMember(OldMethod);
3669 return true;
3670 }
3671 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3672 Diag(NewMethod->getLocation(),
3673 diag::err_definition_of_explicitly_defaulted_member)
3674 << getSpecialMember(OldMethod);
3675 return true;
3676 }
3677 }
3678
3679 // C++11 [dcl.attr.noreturn]p1:
3680 // The first declaration of a function shall specify the noreturn
3681 // attribute if any declaration of that function specifies the noreturn
3682 // attribute.
3683 if (const auto *NRA
46.2
'NRA' is null
46.2
'NRA' is null
= New->getAttr<CXX11NoReturnAttr>())
47
Taking false branch
3684 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
3685 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
3686 << NRA;
3687 Diag(Old->getLocation(), diag::note_previous_declaration);
3688 }
3689
3690 // C++11 [dcl.attr.depend]p2:
3691 // The first declaration of a function shall specify the
3692 // carries_dependency attribute for its declarator-id if any declaration
3693 // of the function specifies the carries_dependency attribute.
3694 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3695 if (CDA
47.1
'CDA' is null
47.1
'CDA' is null
&& !Old->hasAttr<CarriesDependencyAttr>()) {
3696 Diag(CDA->getLocation(),
3697 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3698 Diag(Old->getFirstDecl()->getLocation(),
3699 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3700 }
3701
3702 // (C++98 8.3.5p3):
3703 // All declarations for a function shall agree exactly in both the
3704 // return type and the parameter-type-list.
3705 // We also want to respect all the extended bits except noreturn.
3706
3707 // noreturn should now match unless the old type info didn't have it.
3708 QualType OldQTypeForComparison = OldQType;
3709 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
48
Assuming the condition is false
49
Taking false branch
3710 auto *OldType = OldQType->castAs<FunctionProtoType>();
3711 const FunctionType *OldTypeForComparison
3712 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3713 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3714 assert(OldQTypeForComparison.isCanonical())(static_cast <bool> (OldQTypeForComparison.isCanonical(
)) ? void (0) : __assert_fail ("OldQTypeForComparison.isCanonical()"
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 3714, __extension__ __PRETTY_FUNCTION__))
;
3715 }
3716
3717 if (haveIncompatibleLanguageLinkages(Old, New)) {
50
Calling 'haveIncompatibleLanguageLinkages<clang::FunctionDecl>'
59
Returning from 'haveIncompatibleLanguageLinkages<clang::FunctionDecl>'
60
Taking false branch
3718 // As a special case, retain the language linkage from previous
3719 // declarations of a friend function as an extension.
3720 //
3721 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3722 // and is useful because there's otherwise no way to specify language
3723 // linkage within class scope.
3724 //
3725 // Check cautiously as the friend object kind isn't yet complete.
3726 if (New->getFriendObjectKind() != Decl::FOK_None) {
3727 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3728 Diag(OldLocation, PrevDiag);
3729 } else {
3730 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3731 Diag(OldLocation, PrevDiag);
3732 return true;
3733 }
3734 }
3735
3736 // If the function types are compatible, merge the declarations. Ignore the
3737 // exception specifier because it was already checked above in
3738 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3739 // about incompatible types under -fms-compatibility.
3740 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
61
Assuming the condition is false
62
Taking false branch
3741 NewQType))
3742 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3743
3744 // If the types are imprecise (due to dependent constructs in friends or
3745 // local extern declarations), it's OK if they differ. We'll check again
3746 // during instantiation.
3747 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
63
Calling 'Sema::canFullyTypeCheckRedeclaration'
67
Returning from 'Sema::canFullyTypeCheckRedeclaration'
3748 return false;
3749
3750 // Fall through for conflicting redeclarations and redefinitions.
3751 }
3752
3753 // C: Function types need to be compatible, not identical. This handles
3754 // duplicate function decls like "void f(int); void f(enum X);" properly.
3755 if (!getLangOpts().CPlusPlus &&
68
Assuming field 'CPlusPlus' is 0
70
Taking true branch
3756 Context.typesAreCompatible(OldQType, NewQType)) {
69
Assuming the condition is true
3757 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
71
Assuming the object is not a 'FunctionType'
3758 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
72
Assuming the object is not a 'FunctionType'
73
'NewFuncType' initialized to a null pointer value
3759 const FunctionProtoType *OldProto = nullptr;
3760 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
74
Assuming 'MergeTypeWithOld' is true
75
Assuming 'NewFuncType' is a 'FunctionNoProtoType'
3761 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
76
Assuming 'OldProto' is non-null
3762 // The old declaration provided a function prototype, but the
3763 // new declaration does not. Merge in the prototype.
3764 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~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 3764, __extension__ __PRETTY_FUNCTION__))
;
77
Taking true branch
78
'?' condition is true
3765 SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3766 NewQType =
3767 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
79
Called C++ object pointer is null
3768 OldProto->getExtProtoInfo());
3769 New->setType(NewQType);
3770 New->setHasInheritedPrototype();
3771
3772 // Synthesize parameters with the same types.
3773 SmallVector<ParmVarDecl*, 16> Params;
3774 for (const auto &ParamType : OldProto->param_types()) {
3775 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3776 SourceLocation(), nullptr,
3777 ParamType, /*TInfo=*/nullptr,
3778 SC_None, nullptr);
3779 Param->setScopeInfo(0, Params.size());
3780 Param->setImplicit();
3781 Params.push_back(Param);
3782 }
3783
3784 New->setParams(Params);
3785 }
3786
3787 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3788 }
3789
3790 // Check if the function types are compatible when pointer size address
3791 // spaces are ignored.
3792 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
3793 return false;
3794
3795 // GNU C permits a K&R definition to follow a prototype declaration
3796 // if the declared types of the parameters in the K&R definition
3797 // match the types in the prototype declaration, even when the
3798 // promoted types of the parameters from the K&R definition differ
3799 // from the types in the prototype. GCC then keeps the types from
3800 // the prototype.
3801 //
3802 // If a variadic prototype is followed by a non-variadic K&R definition,
3803 // the K&R definition becomes variadic. This is sort of an edge case, but
3804 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3805 // C99 6.9.1p8.
3806 if (!getLangOpts().CPlusPlus &&
3807 Old->hasPrototype() && !New->hasPrototype() &&
3808 New->getType()->getAs<FunctionProtoType>() &&
3809 Old->getNumParams() == New->getNumParams()) {
3810 SmallVector<QualType, 16> ArgTypes;
3811 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3812 const FunctionProtoType *OldProto
3813 = Old->getType()->getAs<FunctionProtoType>();
3814 const FunctionProtoType *NewProto
3815 = New->getType()->getAs<FunctionProtoType>();
3816
3817 // Determine whether this is the GNU C extension.
3818 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3819 NewProto->getReturnType());
3820 bool LooseCompatible = !MergedReturn.isNull();
3821 for (unsigned Idx = 0, End = Old->getNumParams();
3822 LooseCompatible && Idx != End; ++Idx) {
3823 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3824 ParmVarDecl *NewParm = New->getParamDecl(Idx);
3825 if (Context.typesAreCompatible(OldParm->getType(),
3826 NewProto->getParamType(Idx))) {
3827 ArgTypes.push_back(NewParm->getType());
3828 } else if (Context.typesAreCompatible(OldParm->getType(),
3829 NewParm->getType(),
3830 /*CompareUnqualified=*/true)) {
3831 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3832 NewProto->getParamType(Idx) };
3833 Warnings.push_back(Warn);
3834 ArgTypes.push_back(NewParm->getType());
3835 } else
3836 LooseCompatible = false;
3837 }
3838
3839 if (LooseCompatible) {
3840 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3841 Diag(Warnings[Warn].NewParm->getLocation(),
3842 diag::ext_param_promoted_not_compatible_with_prototype)
3843 << Warnings[Warn].PromotedType
3844 << Warnings[Warn].OldParm->getType();
3845 if (Warnings[Warn].OldParm->getLocation().isValid())
3846 Diag(Warnings[Warn].OldParm->getLocation(),
3847 diag::note_previous_declaration);
3848 }
3849
3850 if (MergeTypeWithOld)
3851 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3852 OldProto->getExtProtoInfo()));
3853 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3854 }
3855
3856 // Fall through to diagnose conflicting types.
3857 }
3858
3859 // A function that has already been declared has been redeclared or
3860 // defined with a different type; show an appropriate diagnostic.
3861
3862 // If the previous declaration was an implicitly-generated builtin
3863 // declaration, then at the very least we should use a specialized note.
3864 unsigned BuiltinID;
3865 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3866 // If it's actually a library-defined builtin function like 'malloc'
3867 // or 'printf', just warn about the incompatible redeclaration.
3868 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3869 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3870 Diag(OldLocation, diag::note_previous_builtin_declaration)
3871 << Old << Old->getType();
3872 return false;
3873 }
3874
3875 PrevDiag = diag::note_previous_builtin_declaration;
3876 }
3877
3878 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3879 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3880 return true;
3881}
3882
3883/// Completes the merge of two function declarations that are
3884/// known to be compatible.
3885///
3886/// This routine handles the merging of attributes and other
3887/// properties of function declarations from the old declaration to
3888/// the new declaration, once we know that New is in fact a
3889/// redeclaration of Old.
3890///
3891/// \returns false
3892bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3893 Scope *S, bool MergeTypeWithOld) {
3894 // Merge the attributes
3895 mergeDeclAttributes(New, Old);
3896
3897 // Merge "pure" flag.
3898 if (Old->isPure())
3899 New->setPure();
3900
3901 // Merge "used" flag.
3902 if (Old->getMostRecentDecl()->isUsed(false))
3903 New->setIsUsed();
3904
3905 // Merge attributes from the parameters. These can mismatch with K&R
3906 // declarations.
3907 if (New->getNumParams() == Old->getNumParams())
3908 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3909 ParmVarDecl *NewParam = New->getParamDecl(i);
3910 ParmVarDecl *OldParam = Old->getParamDecl(i);
3911 mergeParamDeclAttributes(NewParam, OldParam, *this);
3912 mergeParamDeclTypes(NewParam, OldParam, *this);
3913 }
3914
3915 if (getLangOpts().CPlusPlus)
3916 return MergeCXXFunctionDecl(New, Old, S);
3917
3918 // Merge the function types so the we get the composite types for the return
3919 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3920 // was visible.
3921 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3922 if (!Merged.isNull() && MergeTypeWithOld)
3923 New->setType(Merged);
3924
3925 return false;
3926}
3927
3928void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3929 ObjCMethodDecl *oldMethod) {
3930 // Merge the attributes, including deprecated/unavailable
3931 AvailabilityMergeKind MergeKind =
3932 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3933 ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
3934 : AMK_ProtocolImplementation)
3935 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3936 : AMK_Override;
3937
3938 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3939
3940 // Merge attributes from the parameters.
3941 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3942 oe = oldMethod->param_end();
3943 for (ObjCMethodDecl::param_iterator
3944 ni = newMethod->param_begin(), ne = newMethod->param_end();
3945 ni != ne && oi != oe; ++ni, ++oi)
3946 mergeParamDeclAttributes(*ni, *oi, *this);
3947
3948 CheckObjCMethodOverride(newMethod, oldMethod);
3949}
3950
3951static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3952 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~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 3952, __extension__ __PRETTY_FUNCTION__))
;
3953
3954 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3955 ? diag::err_redefinition_different_type
3956 : diag::err_redeclaration_different_type)
3957 << New->getDeclName() << New->getType() << Old->getType();
3958
3959 diag::kind PrevDiag;
3960 SourceLocation OldLocation;
3961 std::tie(PrevDiag, OldLocation)
3962 = getNoteDiagForInvalidRedeclaration(Old, New);
3963 S.Diag(OldLocation, PrevDiag);
3964 New->setInvalidDecl();
3965}
3966
3967/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3968/// scope as a previous declaration 'Old'. Figure out how to merge their types,
3969/// emitting diagnostics as appropriate.
3970///
3971/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3972/// to here in AddInitializerToDecl. We can't check them before the initializer
3973/// is attached.
3974void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3975 bool MergeTypeWithOld) {
3976 if (New->isInvalidDecl() || Old->isInvalidDecl())
3977 return;
3978
3979 QualType MergedT;
3980 if (getLangOpts().CPlusPlus) {
3981 if (New->getType()->isUndeducedType()) {
3982 // We don't know what the new type is until the initializer is attached.
3983 return;
3984 } else if (Context.hasSameType(New->getType(), Old->getType())) {
3985 // These could still be something that needs exception specs checked.
3986 return MergeVarDeclExceptionSpecs(New, Old);
3987 }
3988 // C++ [basic.link]p10:
3989 // [...] the types specified by all declarations referring to a given
3990 // object or function shall be identical, except that declarations for an
3991 // array object can specify array types that differ by the presence or
3992 // absence of a major array bound (8.3.4).
3993 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3994 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3995 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3996
3997 // We are merging a variable declaration New into Old. If it has an array
3998 // bound, and that bound differs from Old's bound, we should diagnose the
3999 // mismatch.
4000 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4001 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4002 PrevVD = PrevVD->getPreviousDecl()) {
4003 QualType PrevVDTy = PrevVD->getType();
4004 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4005 continue;
4006
4007 if (!Context.hasSameType(New->getType(), PrevVDTy))
4008 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4009 }
4010 }
4011
4012 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4013 if (Context.hasSameType(OldArray->getElementType(),
4014 NewArray->getElementType()))
4015 MergedT = New->getType();
4016 }
4017 // FIXME: Check visibility. New is hidden but has a complete type. If New
4018 // has no array bound, it should not inherit one from Old, if Old is not
4019 // visible.
4020 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4021 if (Context.hasSameType(OldArray->getElementType(),
4022 NewArray->getElementType()))
4023 MergedT = Old->getType();
4024 }
4025 }
4026 else if (New->getType()->isObjCObjectPointerType() &&
4027 Old->getType()->isObjCObjectPointerType()) {
4028 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4029 Old->getType());
4030 }
4031 } else {
4032 // C 6.2.7p2:
4033 // All declarations that refer to the same object or function shall have
4034 // compatible type.
4035 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4036 }
4037 if (MergedT.isNull()) {
4038 // It's OK if we couldn't merge types if either type is dependent, for a
4039 // block-scope variable. In other cases (static data members of class
4040 // templates, variable templates, ...), we require the types to be
4041 // equivalent.
4042 // FIXME: The C++ standard doesn't say anything about this.
4043 if ((New->getType()->isDependentType() ||
4044 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4045 // If the old type was dependent, we can't merge with it, so the new type
4046 // becomes dependent for now. We'll reproduce the original type when we
4047 // instantiate the TypeSourceInfo for the variable.
4048 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4049 New->setType(Context.DependentTy);
4050 return;
4051 }
4052 return diagnoseVarDeclTypeMismatch(*this, New, Old);
4053 }
4054
4055 // Don't actually update the type on the new declaration if the old
4056 // declaration was an extern declaration in a different scope.
4057 if (MergeTypeWithOld)
4058 New->setType(MergedT);
4059}
4060
4061static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4062 LookupResult &Previous) {
4063 // C11 6.2.7p4:
4064 // For an identifier with internal or external linkage declared
4065 // in a scope in which a prior declaration of that identifier is
4066 // visible, if the prior declaration specifies internal or
4067 // external linkage, the type of the identifier at the later
4068 // declaration becomes the composite type.
4069 //
4070 // If the variable isn't visible, we do not merge with its type.
4071 if (Previous.isShadowed())
4072 return false;
4073
4074 if (S.getLangOpts().CPlusPlus) {
4075 // C++11 [dcl.array]p3:
4076 // If there is a preceding declaration of the entity in the same
4077 // scope in which the bound was specified, an omitted array bound
4078 // is taken to be the same as in that earlier declaration.
4079 return NewVD->isPreviousDeclInSameBlockScope() ||
4080 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4081 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4082 } else {
4083 // If the old declaration was function-local, don't merge with its
4084 // type unless we're in the same function.
4085 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4086 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4087 }
4088}
4089
4090/// MergeVarDecl - We just parsed a variable 'New' which has the same name
4091/// and scope as a previous declaration 'Old'. Figure out how to resolve this
4092/// situation, merging decls or emitting diagnostics as appropriate.
4093///
4094/// Tentative definition rules (C99 6.9.2p2) are checked by
4095/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4096/// definitions here, since the initializer hasn't been attached.
4097///
4098void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4099 // If the new decl is already invalid, don't do any other checking.
4100 if (New->isInvalidDecl())
4101 return;
4102
4103 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4104 return;
4105
4106 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4107
4108 // Verify the old decl was also a variable or variable template.
4109 VarDecl *Old = nullptr;
4110 VarTemplateDecl *OldTemplate = nullptr;
4111 if (Previous.isSingleResult()) {
4112 if (NewTemplate) {
4113 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4114 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4115
4116 if (auto *Shadow =
4117 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4118 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4119 return New->setInvalidDecl();
4120 } else {
4121 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4122
4123 if (auto *Shadow =
4124 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4125 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4126 return New->setInvalidDecl();
4127 }
4128 }
4129 if (!Old) {
4130 Diag(New->getLocation(), diag::err_redefinition_different_kind)
4131 << New->getDeclName();
4132 notePreviousDefinition(Previous.getRepresentativeDecl(),
4133 New->getLocation());
4134 return New->setInvalidDecl();
4135 }
4136
4137 // If the old declaration was found in an inline namespace and the new
4138 // declaration was qualified, update the DeclContext to match.
4139 adjustDeclContextForDeclaratorDecl(New, Old);
4140
4141 // Ensure the template parameters are compatible.
4142 if (NewTemplate &&
4143 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4144 OldTemplate->getTemplateParameters(),
4145 /*Complain=*/true, TPL_TemplateMatch))
4146 return New->setInvalidDecl();
4147
4148 // C++ [class.mem]p1:
4149 // A member shall not be declared twice in the member-specification [...]
4150 //
4151 // Here, we need only consider static data members.
4152 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4153 Diag(New->getLocation(), diag::err_duplicate_member)
4154 << New->getIdentifier();
4155 Diag(Old->getLocation(), diag::note_previous_declaration);
4156 New->setInvalidDecl();
4157 }
4158
4159 mergeDeclAttributes(New, Old);
4160 // Warn if an already-declared variable is made a weak_import in a subsequent
4161 // declaration
4162 if (New->hasAttr<WeakImportAttr>() &&
4163 Old->getStorageClass() == SC_None &&
4164 !Old->hasAttr<WeakImportAttr>()) {
4165 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4166 Diag(Old->getLocation(), diag::note_previous_declaration);
4167 // Remove weak_import attribute on new declaration.
4168 New->dropAttr<WeakImportAttr>();
4169 }
4170
4171 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4172 if (!Old->hasAttr<InternalLinkageAttr>()) {
4173 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4174 << ILA;
4175 Diag(Old->getLocation(), diag::note_previous_declaration);
4176 New->dropAttr<InternalLinkageAttr>();
4177 }
4178
4179 // Merge the types.
4180 VarDecl *MostRecent = Old->getMostRecentDecl();
4181 if (MostRecent != Old) {
4182 MergeVarDeclTypes(New, MostRecent,
4183 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4184 if (New->isInvalidDecl())
4185 return;
4186 }
4187
4188 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4189 if (New->isInvalidDecl())
4190 return;
4191
4192 diag::kind PrevDiag;
4193 SourceLocation OldLocation;
4194 std::tie(PrevDiag, OldLocation) =
4195 getNoteDiagForInvalidRedeclaration(Old, New);
4196
4197 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4198 if (New->getStorageClass() == SC_Static &&
4199 !New->isStaticDataMember() &&
4200 Old->hasExternalFormalLinkage()) {
4201 if (getLangOpts().MicrosoftExt) {
4202 Diag(New->getLocation(), diag::ext_static_non_static)
4203 << New->getDeclName();
4204 Diag(OldLocation, PrevDiag);
4205 } else {
4206 Diag(New->getLocation(), diag::err_static_non_static)
4207 << New->getDeclName();
4208 Diag(OldLocation, PrevDiag);
4209 return New->setInvalidDecl();
4210 }
4211 }
4212 // C99 6.2.2p4:
4213 // For an identifier declared with the storage-class specifier
4214 // extern in a scope in which a prior declaration of that
4215 // identifier is visible,23) if the prior declaration specifies
4216 // internal or external linkage, the linkage of the identifier at
4217 // the later declaration is the same as the linkage specified at
4218 // the prior declaration. If no prior declaration is visible, or
4219 // if the prior declaration specifies no linkage, then the
4220 // identifier has external linkage.
4221 if (New->hasExternalStorage() && Old->hasLinkage())
4222 /* Okay */;
4223 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4224 !New->isStaticDataMember() &&
4225 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4226 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4227 Diag(OldLocation, PrevDiag);
4228 return New->setInvalidDecl();
4229 }
4230
4231 // Check if extern is followed by non-extern and vice-versa.
4232 if (New->hasExternalStorage() &&
4233 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4234 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4235 Diag(OldLocation, PrevDiag);
4236 return New->setInvalidDecl();
4237 }
4238 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4239 !New->hasExternalStorage()) {
4240 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4241 Diag(OldLocation, PrevDiag);
4242 return New->setInvalidDecl();
4243 }
4244
4245 if (CheckRedeclarationModuleOwnership(New, Old))
4246 return;
4247
4248 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4249
4250 // FIXME: The test for external storage here seems wrong? We still
4251 // need to check for mismatches.
4252 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4253 // Don't complain about out-of-line definitions of static members.
4254 !(Old->getLexicalDeclContext()->isRecord() &&
4255 !New->getLexicalDeclContext()->isRecord())) {
4256 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4257 Diag(OldLocation, PrevDiag);
4258 return New->setInvalidDecl();
4259 }
4260
4261 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4262 if (VarDecl *Def = Old->getDefinition()) {
4263 // C++1z [dcl.fcn.spec]p4:
4264 // If the definition of a variable appears in a translation unit before
4265 // its first declaration as inline, the program is ill-formed.
4266 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4267 Diag(Def->getLocation(), diag::note_previous_definition);
4268 }
4269 }
4270
4271 // If this redeclaration makes the variable inline, we may need to add it to
4272 // UndefinedButUsed.
4273 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4274 !Old->getDefinition() && !New->isThisDeclarationADefinition())
4275 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4276 SourceLocation()));
4277
4278 if (New->getTLSKind() != Old->getTLSKind()) {
4279 if (!Old->getTLSKind()) {
4280 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4281 Diag(OldLocation, PrevDiag);
4282 } else if (!New->getTLSKind()) {
4283 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4284 Diag(OldLocation, PrevDiag);
4285 } else {
4286 // Do not allow redeclaration to change the variable between requiring
4287 // static and dynamic initialization.
4288 // FIXME: GCC allows this, but uses the TLS keyword on the first
4289 // declaration to determine the kind. Do we need to be compatible here?
4290 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4291 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4292 Diag(OldLocation, PrevDiag);
4293 }
4294 }
4295
4296 // C++ doesn't have tentative definitions, so go right ahead and check here.
4297 if (getLangOpts().CPlusPlus &&
4298 New->isThisDeclarationADefinition() == VarDecl::Definition) {
4299 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4300 Old->getCanonicalDecl()->isConstexpr()) {
4301 // This definition won't be a definition any more once it's been merged.
4302 Diag(New->getLocation(),
4303 diag::warn_deprecated_redundant_constexpr_static_def);
4304 } else if (VarDecl *Def = Old->getDefinition()) {
4305 if (checkVarDeclRedefinition(Def, New))
4306 return;
4307 }
4308 }
4309
4310 if (haveIncompatibleLanguageLinkages(Old, New)) {
4311 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4312 Diag(OldLocation, PrevDiag);
4313 New->setInvalidDecl();
4314 return;
4315 }
4316
4317 // Merge "used" flag.
4318 if (Old->getMostRecentDecl()->isUsed(false))
4319 New->setIsUsed();
4320
4321 // Keep a chain of previous declarations.
4322 New->setPreviousDecl(Old);
4323 if (NewTemplate)
4324 NewTemplate->setPreviousDecl(OldTemplate);
4325
4326 // Inherit access appropriately.
4327 New->setAccess(Old->getAccess());
4328 if (NewTemplate)
4329 NewTemplate->setAccess(New->getAccess());
4330
4331 if (Old->isInline())
4332 New->setImplicitlyInline();
4333}
4334
4335void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4336 SourceManager &SrcMgr = getSourceManager();
4337 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4338 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4339 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4340 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4341 auto &HSI = PP.getHeaderSearchInfo();
4342 StringRef HdrFilename =
4343 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4344
4345 auto noteFromModuleOrInclude = [&](Module *Mod,
4346 SourceLocation IncLoc) -> bool {
4347 // Redefinition errors with modules are common with non modular mapped
4348 // headers, example: a non-modular header H in module A that also gets
4349 // included directly in a TU. Pointing twice to the same header/definition
4350 // is confusing, try to get better diagnostics when modules is on.
4351 if (IncLoc.isValid()) {
4352 if (Mod) {
4353 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4354 << HdrFilename.str() << Mod->getFullModuleName();
4355 if (!Mod->DefinitionLoc.isInvalid())
4356 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4357 << Mod->getFullModuleName();
4358 } else {
4359 Diag(IncLoc, diag::note_redefinition_include_same_file)
4360 << HdrFilename.str();
4361 }
4362 return true;
4363 }
4364
4365 return false;
4366 };
4367
4368 // Is it the same file and same offset? Provide more information on why
4369 // this leads to a redefinition error.
4370 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4371 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4372 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4373 bool EmittedDiag =
4374 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4375 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4376
4377 // If the header has no guards, emit a note suggesting one.
4378 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4379 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4380
4381 if (EmittedDiag)
4382 return;
4383 }
4384
4385 // Redefinition coming from different files or couldn't do better above.
4386 if (Old->getLocation().isValid())
4387 Diag(Old->getLocation(), diag::note_previous_definition);
4388}
4389
4390/// We've just determined that \p Old and \p New both appear to be definitions
4391/// of the same variable. Either diagnose or fix the problem.
4392bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4393 if (!hasVisibleDefinition(Old) &&
4394 (New->getFormalLinkage() == InternalLinkage ||
4395 New->isInline() ||
4396 New->getDescribedVarTemplate() ||
4397 New->getNumTemplateParameterLists() ||
4398 New->getDeclContext()->isDependentContext())) {
4399 // The previous definition is hidden, and multiple definitions are
4400 // permitted (in separate TUs). Demote this to a declaration.
4401 New->demoteThisDefinitionToDeclaration();
4402
4403 // Make the canonical definition visible.
4404 if (auto *OldTD = Old->getDescribedVarTemplate())
4405 makeMergedDefinitionVisible(OldTD);
4406 makeMergedDefinitionVisible(Old);
4407 return false;
4408 } else {
4409 Diag(New->getLocation(), diag::err_redefinition) << New;
4410 notePreviousDefinition(Old, New->getLocation());
4411 New->setInvalidDecl();
4412 return true;
4413 }
4414}
4415
4416/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4417/// no declarator (e.g. "struct foo;") is parsed.
4418Decl *
4419Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4420 RecordDecl *&AnonRecord) {
4421 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4422 AnonRecord);
4423}
4424
4425// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4426// disambiguate entities defined in different scopes.
4427// While the VS2015 ABI fixes potential miscompiles, it is also breaks
4428// compatibility.
4429// We will pick our mangling number depending on which version of MSVC is being
4430// targeted.
4431static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4432 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4433 ? S->getMSCurManglingNumber()
4434 : S->getMSLastManglingNumber();
4435}
4436
4437void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4438 if (!Context.getLangOpts().CPlusPlus)
4439 return;
4440
4441 if (isa<CXXRecordDecl>(Tag->getParent())) {
4442 // If this tag is the direct child of a class, number it if
4443 // it is anonymous.
4444 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4445 return;
4446 MangleNumberingContext &MCtx =
4447 Context.getManglingNumberContext(Tag->getParent());
4448 Context.setManglingNumber(
4449 Tag, MCtx.getManglingNumber(
4450 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4451 return;
4452 }
4453
4454 // If this tag isn't a direct child of a class, number it if it is local.
4455 MangleNumberingContext *MCtx;
4456 Decl *ManglingContextDecl;
4457 std::tie(MCtx, ManglingContextDecl) =
4458 getCurrentMangleNumberContext(Tag->getDeclContext());
4459 if (MCtx) {
4460 Context.setManglingNumber(
4461 Tag, MCtx->getManglingNumber(
4462 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4463 }
4464}
4465
4466namespace {
4467struct NonCLikeKind {
4468 enum {
4469 None,
4470 BaseClass,
4471 DefaultMemberInit,
4472 Lambda,
4473 Friend,
4474 OtherMember,
4475 Invalid,
4476 } Kind = None;
4477 SourceRange Range;
4478
4479 explicit operator bool() { return Kind != None; }
4480};
4481}
4482
4483/// Determine whether a class is C-like, according to the rules of C++
4484/// [dcl.typedef] for anonymous classes with typedef names for linkage.
4485static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4486 if (RD->isInvalidDecl())
4487 return {NonCLikeKind::Invalid, {}};
4488
4489 // C++ [dcl.typedef]p9: [P1766R1]
4490 // An unnamed class with a typedef name for linkage purposes shall not
4491 //
4492 // -- have any base classes
4493 if (RD->getNumBases())
4494 return {NonCLikeKind::BaseClass,
4495 SourceRange(RD->bases_begin()->getBeginLoc(),
4496 RD->bases_end()[-1].getEndLoc())};
4497 bool Invalid = false;
4498 for (Decl *D : RD->decls()) {
4499 // Don't complain about things we already diagnosed.
4500 if (D->isInvalidDecl()) {
4501 Invalid = true;
4502 continue;
4503 }
4504
4505 // -- have any [...] default member initializers
4506 if (auto *FD = dyn_cast<FieldDecl>(D)) {
4507 if (FD->hasInClassInitializer()) {
4508 auto *Init = FD->getInClassInitializer();
4509 return {NonCLikeKind::DefaultMemberInit,
4510 Init ? Init->getSourceRange() : D->getSourceRange()};
4511 }
4512 continue;
4513 }
4514
4515 // FIXME: We don't allow friend declarations. This violates the wording of
4516 // P1766, but not the intent.
4517 if (isa<FriendDecl>(D))
4518 return {NonCLikeKind::Friend, D->getSourceRange()};
4519
4520 // -- declare any members other than non-static data members, member
4521 // enumerations, or member classes,
4522 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4523 isa<EnumDecl>(D))
4524 continue;
4525 auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4526 if (!MemberRD) {
4527 if (D->isImplicit())
4528 continue;
4529 return {NonCLikeKind::OtherMember, D->getSourceRange()};
4530 }
4531
4532 // -- contain a lambda-expression,
4533 if (MemberRD->isLambda())
4534 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4535
4536 // and all member classes shall also satisfy these requirements
4537 // (recursively).
4538 if (MemberRD->isThisDeclarationADefinition()) {
4539 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4540 return Kind;
4541 }
4542 }
4543
4544 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4545}
4546
4547void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4548 TypedefNameDecl *NewTD) {
4549 if (TagFromDeclSpec->isInvalidDecl())
4550 return;
4551
4552 // Do nothing if the tag already has a name for linkage purposes.
4553 if (TagFromDeclSpec->hasNameForLinkage())
4554 return;
4555
4556 // A well-formed anonymous tag must always be a TUK_Definition.
4557 assert(TagFromDeclSpec->isThisDeclarationADefinition())(static_cast <bool> (TagFromDeclSpec->isThisDeclarationADefinition
()) ? void (0) : __assert_fail ("TagFromDeclSpec->isThisDeclarationADefinition()"
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 4557, __extension__ __PRETTY_FUNCTION__))
;
4558
4559 // The type must match the tag exactly; no qualifiers allowed.
4560 if (!Context.hasSameType(NewTD->getUnderlyingType(),
4561 Context.getTagDeclType(TagFromDeclSpec))) {
4562 if (getLangOpts().CPlusPlus)
4563 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4564 return;
4565 }
4566
4567 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4568 // An unnamed class with a typedef name for linkage purposes shall [be
4569 // C-like].
4570 //
4571 // FIXME: Also diagnose if we've already computed the linkage. That ideally
4572 // shouldn't happen, but there are constructs that the language rule doesn't
4573 // disallow for which we can't reasonably avoid computing linkage early.
4574 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4575 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4576 : NonCLikeKind();
4577 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4578 if (NonCLike || ChangesLinkage) {
4579 if (NonCLike.Kind == NonCLikeKind::Invalid)
4580 return;
4581
4582 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4583 if (ChangesLinkage) {
4584 // If the linkage changes, we can't accept this as an extension.
4585 if (NonCLike.Kind == NonCLikeKind::None)
4586 DiagID = diag::err_typedef_changes_linkage;
4587 else
4588 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4589 }
4590
4591 SourceLocation FixitLoc =
4592 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4593 llvm::SmallString<40> TextToInsert;
4594 TextToInsert += ' ';
4595 TextToInsert += NewTD->getIdentifier()->getName();
4596
4597 Diag(FixitLoc, DiagID)
4598 << isa<TypeAliasDecl>(NewTD)
4599 << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4600 if (NonCLike.Kind != NonCLikeKind::None) {
4601 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4602 << NonCLike.Kind - 1 << NonCLike.Range;
4603 }
4604 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4605 << NewTD << isa<TypeAliasDecl>(NewTD);
4606
4607 if (ChangesLinkage)
4608 return;
4609 }
4610
4611 // Otherwise, set this as the anon-decl typedef for the tag.
4612 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4613}
4614
4615static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4616 switch (T) {
4617 case DeclSpec::TST_class:
4618 return 0;
4619 case DeclSpec::TST_struct:
4620 return 1;
4621 case DeclSpec::TST_interface:
4622 return 2;
4623 case DeclSpec::TST_union:
4624 return 3;
4625 case DeclSpec::TST_enum:
4626 return 4;
4627 default:
4628 llvm_unreachable("unexpected type specifier")::llvm::llvm_unreachable_internal("unexpected type specifier"
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 4628)
;
4629 }
4630}
4631
4632/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4633/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4634/// parameters to cope with template friend declarations.
4635Decl *
4636Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4637 MultiTemplateParamsArg TemplateParams,
4638 bool IsExplicitInstantiation,
4639 RecordDecl *&AnonRecord) {
4640 Decl *TagD = nullptr;
4641 TagDecl *Tag = nullptr;
4642 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4643 DS.getTypeSpecType() == DeclSpec::TST_struct ||
4644 DS.getTypeSpecType() == DeclSpec::TST_interface ||
4645 DS.getTypeSpecType() == DeclSpec::TST_union ||
4646 DS.getTypeSpecType() == DeclSpec::TST_enum) {
4647 TagD = DS.getRepAsDecl();
4648
4649 if (!TagD) // We probably had an error
4650 return nullptr;
4651
4652 // Note that the above type specs guarantee that the
4653 // type rep is a Decl, whereas in many of the others
4654 // it's a Type.
4655 if (isa<TagDecl>(TagD))
4656 Tag = cast<TagDecl>(TagD);
4657 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4658 Tag = CTD->getTemplatedDecl();
4659 }
4660
4661 if (Tag) {
4662 handleTagNumbering(Tag, S);
4663 Tag->setFreeStanding();
4664 if (Tag->isInvalidDecl())
4665 return Tag;
4666 }
4667
4668 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4669 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4670 // or incomplete types shall not be restrict-qualified."
4671 if (TypeQuals & DeclSpec::TQ_restrict)
4672 Diag(DS.getRestrictSpecLoc(),
4673 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4674 << DS.getSourceRange();
4675 }
4676
4677 if (DS.isInlineSpecified())
4678 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4679 << getLangOpts().CPlusPlus17;
4680
4681 if (DS.hasConstexprSpecifier()) {
4682 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4683 // and definitions of functions and variables.
4684 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4685 // the declaration of a function or function template
4686 if (Tag)
4687 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4688 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4689 << static_cast<int>(DS.getConstexprSpecifier());
4690 else
4691 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4692 << static_cast<int>(DS.getConstexprSpecifier());
4693 // Don't emit warnings after this error.
4694 return TagD;
4695 }
4696
4697 DiagnoseFunctionSpecifiers(DS);
4698
4699 if (DS.isFriendSpecified()) {
4700 // If we're dealing with a decl but not a TagDecl, assume that
4701 // whatever routines created it handled the friendship aspect.
4702 if (TagD && !Tag)
4703 return nullptr;
4704 return ActOnFriendTypeDecl(S, DS, TemplateParams);
4705 }
4706
4707 const CXXScopeSpec &SS = DS.getTypeSpecScope();
4708 bool IsExplicitSpecialization =
4709 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4710 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4711 !IsExplicitInstantiation && !IsExplicitSpecialization &&
4712 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4713 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4714 // nested-name-specifier unless it is an explicit instantiation
4715 // or an explicit specialization.
4716 //
4717 // FIXME: We allow class template partial specializations here too, per the
4718 // obvious intent of DR1819.
4719 //
4720 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4721 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4722 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4723 return nullptr;
4724 }
4725
4726 // Track whether this decl-specifier declares anything.
4727 bool DeclaresAnything = true;
4728
4729 // Handle anonymous struct definitions.
4730 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4731 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4732 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4733 if (getLangOpts().CPlusPlus ||
4734 Record->getDeclContext()->isRecord()) {
4735 // If CurContext is a DeclContext that can contain statements,
4736 // RecursiveASTVisitor won't visit the decls that
4737 // BuildAnonymousStructOrUnion() will put into CurContext.
4738 // Also store them here so that they can be part of the
4739 // DeclStmt that gets created in this case.
4740 // FIXME: Also return the IndirectFieldDecls created by
4741 // BuildAnonymousStructOr union, for the same reason?
4742 if (CurContext->isFunctionOrMethod())
4743 AnonRecord = Record;
4744 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4745 Context.getPrintingPolicy());
4746 }
4747
4748 DeclaresAnything = false;
4749 }
4750 }
4751
4752 // C11 6.7.2.1p2:
4753 // A struct-declaration that does not declare an anonymous structure or
4754 // anonymous union shall contain a struct-declarator-list.
4755 //
4756 // This rule also existed in C89 and C99; the grammar for struct-declaration
4757 // did not permit a struct-declaration without a struct-declarator-list.
4758 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4759 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4760 // Check for Microsoft C extension: anonymous struct/union member.
4761 // Handle 2 kinds of anonymous struct/union:
4762 // struct STRUCT;
4763 // union UNION;
4764 // and
4765 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
4766 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
4767 if ((Tag && Tag->getDeclName()) ||
4768 DS.getTypeSpecType() == DeclSpec::TST_typename) {
4769 RecordDecl *Record = nullptr;
4770 if (Tag)
4771 Record = dyn_cast<RecordDecl>(Tag);
4772 else if (const RecordType *RT =
4773 DS.getRepAsType().get()->getAsStructureType())
4774 Record = RT->getDecl();
4775 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4776 Record = UT->getDecl();
4777
4778 if (Record && getLangOpts().MicrosoftExt) {
4779 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4780 << Record->isUnion() << DS.getSourceRange();
4781 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4782 }
4783
4784 DeclaresAnything = false;
4785 }
4786 }
4787
4788 // Skip all the checks below if we have a type error.
4789 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4790 (TagD && TagD->isInvalidDecl()))
4791 return TagD;
4792
4793 if (getLangOpts().CPlusPlus &&
4794 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4795 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4796 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4797 !Enum->getIdentifier() && !Enum->isInvalidDecl())
4798 DeclaresAnything = false;
4799
4800 if (!DS.isMissingDeclaratorOk()) {
4801 // Customize diagnostic for a typedef missing a name.
4802 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4803 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4804 << DS.getSourceRange();
4805 else
4806 DeclaresAnything = false;
4807 }
4808
4809 if (DS.isModulePrivateSpecified() &&
4810 Tag && Tag->getDeclContext()->isFunctionOrMethod())
4811 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4812 << Tag->getTagKind()
4813 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4814
4815 ActOnDocumentableDecl(TagD);
4816
4817 // C 6.7/2:
4818 // A declaration [...] shall declare at least a declarator [...], a tag,
4819 // or the members of an enumeration.
4820 // C++ [dcl.dcl]p3:
4821 // [If there are no declarators], and except for the declaration of an
4822 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
4823 // names into the program, or shall redeclare a name introduced by a
4824 // previous declaration.
4825 if (!DeclaresAnything) {
4826 // In C, we allow this as a (popular) extension / bug. Don't bother
4827 // producing further diagnostics for redundant qualifiers after this.
4828 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
4829 ? diag::err_no_declarators
4830 : diag::ext_no_declarators)
4831 << DS.getSourceRange();
4832 return TagD;
4833 }
4834
4835 // C++ [dcl.stc]p1:
4836 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4837 // init-declarator-list of the declaration shall not be empty.
4838 // C++ [dcl.fct.spec]p1:
4839 // If a cv-qualifier appears in a decl-specifier-seq, the
4840 // init-declarator-list of the declaration shall not be empty.
4841 //
4842 // Spurious qualifiers here appear to be valid in C.
4843 unsigned DiagID = diag::warn_standalone_specifier;
4844 if (getLangOpts().CPlusPlus)
4845 DiagID = diag::ext_standalone_specifier;
4846
4847 // Note that a linkage-specification sets a storage class, but
4848 // 'extern "C" struct foo;' is actually valid and not theoretically
4849 // useless.
4850 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4851 if (SCS == DeclSpec::SCS_mutable)
4852 // Since mutable is not a viable storage class specifier in C, there is
4853 // no reason to treat it as an extension. Instead, diagnose as an error.
4854 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4855 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4856 Diag(DS.getStorageClassSpecLoc(), DiagID)
4857 << DeclSpec::getSpecifierName(SCS);
4858 }
4859
4860 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4861 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4862 << DeclSpec::getSpecifierName(TSCS);
4863 if (DS.getTypeQualifiers()) {
4864 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4865 Diag(DS.getConstSpecLoc(), DiagID) << "const";
4866 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4867 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4868 // Restrict is covered above.
4869 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4870 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4871 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4872 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4873 }
4874
4875 // Warn about ignored type attributes, for example:
4876 // __attribute__((aligned)) struct A;
4877 // Attributes should be placed after tag to apply to type declaration.
4878 if (!DS.getAttributes().empty()) {
4879 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4880 if (TypeSpecType == DeclSpec::TST_class ||
4881 TypeSpecType == DeclSpec::TST_struct ||
4882 TypeSpecType == DeclSpec::TST_interface ||
4883 TypeSpecType == DeclSpec::TST_union ||
4884 TypeSpecType == DeclSpec::TST_enum) {
4885 for (const ParsedAttr &AL : DS.getAttributes())
4886 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4887 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
4888 }
4889 }
4890
4891 return TagD;
4892}
4893
4894/// We are trying to inject an anonymous member into the given scope;
4895/// check if there's an existing declaration that can't be overloaded.
4896///
4897/// \return true if this is a forbidden redeclaration
4898static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4899 Scope *S,
4900 DeclContext *Owner,
4901 DeclarationName Name,
4902 SourceLocation NameLoc,
4903 bool IsUnion) {
4904 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4905 Sema::ForVisibleRedeclaration);
4906 if (!SemaRef.LookupName(R, S)) return false;
4907
4908 // Pick a representative declaration.
4909 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4910 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~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 4910, __extension__ __PRETTY_FUNCTION__))
;
4911
4912 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4913 return false;
4914
4915 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4916 << IsUnion << Name;
4917 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4918
4919 return true;
4920}
4921
4922/// InjectAnonymousStructOrUnionMembers - Inject the members of the
4923/// anonymous struct or union AnonRecord into the owning context Owner
4924/// and scope S. This routine will be invoked just after we realize
4925/// that an unnamed union or struct is actually an anonymous union or
4926/// struct, e.g.,
4927///
4928/// @code
4929/// union {
4930/// int i;
4931/// float f;
4932/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4933/// // f into the surrounding scope.x
4934/// @endcode
4935///
4936/// This routine is recursive, injecting the names of nested anonymous
4937/// structs/unions into the owning context and scope as well.
4938static bool
4939InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4940 RecordDecl *AnonRecord, AccessSpecifier AS,
4941 SmallVectorImpl<NamedDecl *> &Chaining) {
4942 bool Invalid = false;
4943
4944 // Look every FieldDecl and IndirectFieldDecl with a name.
4945 for (auto *D : AnonRecord->decls()) {
4946 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4947 cast<NamedDecl>(D)->getDeclName()) {
4948 ValueDecl *VD = cast<ValueDecl>(D);
4949 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4950 VD->getLocation(),
4951 AnonRecord->isUnion())) {
4952 // C++ [class.union]p2:
4953 // The names of the members of an anonymous union shall be
4954 // distinct from the names of any other entity in the
4955 // scope in which the anonymous union is declared.
4956 Invalid = true;
4957 } else {
4958 // C++ [class.union]p2:
4959 // For the purpose of name lookup, after the anonymous union
4960 // definition, the members of the anonymous union are
4961 // considered to have been defined in the scope in which the
4962 // anonymous union is declared.
4963 unsigned OldChainingSize = Chaining.size();
4964 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4965 Chaining.append(IF->chain_begin(), IF->chain_end());
4966 else
4967 Chaining.push_back(VD);
4968
4969 assert(Chaining.size() >= 2)(static_cast <bool> (Chaining.size() >= 2) ? void (0
) : __assert_fail ("Chaining.size() >= 2", "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 4969, __extension__ __PRETTY_FUNCTION__))
;
4970 NamedDecl **NamedChain =
4971 new (SemaRef.Context)NamedDecl*[Chaining.size()];
4972 for (unsigned i = 0; i < Chaining.size(); i++)
4973 NamedChain[i] = Chaining[i];
4974
4975 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4976 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4977 VD->getType(), {NamedChain, Chaining.size()});
4978
4979 for (const auto *Attr : VD->attrs())
4980 IndirectField->addAttr(Attr->clone(SemaRef.Context));
4981
4982 IndirectField->setAccess(AS);
4983 IndirectField->setImplicit();
4984 SemaRef.PushOnScopeChains(IndirectField, S);
4985
4986 // That includes picking up the appropriate access specifier.
4987 if (AS != AS_none) IndirectField->setAccess(AS);
4988
4989 Chaining.resize(OldChainingSize);
4990 }
4991 }
4992 }
4993
4994 return Invalid;
4995}
4996
4997/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4998/// a VarDecl::StorageClass. Any error reporting is up to the caller:
4999/// illegal input values are mapped to SC_None.
5000static StorageClass
5001StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5002 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5003 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~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 5004, __extension__ __PRETTY_FUNCTION__))
5004 "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~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 5004, __extension__ __PRETTY_FUNCTION__))
;
5005 switch (StorageClassSpec) {
5006 case DeclSpec::SCS_unspecified: return SC_None;
5007 case DeclSpec::SCS_extern:
5008 if (DS.isExternInLinkageSpec())
5009 return SC_None;
5010 return SC_Extern;
5011 case DeclSpec::SCS_static: return SC_Static;
5012 case DeclSpec::SCS_auto: return SC_Auto;
5013 case DeclSpec::SCS_register: return SC_Register;
5014 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5015 // Illegal SCSs map to None: error reporting is up to the caller.
5016 case DeclSpec::SCS_mutable: // Fall through.
5017 case DeclSpec::SCS_typedef: return SC_None;
5018 }
5019 llvm_unreachable("unknown storage class specifier")::llvm::llvm_unreachable_internal("unknown storage class specifier"
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 5019)
;
5020}
5021
5022static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5023 assert(Record->hasInClassInitializer())(static_cast <bool> (Record->hasInClassInitializer()
) ? void (0) : __assert_fail ("Record->hasInClassInitializer()"
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 5023, __extension__ __PRETTY_FUNCTION__))
;
5024
5025 for (const auto *I : Record->decls()) {
5026 const auto *FD = dyn_cast<FieldDecl>(I);
5027 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5028 FD = IFD->getAnonField();
5029 if (FD && FD->hasInClassInitializer())
5030 return FD->getLocation();
5031 }
5032
5033 llvm_unreachable("couldn't find in-class initializer")::llvm::llvm_unreachable_internal("couldn't find in-class initializer"
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 5033)
;
5034}
5035
5036static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5037 SourceLocation DefaultInitLoc) {
5038 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5039 return;
5040
5041 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5042 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5043}
5044
5045static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5046 CXXRecordDecl *AnonUnion) {
5047 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5048 return;
5049
5050 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
5051}
5052
5053/// BuildAnonymousStructOrUnion - Handle the declaration of an
5054/// anonymous structure or union. Anonymous unions are a C++ feature
5055/// (C++ [class.union]) and a C11 feature; anonymous structures
5056/// are a C11 feature and GNU C++ extension.
5057Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5058 AccessSpecifier AS,
5059 RecordDecl *Record,
5060 const PrintingPolicy &Policy) {
5061 DeclContext *Owner = Record->getDeclContext();
5062
5063 // Diagnose whether this anonymous struct/union is an extension.
5064 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5065 Diag(Record->getLocation(), diag::ext_anonymous_union);
5066 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5067 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5068 else if (!Record->isUnion() && !getLangOpts().C11)
5069 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5070
5071 // C and C++ require different kinds of checks for anonymous
5072 // structs/unions.
5073 bool Invalid = false;
5074 if (getLangOpts().CPlusPlus) {
5075 const char *PrevSpec = nullptr;
5076 if (Record->isUnion()) {
5077 // C++ [class.union]p6:
5078 // C++17 [class.union.anon]p2:
5079 // Anonymous unions declared in a named namespace or in the
5080 // global namespace shall be declared static.
5081 unsigned DiagID;
5082 DeclContext *OwnerScope = Owner->getRedeclContext();
5083 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5084 (OwnerScope->isTranslationUnit() ||
5085 (OwnerScope->isNamespace() &&
5086 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5087 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5088 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5089
5090 // Recover by adding 'static'.
5091 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5092 PrevSpec, DiagID, Policy);
5093 }
5094 // C++ [class.union]p6:
5095 // A storage class is not allowed in a declaration of an
5096 // anonymous union in a class scope.
5097 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5098 isa<RecordDecl>(Owner)) {
5099 Diag(DS.getStorageClassSpecLoc(),
5100 diag::err_anonymous_union_with_storage_spec)
5101 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5102
5103 // Recover by removing the storage specifier.
5104 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5105 SourceLocation(),
5106 PrevSpec, DiagID, Context.getPrintingPolicy());
5107 }
5108 }
5109
5110 // Ignore const/volatile/restrict qualifiers.
5111 if (DS.getTypeQualifiers()) {
5112 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5113 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5114 << Record->isUnion() << "const"
5115 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5116 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5117 Diag(DS.getVolatileSpecLoc(),
5118 diag::ext_anonymous_struct_union_qualified)
5119 << Record->isUnion() << "volatile"
5120 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5121 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5122 Diag(DS.getRestrictSpecLoc(),
5123 diag::ext_anonymous_struct_union_qualified)
5124 << Record->isUnion() << "restrict"
5125 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5126 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5127 Diag(DS.getAtomicSpecLoc(),
5128 diag::ext_anonymous_struct_union_qualified)
5129 << Record->isUnion() << "_Atomic"
5130 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5131 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5132 Diag(DS.getUnalignedSpecLoc(),
5133 diag::ext_anonymous_struct_union_qualified)
5134 << Record->isUnion() << "__unaligned"
5135 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5136
5137 DS.ClearTypeQualifiers();
5138 }
5139
5140 // C++ [class.union]p2:
5141 // The member-specification of an anonymous union shall only
5142 // define non-static data members. [Note: nested types and
5143 // functions cannot be declared within an anonymous union. ]
5144 for (auto *Mem : Record->decls()) {
5145 // Ignore invalid declarations; we already diagnosed them.
5146 if (Mem->isInvalidDecl())
5147 continue;
5148
5149 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5150 // C++ [class.union]p3:
5151 // An anonymous union shall not have private or protected
5152 // members (clause 11).
5153 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~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 5153, __extension__ __PRETTY_FUNCTION__))
;
5154 if (FD->getAccess() != AS_public) {
5155 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5156 << Record->isUnion() << (FD->getAccess() == AS_protected);
5157 Invalid = true;
5158 }
5159
5160 // C++ [class.union]p1
5161 // An object of a class with a non-trivial constructor, a non-trivial
5162 // copy constructor, a non-trivial destructor, or a non-trivial copy
5163 // assignment operator cannot be a member of a union, nor can an
5164 // array of such objects.
5165 if (CheckNontrivialField(FD))
5166 Invalid = true;
5167 } else if (Mem->isImplicit()) {
5168 // Any implicit members are fine.
5169 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5170 // This is a type that showed up in an
5171 // elaborated-type-specifier inside the anonymous struct or
5172 // union, but which actually declares a type outside of the
5173 // anonymous struct or union. It's okay.
5174 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5175 if (!MemRecord->isAnonymousStructOrUnion() &&
5176 MemRecord->getDeclName()) {
5177 // Visual C++ allows type definition in anonymous struct or union.
5178 if (getLangOpts().MicrosoftExt)
5179 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5180 << Record->isUnion();
5181 else {
5182 // This is a nested type declaration.
5183 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5184 << Record->isUnion();
5185 Invalid = true;
5186 }
5187 } else {
5188 // This is an anonymous type definition within another anonymous type.
5189 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5190 // not part of standard C++.
5191 Diag(MemRecord->getLocation(),
5192 diag::ext_anonymous_record_with_anonymous_type)
5193 << Record->isUnion();
5194 }
5195 } else if (isa<AccessSpecDecl>(Mem)) {
5196 // Any access specifier is fine.
5197 } else if (isa<StaticAssertDecl>(Mem)) {
5198 // In C++1z, static_assert declarations are also fine.
5199 } else {
5200 // We have something that isn't a non-static data
5201 // member. Complain about it.
5202 unsigned DK = diag::err_anonymous_record_bad_member;
5203 if (isa<TypeDecl>(Mem))
5204 DK = diag::err_anonymous_record_with_type;
5205 else if (isa<FunctionDecl>(Mem))
5206 DK = diag::err_anonymous_record_with_function;
5207 else if (isa<VarDecl>(Mem))
5208 DK = diag::err_anonymous_record_with_static;
5209
5210 // Visual C++ allows type definition in anonymous struct or union.
5211 if (getLangOpts().MicrosoftExt &&
5212 DK == diag::err_anonymous_record_with_type)
5213 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5214 << Record->isUnion();
5215 else {
5216 Diag(Mem->getLocation(), DK) << Record->isUnion();
5217 Invalid = true;
5218 }
5219 }
5220 }
5221
5222 // C++11 [class.union]p8 (DR1460):
5223 // At most one variant member of a union may have a
5224 // brace-or-equal-initializer.
5225 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5226 Owner->isRecord())
5227 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5228 cast<CXXRecordDecl>(Record));
5229 }
5230
5231 if (!Record->isUnion() && !Owner->isRecord()) {
5232 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5233 << getLangOpts().CPlusPlus;
5234 Invalid = true;
5235 }
5236
5237 // C++ [dcl.dcl]p3:
5238 // [If there are no declarators], and except for the declaration of an
5239 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5240 // names into the program
5241 // C++ [class.mem]p2:
5242 // each such member-declaration shall either declare at least one member
5243 // name of the class or declare at least one unnamed bit-field
5244 //
5245 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5246 if (getLangOpts().CPlusPlus && Record->field_empty())
5247 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5248
5249 // Mock up a declarator.
5250 Declarator Dc(DS, DeclaratorContext::Member);
5251 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5252 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~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 5252, __extension__ __PRETTY_FUNCTION__))
;
5253
5254 // Create a declaration for this anonymous struct/union.
5255 NamedDecl *Anon = nullptr;
5256 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5257 Anon = FieldDecl::Create(
5258 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5259 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5260 /*BitWidth=*/nullptr, /*Mutable=*/false,
5261 /*InitStyle=*/ICIS_NoInit);
5262 Anon->setAccess(AS);
5263 ProcessDeclAttributes(S, Anon, Dc);
5264
5265 if (getLangOpts().CPlusPlus)
5266 FieldCollector->Add(cast<FieldDecl>(Anon));
5267 } else {
5268 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5269 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5270 if (SCSpec == DeclSpec::SCS_mutable) {
5271 // mutable can only appear on non-static class members, so it's always
5272 // an error here
5273 Diag(Record->getLocation(), diag::err_mutable_nonmember);
5274 Invalid = true;
5275 SC = SC_None;
5276 }
5277
5278 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~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 5278, __extension__ __PRETTY_FUNCTION__))
;
5279 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5280 Record->getLocation(), /*IdentifierInfo=*/nullptr,
5281 Context.getTypeDeclType(Record), TInfo, SC);
5282
5283 // Default-initialize the implicit variable. This initialization will be
5284 // trivial in almost all cases, except if a union member has an in-class
5285 // initializer:
5286 // union { int n = 0; };
5287 if (!Invalid)
5288 ActOnUninitializedDecl(Anon);
5289 }
5290 Anon->setImplicit();
5291
5292 // Mark this as an anonymous struct/union type.
5293 Record->setAnonymousStructOrUnion(true);
5294
5295 // Add the anonymous struct/union object to the current
5296 // context. We'll be referencing this object when we refer to one of
5297 // its members.
5298 Owner->addDecl(Anon);
5299
5300 // Inject the members of the anonymous struct/union into the owning
5301 // context and into the identifier resolver chain for name lookup
5302 // purposes.
5303 SmallVector<NamedDecl*, 2> Chain;
5304 Chain.push_back(Anon);
5305
5306 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5307 Invalid = true;
5308
5309 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5310 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5311 MangleNumberingContext *MCtx;
5312 Decl *ManglingContextDecl;
5313 std::tie(MCtx, ManglingContextDecl) =
5314 getCurrentMangleNumberContext(NewVD->getDeclContext());
5315 if (MCtx) {
5316 Context.setManglingNumber(
5317 NewVD, MCtx->getManglingNumber(
5318 NewVD, getMSManglingNumber(getLangOpts(), S)));
5319 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5320 }
5321 }
5322 }
5323
5324 if (Invalid)
5325 Anon->setInvalidDecl();
5326
5327 return Anon;
5328}
5329
5330/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5331/// Microsoft C anonymous structure.
5332/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5333/// Example:
5334///
5335/// struct A { int a; };
5336/// struct B { struct A; int b; };
5337///
5338/// void foo() {
5339/// B var;
5340/// var.a = 3;
5341/// }
5342///
5343Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5344 RecordDecl *Record) {
5345 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~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 5345, __extension__ __PRETTY_FUNCTION__))
;
5346
5347 // Mock up a declarator.
5348 Declarator Dc(DS, DeclaratorContext::TypeName);
5349 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5350 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~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 5350, __extension__ __PRETTY_FUNCTION__))
;
5351
5352 auto *ParentDecl = cast<RecordDecl>(CurContext);
5353 QualType RecTy = Context.getTypeDeclType(Record);
5354
5355 // Create a declaration for this anonymous struct.
5356 NamedDecl *Anon =
5357 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5358 /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5359 /*BitWidth=*/nullptr, /*Mutable=*/false,
5360 /*InitStyle=*/ICIS_NoInit);
5361 Anon->setImplicit();
5362
5363 // Add the anonymous struct object to the current context.
5364 CurContext->addDecl(Anon);
5365
5366 // Inject the members of the anonymous struct into the current
5367 // context and into the identifier resolver chain for name lookup
5368 // purposes.
5369 SmallVector<NamedDecl*, 2> Chain;
5370 Chain.push_back(Anon);
5371
5372 RecordDecl *RecordDef = Record->getDefinition();
5373 if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5374 diag::err_field_incomplete_or_sizeless) ||
5375 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5376 AS_none, Chain)) {
5377 Anon->setInvalidDecl();
5378 ParentDecl->setInvalidDecl();
5379 }
5380
5381 return Anon;
5382}
5383
5384/// GetNameForDeclarator - Determine the full declaration name for the
5385/// given Declarator.
5386DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5387 return GetNameFromUnqualifiedId(D.getName());
5388}
5389
5390/// Retrieves the declaration name from a parsed unqualified-id.
5391DeclarationNameInfo
5392Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5393 DeclarationNameInfo NameInfo;
5394 NameInfo.setLoc(Name.StartLocation);
5395
5396 switch (Name.getKind()) {
5397
5398 case UnqualifiedIdKind::IK_ImplicitSelfParam:
5399 case UnqualifiedIdKind::IK_Identifier:
5400 NameInfo.setName(Name.Identifier);
5401 return NameInfo;
5402
5403 case UnqualifiedIdKind::IK_DeductionGuideName: {
5404 // C++ [temp.deduct.guide]p3:
5405 // The simple-template-id shall name a class template specialization.
5406 // The template-name shall be the same identifier as the template-name
5407 // of the simple-template-id.
5408 // These together intend to imply that the template-name shall name a
5409 // class template.
5410 // FIXME: template<typename T> struct X {};
5411 // template<typename T> using Y = X<T>;
5412 // Y(int) -> Y<int>;
5413 // satisfies these rules but does not name a class template.
5414 TemplateName TN = Name.TemplateName.get().get();
5415 auto *Template = TN.getAsTemplateDecl();
5416 if (!Template || !isa<ClassTemplateDecl>(Template)) {
5417 Diag(Name.StartLocation,
5418 diag::err_deduction_guide_name_not_class_template)
5419 << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5420 if (Template)
5421 Diag(Template->getLocation(), diag::note_template_decl_here);
5422 return DeclarationNameInfo();
5423 }
5424
5425 NameInfo.setName(
5426 Context.DeclarationNames.getCXXDeductionGuideName(Template));
5427 return NameInfo;
5428 }
5429
5430 case UnqualifiedIdKind::IK_OperatorFunctionId:
5431 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5432 Name.OperatorFunctionId.Operator));
5433 NameInfo.setCXXOperatorNameRange(SourceRange(
5434 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5435 return NameInfo;
5436
5437 case UnqualifiedIdKind::IK_LiteralOperatorId:
5438 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5439 Name.Identifier));
5440 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5441 return NameInfo;
5442
5443 case UnqualifiedIdKind::IK_ConversionFunctionId: {
5444 TypeSourceInfo *TInfo;
5445 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5446 if (Ty.isNull())
5447 return DeclarationNameInfo();
5448 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5449 Context.getCanonicalType(Ty)));
5450 NameInfo.setNamedTypeInfo(TInfo);
5451 return NameInfo;
5452 }
5453
5454 case UnqualifiedIdKind::IK_ConstructorName: {
5455 TypeSourceInfo *TInfo;
5456 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5457 if (Ty.isNull())
5458 return DeclarationNameInfo();
5459 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5460 Context.getCanonicalType(Ty)));
5461 NameInfo.setNamedTypeInfo(TInfo);
5462 return NameInfo;
5463 }
5464
5465 case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5466 // In well-formed code, we can only have a constructor
5467 // template-id that refers to the current context, so go there
5468 // to find the actual type being constructed.
5469 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5470 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5471 return DeclarationNameInfo();
5472
5473 // Determine the type of the class being constructed.
5474 QualType CurClassType = Context.getTypeDeclType(CurClass);
5475
5476 // FIXME: Check two things: that the template-id names the same type as
5477 // CurClassType, and that the template-id does not occur when the name
5478 // was qualified.
5479
5480 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5481 Context.getCanonicalType(CurClassType)));
5482 // FIXME: should we retrieve TypeSourceInfo?
5483 NameInfo.setNamedTypeInfo(nullptr);
5484 return NameInfo;
5485 }
5486
5487 case UnqualifiedIdKind::IK_DestructorName: {
5488 TypeSourceInfo *TInfo;
5489 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5490 if (Ty.isNull())
5491 return DeclarationNameInfo();
5492 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5493 Context.getCanonicalType(Ty)));
5494 NameInfo.setNamedTypeInfo(TInfo);
5495 return NameInfo;
5496 }
5497
5498 case UnqualifiedIdKind::IK_TemplateId: {
5499 TemplateName TName = Name.TemplateId->Template.get();
5500 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5501 return Context.getNameForTemplate(TName, TNameLoc);
5502 }
5503
5504 } // switch (Name.getKind())
5505
5506 llvm_unreachable("Unknown name kind")::llvm::llvm_unreachable_internal("Unknown name kind", "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 5506)
;
5507}
5508
5509static QualType getCoreType(QualType Ty) {
5510 do {
5511 if (Ty->isPointerType() || Ty->isReferenceType())
5512 Ty = Ty->getPointeeType();
5513 else if (Ty->isArrayType())
5514 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5515 else
5516 return Ty.withoutLocalFastQualifiers();
5517 } while (true);
5518}
5519
5520/// hasSimilarParameters - Determine whether the C++ functions Declaration
5521/// and Definition have "nearly" matching parameters. This heuristic is
5522/// used to improve diagnostics in the case where an out-of-line function
5523/// definition doesn't match any declaration within the class or namespace.
5524/// Also sets Params to the list of indices to the parameters that differ
5525/// between the declaration and the definition. If hasSimilarParameters
5526/// returns true and Params is empty, then all of the parameters match.
5527static bool hasSimilarParameters(ASTContext &Context,
5528 FunctionDecl *Declaration,
5529 FunctionDecl *Definition,
5530 SmallVectorImpl<unsigned> &Params) {
5531 Params.clear();
5532 if (Declaration->param_size() != Definition->param_size())
5533 return false;
5534 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5535 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5536 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5537
5538 // The parameter types are identical
5539 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5540 continue;
5541
5542 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5543 QualType DefParamBaseTy = getCoreType(DefParamTy);
5544 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5545 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5546
5547 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5548 (DeclTyName && DeclTyName == DefTyName))
5549 Params.push_back(Idx);
5550 else // The two parameters aren't even close
5551 return false;
5552 }
5553
5554 return true;
5555}
5556
5557/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5558/// declarator needs to be rebuilt in the current instantiation.
5559/// Any bits of declarator which appear before the name are valid for
5560/// consideration here. That's specifically the type in the decl spec
5561/// and the base type in any member-pointer chunks.
5562static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5563 DeclarationName Name) {
5564 // The types we specifically need to rebuild are:
5565 // - typenames, typeofs, and decltypes
5566 // - types which will become injected class names
5567 // Of course, we also need to rebuild any type referencing such a
5568 // type. It's safest to just say "dependent", but we call out a
5569 // few cases here.
5570
5571 DeclSpec &DS = D.getMutableDeclSpec();
5572 switch (DS.getTypeSpecType()) {
5573 case DeclSpec::TST_typename:
5574 case DeclSpec::TST_typeofType:
5575 case DeclSpec::TST_underlyingType:
5576 case DeclSpec::TST_atomic: {
5577 // Grab the type from the parser.
5578 TypeSourceInfo *TSI = nullptr;
5579 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5580 if (T.isNull() || !T->isInstantiationDependentType()) break;
5581
5582 // Make sure there's a type source info. This isn't really much
5583 // of a waste; most dependent types should have type source info
5584 // attached already.
5585 if (!TSI)
5586 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5587
5588 // Rebuild the type in the current instantiation.
5589 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5590 if (!TSI) return true;
5591
5592 // Store the new type back in the decl spec.
5593 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5594 DS.UpdateTypeRep(LocType);
5595 break;
5596 }
5597
5598 case DeclSpec::TST_decltype:
5599 case DeclSpec::TST_typeofExpr: {
5600 Expr *E = DS.getRepAsExpr();
5601 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5602 if (Result.isInvalid()) return true;
5603 DS.UpdateExprRep(Result.get());
5604 break;
5605 }
5606
5607 default:
5608 // Nothing to do for these decl specs.
5609 break;
5610 }
5611
5612 // It doesn't matter what order we do this in.
5613 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5614 DeclaratorChunk &Chunk = D.getTypeObject(I);
5615
5616 // The only type information in the declarator which can come
5617 // before the declaration name is the base type of a member
5618 // pointer.
5619 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5620 continue;
5621
5622 // Rebuild the scope specifier in-place.
5623 CXXScopeSpec &SS = Chunk.Mem.Scope();
5624 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5625 return true;
5626 }
5627
5628 return false;
5629}
5630
5631void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
5632 // Avoid warning twice on the same identifier, and don't warn on redeclaration
5633 // of system decl.
5634 if (D->getPreviousDecl() || D->isImplicit())
5635 return;
5636 ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
5637 if (Status != ReservedIdentifierStatus::NotReserved &&
5638 !Context.getSourceManager().isInSystemHeader(D->getLocation()))
5639 Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
5640 << D << static_cast<int>(Status);
5641}
5642
5643Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5644 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
5645 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5646
5647 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5648 Dcl && Dcl->getDeclContext()->isFileContext())
5649 Dcl->setTopLevelDeclInObjCContainer();
5650
5651 return Dcl;
5652}