Bug Summary

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