Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name SemaDecl.cpp -analyzer-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-14~++20220116111435+edbb8a843c13/build-llvm -resource-dir /usr/lib/llvm-14/lib/clang/14.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-14~++20220116111435+edbb8a843c13/clang/lib/Sema -I /build/llvm-toolchain-snapshot-14~++20220116111435+edbb8a843c13/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-14~++20220116111435+edbb8a843c13/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-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116111435+edbb8a843c13/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116111435+edbb8a843c13/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116111435+edbb8a843c13/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116111435+edbb8a843c13/= -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-14~++20220116111435+edbb8a843c13/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116111435+edbb8a843c13/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116111435+edbb8a843c13/= -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-01-16-123900-34731-1 -x c++ /build/llvm-toolchain-snapshot-14~++20220116111435+edbb8a843c13/clang/lib/Sema/SemaDecl.cpp

/build/llvm-toolchain-snapshot-14~++20220116111435+edbb8a843c13/clang/lib/Sema/SemaDecl.cpp

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