Bug Summary

File:clang/lib/Sema/SemaDecl.cpp
Warning:line 8523, column 35
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-10/lib/clang/10.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-10~+20191226100611+bb0138729b8/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~+20191226100611+bb0138729b8/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~+20191226100611+bb0138729b8/clang/include -I /build/llvm-toolchain-snapshot-10~+20191226100611+bb0138729b8/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~+20191226100611+bb0138729b8/build-llvm/include -I /build/llvm-toolchain-snapshot-10~+20191226100611+bb0138729b8/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-10/lib/clang/10.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-10~+20191226100611+bb0138729b8/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~+20191226100611+bb0138729b8=. -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-2019-12-27-023715-10247-1 -x c++ /build/llvm-toolchain-snapshot-10~+20191226100611+bb0138729b8/clang/lib/Sema/SemaDecl.cpp

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