Bug Summary

File:build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/clang/lib/Sema/SemaDecl.cpp
Warning:line 17592, column 9
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

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