Bug Summary

File:clang/lib/Sema/SemaDecl.cpp
Warning:line 3753, 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-13~++20210604044723+50c0aaed47b5/build-llvm/tools/clang/lib/Sema -resource-dir /usr/lib/llvm-13/lib/clang/13.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-13~++20210604044723+50c0aaed47b5/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-13~++20210604044723+50c0aaed47b5/clang/lib/Sema -I /build/llvm-toolchain-snapshot-13~++20210604044723+50c0aaed47b5/clang/include -I /build/llvm-toolchain-snapshot-13~++20210604044723+50c0aaed47b5/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-13~++20210604044723+50c0aaed47b5/build-llvm/include -I /build/llvm-toolchain-snapshot-13~++20210604044723+50c0aaed47b5/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-13/lib/clang/13.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-13~++20210604044723+50c0aaed47b5/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-13~++20210604044723+50c0aaed47b5=. -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-06-04-165508-3769-1 -x c++ /build/llvm-toolchain-snapshot-13~++20210604044723+50c0aaed47b5/clang/lib/Sema/SemaDecl.cpp

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