Bug Summary

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