Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaDecl.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-11/lib/clang/11.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-11/lib/clang/11.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-03-09-184146-41876-1 -x c++ /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaDecl.cpp

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