Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name SemaDecl.cpp -analyzer-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/source/build-llvm -resource-dir /usr/lib/llvm-17/lib/clang/17 -I tools/clang/lib/Sema -I /build/source/clang/lib/Sema -I /build/source/clang/include -I tools/clang/include -I include -I /build/source/llvm/include -D _DEBUG -D _GLIBCXX_ASSERTIONS -D _GNU_SOURCE -D _LIBCPP_ENABLE_ASSERTIONS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -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-17/lib/clang/17/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/source/build-llvm=build-llvm -fmacro-prefix-map=/build/source/= -fcoverage-prefix-map=/build/source/build-llvm=build-llvm -fcoverage-prefix-map=/build/source/= -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/source/build-llvm -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -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-2023-05-10-133810-16478-1 -x c++ /build/source/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/HLSLRuntime.h"
31#include "clang/Basic/PartialDiagnostic.h"
32#include "clang/Basic/SourceManager.h"
33#include "clang/Basic/TargetInfo.h"
34#include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
35#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
36#include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
37#include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
38#include "clang/Sema/CXXFieldCollector.h"
39#include "clang/Sema/DeclSpec.h"
40#include "clang/Sema/DelayedDiagnostic.h"
41#include "clang/Sema/Initialization.h"
42#include "clang/Sema/Lookup.h"
43#include "clang/Sema/ParsedTemplate.h"
44#include "clang/Sema/Scope.h"
45#include "clang/Sema/ScopeInfo.h"
46#include "clang/Sema/SemaInternal.h"
47#include "clang/Sema/Template.h"
48#include "llvm/ADT/SmallString.h"
49#include "llvm/TargetParser/Triple.h"
50#include <algorithm>
51#include <cstring>
52#include <functional>
53#include <optional>
54#include <unordered_map>
55
56using namespace clang;
57using namespace sema;
58
59Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
60 if (OwnedType) {
61 Decl *Group[2] = { OwnedType, Ptr };
62 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
63 }
64
65 return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
66}
67
68namespace {
69
70class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
71 public:
72 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
73 bool AllowTemplates = false,
74 bool AllowNonTemplates = true)
75 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
76 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
77 WantExpressionKeywords = false;
78 WantCXXNamedCasts = false;
79 WantRemainingKeywords = false;
80 }
81
82 bool ValidateCandidate(const TypoCorrection &candidate) override {
83 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
84 if (!AllowInvalidDecl && ND->isInvalidDecl())
85 return false;
86
87 if (getAsTypeTemplateDecl(ND))
88 return AllowTemplates;
89
90 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
91 if (!IsType)
92 return false;
93
94 if (AllowNonTemplates)
95 return true;
96
97 // An injected-class-name of a class template (specialization) is valid
98 // as a template or as a non-template.
99 if (AllowTemplates) {
100 auto *RD = dyn_cast<CXXRecordDecl>(ND);
101 if (!RD || !RD->isInjectedClassName())
102 return false;
103 RD = cast<CXXRecordDecl>(RD->getDeclContext());
104 return RD->getDescribedClassTemplate() ||
105 isa<ClassTemplateSpecializationDecl>(RD);
106 }
107
108 return false;
109 }
110
111 return !WantClassName && candidate.isKeyword();
112 }
113
114 std::unique_ptr<CorrectionCandidateCallback> clone() override {
115 return std::make_unique<TypeNameValidatorCCC>(*this);
116 }
117
118 private:
119 bool AllowInvalidDecl;
120 bool WantClassName;
121 bool AllowTemplates;
122 bool AllowNonTemplates;
123};
124
125} // end anonymous namespace
126
127/// Determine whether the token kind starts a simple-type-specifier.
128bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
129 switch (Kind) {
130 // FIXME: Take into account the current language when deciding whether a
131 // token kind is a valid type specifier
132 case tok::kw_short:
133 case tok::kw_long:
134 case tok::kw___int64:
135 case tok::kw___int128:
136 case tok::kw_signed:
137 case tok::kw_unsigned:
138 case tok::kw_void:
139 case tok::kw_char:
140 case tok::kw_int:
141 case tok::kw_half:
142 case tok::kw_float:
143 case tok::kw_double:
144 case tok::kw___bf16:
145 case tok::kw__Float16:
146 case tok::kw___float128:
147 case tok::kw___ibm128:
148 case tok::kw_wchar_t:
149 case tok::kw_bool:
150#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
151#include "clang/Basic/TransformTypeTraits.def"
152 case tok::kw___auto_type:
153 return true;
154
155 case tok::annot_typename:
156 case tok::kw_char16_t:
157 case tok::kw_char32_t:
158 case tok::kw_typeof:
159 case tok::annot_decltype:
160 case tok::kw_decltype:
161 return getLangOpts().CPlusPlus;
162
163 case tok::kw_char8_t:
164 return getLangOpts().Char8;
165
166 default:
167 break;
168 }
169
170 return false;
171}
172
173namespace {
174enum class UnqualifiedTypeNameLookupResult {
175 NotFound,
176 FoundNonType,
177 FoundType
178};
179} // end anonymous namespace
180
181/// Tries to perform unqualified lookup of the type decls in bases for
182/// dependent class.
183/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
184/// type decl, \a FoundType if only type decls are found.
185static UnqualifiedTypeNameLookupResult
186lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
187 SourceLocation NameLoc,
188 const CXXRecordDecl *RD) {
189 if (!RD->hasDefinition())
190 return UnqualifiedTypeNameLookupResult::NotFound;
191 // Look for type decls in base classes.
192 UnqualifiedTypeNameLookupResult FoundTypeDecl =
193 UnqualifiedTypeNameLookupResult::NotFound;
194 for (const auto &Base : RD->bases()) {
195 const CXXRecordDecl *BaseRD = nullptr;
196 if (auto *BaseTT = Base.getType()->getAs<TagType>())
197 BaseRD = BaseTT->getAsCXXRecordDecl();
198 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
199 // Look for type decls in dependent base classes that have known primary
200 // templates.
201 if (!TST || !TST->isDependentType())
202 continue;
203 auto *TD = TST->getTemplateName().getAsTemplateDecl();
204 if (!TD)
205 continue;
206 if (auto *BasePrimaryTemplate =
207 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
208 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
209 BaseRD = BasePrimaryTemplate;
210 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
211 if (const ClassTemplatePartialSpecializationDecl *PS =
212 CTD->findPartialSpecialization(Base.getType()))
213 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
214 BaseRD = PS;
215 }
216 }
217 }
218 if (BaseRD) {
219 for (NamedDecl *ND : BaseRD->lookup(&II)) {
220 if (!isa<TypeDecl>(ND))
221 return UnqualifiedTypeNameLookupResult::FoundNonType;
222 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
223 }
224 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
225 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
226 case UnqualifiedTypeNameLookupResult::FoundNonType:
227 return UnqualifiedTypeNameLookupResult::FoundNonType;
228 case UnqualifiedTypeNameLookupResult::FoundType:
229 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
230 break;
231 case UnqualifiedTypeNameLookupResult::NotFound:
232 break;
233 }
234 }
235 }
236 }
237
238 return FoundTypeDecl;
239}
240
241static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
242 const IdentifierInfo &II,
243 SourceLocation NameLoc) {
244 // Lookup in the parent class template context, if any.
245 const CXXRecordDecl *RD = nullptr;
246 UnqualifiedTypeNameLookupResult FoundTypeDecl =
247 UnqualifiedTypeNameLookupResult::NotFound;
248 for (DeclContext *DC = S.CurContext;
249 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
250 DC = DC->getParent()) {
251 // Look for type decls in dependent base classes that have known primary
252 // templates.
253 RD = dyn_cast<CXXRecordDecl>(DC);
254 if (RD && RD->getDescribedClassTemplate())
255 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
256 }
257 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
258 return nullptr;
259
260 // We found some types in dependent base classes. Recover as if the user
261 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
262 // lookup during template instantiation.
263 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
264
265 ASTContext &Context = S.Context;
266 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
267 cast<Type>(Context.getRecordType(RD)));
268 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
269
270 CXXScopeSpec SS;
271 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
272
273 TypeLocBuilder Builder;
274 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
275 DepTL.setNameLoc(NameLoc);
276 DepTL.setElaboratedKeywordLoc(SourceLocation());
277 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
278 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
279}
280
281/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
282static ParsedType buildNamedType(Sema &S, const CXXScopeSpec *SS, QualType T,
283 SourceLocation NameLoc,
284 bool WantNontrivialTypeSourceInfo = true) {
285 switch (T->getTypeClass()) {
286 case Type::DeducedTemplateSpecialization:
287 case Type::Enum:
288 case Type::InjectedClassName:
289 case Type::Record:
290 case Type::Typedef:
291 case Type::UnresolvedUsing:
292 case Type::Using:
293 break;
294 // These can never be qualified so an ElaboratedType node
295 // would carry no additional meaning.
296 case Type::ObjCInterface:
297 case Type::ObjCTypeParam:
298 case Type::TemplateTypeParm:
299 return ParsedType::make(T);
300 default:
301 llvm_unreachable("Unexpected Type Class")::llvm::llvm_unreachable_internal("Unexpected Type Class", "clang/lib/Sema/SemaDecl.cpp"
, 301)
;
302 }
303
304 if (!SS || SS->isEmpty())
305 return ParsedType::make(
306 S.Context.getElaboratedType(ETK_None, nullptr, T, nullptr));
307
308 QualType ElTy = S.getElaboratedType(ETK_None, *SS, T);
309 if (!WantNontrivialTypeSourceInfo)
310 return ParsedType::make(ElTy);
311
312 TypeLocBuilder Builder;
313 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
314 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(ElTy);
315 ElabTL.setElaboratedKeywordLoc(SourceLocation());
316 ElabTL.setQualifierLoc(SS->getWithLocInContext(S.Context));
317 return S.CreateParsedType(ElTy, Builder.getTypeSourceInfo(S.Context, ElTy));
318}
319
320/// If the identifier refers to a type name within this scope,
321/// return the declaration of that type.
322///
323/// This routine performs ordinary name lookup of the identifier II
324/// within the given scope, with optional C++ scope specifier SS, to
325/// determine whether the name refers to a type. If so, returns an
326/// opaque pointer (actually a QualType) corresponding to that
327/// type. Otherwise, returns NULL.
328ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
329 Scope *S, CXXScopeSpec *SS, bool isClassName,
330 bool HasTrailingDot, ParsedType ObjectTypePtr,
331 bool IsCtorOrDtorName,
332 bool WantNontrivialTypeSourceInfo,
333 bool IsClassTemplateDeductionContext,
334 ImplicitTypenameContext AllowImplicitTypename,
335 IdentifierInfo **CorrectedII) {
336 // FIXME: Consider allowing this outside C++1z mode as an extension.
337 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
338 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
339 !isClassName && !HasTrailingDot;
340
341 // Determine where we will perform name lookup.
342 DeclContext *LookupCtx = nullptr;
343 if (ObjectTypePtr) {
344 QualType ObjectType = ObjectTypePtr.get();
345 if (ObjectType->isRecordType())
346 LookupCtx = computeDeclContext(ObjectType);
347 } else if (SS && SS->isNotEmpty()) {
348 LookupCtx = computeDeclContext(*SS, false);
349
350 if (!LookupCtx) {
351 if (isDependentScopeSpecifier(*SS)) {
352 // C++ [temp.res]p3:
353 // A qualified-id that refers to a type and in which the
354 // nested-name-specifier depends on a template-parameter (14.6.2)
355 // shall be prefixed by the keyword typename to indicate that the
356 // qualified-id denotes a type, forming an
357 // elaborated-type-specifier (7.1.5.3).
358 //
359 // We therefore do not perform any name lookup if the result would
360 // refer to a member of an unknown specialization.
361 // In C++2a, in several contexts a 'typename' is not required. Also
362 // allow this as an extension.
363 if (AllowImplicitTypename == ImplicitTypenameContext::No &&
364 !isClassName && !IsCtorOrDtorName)
365 return nullptr;
366 bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
367 if (IsImplicitTypename) {
368 SourceLocation QualifiedLoc = SS->getRange().getBegin();
369 if (getLangOpts().CPlusPlus20)
370 Diag(QualifiedLoc, diag::warn_cxx17_compat_implicit_typename);
371 else
372 Diag(QualifiedLoc, diag::ext_implicit_typename)
373 << SS->getScopeRep() << II.getName()
374 << FixItHint::CreateInsertion(QualifiedLoc, "typename ");
375 }
376
377 // We know from the grammar that this name refers to a type,
378 // so build a dependent node to describe the type.
379 if (WantNontrivialTypeSourceInfo)
380 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc,
381 (ImplicitTypenameContext)IsImplicitTypename)
382 .get();
383
384 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
385 QualType T =
386 CheckTypenameType(IsImplicitTypename ? ETK_Typename : ETK_None,
387 SourceLocation(), QualifierLoc, II, NameLoc);
388 return ParsedType::make(T);
389 }
390
391 return nullptr;
392 }
393
394 if (!LookupCtx->isDependentContext() &&
395 RequireCompleteDeclContext(*SS, LookupCtx))
396 return nullptr;
397 }
398
399 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
400 // lookup for class-names.
401 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
402 LookupOrdinaryName;
403 LookupResult Result(*this, &II, NameLoc, Kind);
404 if (LookupCtx) {
405 // Perform "qualified" name lookup into the declaration context we
406 // computed, which is either the type of the base of a member access
407 // expression or the declaration context associated with a prior
408 // nested-name-specifier.
409 LookupQualifiedName(Result, LookupCtx);
410
411 if (ObjectTypePtr && Result.empty()) {
412 // C++ [basic.lookup.classref]p3:
413 // If the unqualified-id is ~type-name, the type-name is looked up
414 // in the context of the entire postfix-expression. If the type T of
415 // the object expression is of a class type C, the type-name is also
416 // looked up in the scope of class C. At least one of the lookups shall
417 // find a name that refers to (possibly cv-qualified) T.
418 LookupName(Result, S);
419 }
420 } else {
421 // Perform unqualified name lookup.
422 LookupName(Result, S);
423
424 // For unqualified lookup in a class template in MSVC mode, look into
425 // dependent base classes where the primary class template is known.
426 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
427 if (ParsedType TypeInBase =
428 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
429 return TypeInBase;
430 }
431 }
432
433 NamedDecl *IIDecl = nullptr;
434 UsingShadowDecl *FoundUsingShadow = nullptr;
435 switch (Result.getResultKind()) {
436 case LookupResult::NotFound:
437 case LookupResult::NotFoundInCurrentInstantiation:
438 if (CorrectedII) {
439 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
440 AllowDeducedTemplate);
441 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
442 S, SS, CCC, CTK_ErrorRecovery);
443 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
444 TemplateTy Template;
445 bool MemberOfUnknownSpecialization;
446 UnqualifiedId TemplateName;
447 TemplateName.setIdentifier(NewII, NameLoc);
448 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
449 CXXScopeSpec NewSS, *NewSSPtr = SS;
450 if (SS && NNS) {
451 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
452 NewSSPtr = &NewSS;
453 }
454 if (Correction && (NNS || NewII != &II) &&
455 // Ignore a correction to a template type as the to-be-corrected
456 // identifier is not a template (typo correction for template names
457 // is handled elsewhere).
458 !(getLangOpts().CPlusPlus && NewSSPtr &&
459 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
460 Template, MemberOfUnknownSpecialization))) {
461 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
462 isClassName, HasTrailingDot, ObjectTypePtr,
463 IsCtorOrDtorName,
464 WantNontrivialTypeSourceInfo,
465 IsClassTemplateDeductionContext);
466 if (Ty) {
467 diagnoseTypo(Correction,
468 PDiag(diag::err_unknown_type_or_class_name_suggest)
469 << Result.getLookupName() << isClassName);
470 if (SS && NNS)
471 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
472 *CorrectedII = NewII;
473 return Ty;
474 }
475 }
476 }
477 // If typo correction failed or was not performed, fall through
478 [[fallthrough]];
479 case LookupResult::FoundOverloaded:
480 case LookupResult::FoundUnresolvedValue:
481 Result.suppressDiagnostics();
482 return nullptr;
483
484 case LookupResult::Ambiguous:
485 // Recover from type-hiding ambiguities by hiding the type. We'll
486 // do the lookup again when looking for an object, and we can
487 // diagnose the error then. If we don't do this, then the error
488 // about hiding the type will be immediately followed by an error
489 // that only makes sense if the identifier was treated like a type.
490 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
491 Result.suppressDiagnostics();
492 return nullptr;
493 }
494
495 // Look to see if we have a type anywhere in the list of results.
496 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
497 Res != ResEnd; ++Res) {
498 NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
499 if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
500 RealRes) ||
501 (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
502 if (!IIDecl ||
503 // Make the selection of the recovery decl deterministic.
504 RealRes->getLocation() < IIDecl->getLocation()) {
505 IIDecl = RealRes;
506 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
507 }
508 }
509 }
510
511 if (!IIDecl) {
512 // None of the entities we found is a type, so there is no way
513 // to even assume that the result is a type. In this case, don't
514 // complain about the ambiguity. The parser will either try to
515 // perform this lookup again (e.g., as an object name), which
516 // will produce the ambiguity, or will complain that it expected
517 // a type name.
518 Result.suppressDiagnostics();
519 return nullptr;
520 }
521
522 // We found a type within the ambiguous lookup; diagnose the
523 // ambiguity and then return that type. This might be the right
524 // answer, or it might not be, but it suppresses any attempt to
525 // perform the name lookup again.
526 break;
527
528 case LookupResult::Found:
529 IIDecl = Result.getFoundDecl();
530 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
531 break;
532 }
533
534 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", 534, __extension__ __PRETTY_FUNCTION__
))
;
535
536 QualType T;
537 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
538 // C++ [class.qual]p2: A lookup that would find the injected-class-name
539 // instead names the constructors of the class, except when naming a class.
540 // This is ill-formed when we're not actually forming a ctor or dtor name.
541 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
542 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
543 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
544 FoundRD->isInjectedClassName() &&
545 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
546 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
547 << &II << /*Type*/1;
548
549 DiagnoseUseOfDecl(IIDecl, NameLoc);
550
551 T = Context.getTypeDeclType(TD);
552 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
553 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
554 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
555 if (!HasTrailingDot)
556 T = Context.getObjCInterfaceType(IDecl);
557 FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl.
558 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
559 (void)DiagnoseUseOfDecl(UD, NameLoc);
560 // Recover with 'int'
561 return ParsedType::make(Context.IntTy);
562 } else if (AllowDeducedTemplate) {
563 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
564 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", 564, __extension__ __PRETTY_FUNCTION__
))
;
565 TemplateName Template =
566 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
567 T = Context.getDeducedTemplateSpecializationType(Template, QualType(),
568 false);
569 // Don't wrap in a further UsingType.
570 FoundUsingShadow = nullptr;
571 }
572 }
573
574 if (T.isNull()) {
575 // If it's not plausibly a type, suppress diagnostics.
576 Result.suppressDiagnostics();
577 return nullptr;
578 }
579
580 if (FoundUsingShadow)
581 T = Context.getUsingType(FoundUsingShadow, T);
582
583 return buildNamedType(*this, SS, T, NameLoc, WantNontrivialTypeSourceInfo);
584}
585
586// Builds a fake NNS for the given decl context.
587static NestedNameSpecifier *
588synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
589 for (;; DC = DC->getLookupParent()) {
590 DC = DC->getPrimaryContext();
591 auto *ND = dyn_cast<NamespaceDecl>(DC);
592 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
593 return NestedNameSpecifier::Create(Context, nullptr, ND);
594 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
595 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
596 RD->getTypeForDecl());
597 else if (isa<TranslationUnitDecl>(DC))
598 return NestedNameSpecifier::GlobalSpecifier(Context);
599 }
600 llvm_unreachable("something isn't in TU scope?")::llvm::llvm_unreachable_internal("something isn't in TU scope?"
, "clang/lib/Sema/SemaDecl.cpp", 600)
;
601}
602
603/// Find the parent class with dependent bases of the innermost enclosing method
604/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
605/// up allowing unqualified dependent type names at class-level, which MSVC
606/// correctly rejects.
607static const CXXRecordDecl *
608findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
609 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
610 DC = DC->getPrimaryContext();
611 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
612 if (MD->getParent()->hasAnyDependentBases())
613 return MD->getParent();
614 }
615 return nullptr;
616}
617
618ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
619 SourceLocation NameLoc,
620 bool IsTemplateTypeArg) {
621 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", 621, __extension__ __PRETTY_FUNCTION__
))
;
622
623 NestedNameSpecifier *NNS = nullptr;
624 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
625 // If we weren't able to parse a default template argument, delay lookup
626 // until instantiation time by making a non-dependent DependentTypeName. We
627 // pretend we saw a NestedNameSpecifier referring to the current scope, and
628 // lookup is retried.
629 // FIXME: This hurts our diagnostic quality, since we get errors like "no
630 // type named 'Foo' in 'current_namespace'" when the user didn't write any
631 // name specifiers.
632 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
633 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
634 } else if (const CXXRecordDecl *RD =
635 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
636 // Build a DependentNameType that will perform lookup into RD at
637 // instantiation time.
638 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
639 RD->getTypeForDecl());
640
641 // Diagnose that this identifier was undeclared, and retry the lookup during
642 // template instantiation.
643 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
644 << RD;
645 } else {
646 // This is not a situation that we should recover from.
647 return ParsedType();
648 }
649
650 QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
651
652 // Build type location information. We synthesized the qualifier, so we have
653 // to build a fake NestedNameSpecifierLoc.
654 NestedNameSpecifierLocBuilder NNSLocBuilder;
655 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
656 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
657
658 TypeLocBuilder Builder;
659 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
660 DepTL.setNameLoc(NameLoc);
661 DepTL.setElaboratedKeywordLoc(SourceLocation());
662 DepTL.setQualifierLoc(QualifierLoc);
663 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
664}
665
666/// isTagName() - This method is called *for error recovery purposes only*
667/// to determine if the specified name is a valid tag name ("struct foo"). If
668/// so, this returns the TST for the tag corresponding to it (TST_enum,
669/// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
670/// cases in C where the user forgot to specify the tag.
671DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
672 // Do a tag name lookup in this scope.
673 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
674 LookupName(R, S, false);
675 R.suppressDiagnostics();
676 if (R.getResultKind() == LookupResult::Found)
677 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
678 switch (TD->getTagKind()) {
679 case TTK_Struct: return DeclSpec::TST_struct;
680 case TTK_Interface: return DeclSpec::TST_interface;
681 case TTK_Union: return DeclSpec::TST_union;
682 case TTK_Class: return DeclSpec::TST_class;
683 case TTK_Enum: return DeclSpec::TST_enum;
684 }
685 }
686
687 return DeclSpec::TST_unspecified;
688}
689
690/// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
691/// if a CXXScopeSpec's type is equal to the type of one of the base classes
692/// then downgrade the missing typename error to a warning.
693/// This is needed for MSVC compatibility; Example:
694/// @code
695/// template<class T> class A {
696/// public:
697/// typedef int TYPE;
698/// };
699/// template<class T> class B : public A<T> {
700/// public:
701/// A<T>::TYPE a; // no typename required because A<T> is a base class.
702/// };
703/// @endcode
704bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
705 if (CurContext->isRecord()) {
706 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
707 return true;
708
709 const Type *Ty = SS->getScopeRep()->getAsType();
710
711 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
712 for (const auto &Base : RD->bases())
713 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
714 return true;
715 return S->isFunctionPrototypeScope();
716 }
717 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
718}
719
720void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
721 SourceLocation IILoc,
722 Scope *S,
723 CXXScopeSpec *SS,
724 ParsedType &SuggestedType,
725 bool IsTemplateName) {
726 // Don't report typename errors for editor placeholders.
727 if (II->isEditorPlaceholder())
728 return;
729 // We don't have anything to suggest (yet).
730 SuggestedType = nullptr;
731
732 // There may have been a typo in the name of the type. Look up typo
733 // results, in case we have something that we can suggest.
734 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
735 /*AllowTemplates=*/IsTemplateName,
736 /*AllowNonTemplates=*/!IsTemplateName);
737 if (TypoCorrection Corrected =
738 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
739 CCC, CTK_ErrorRecovery)) {
740 // FIXME: Support error recovery for the template-name case.
741 bool CanRecover = !IsTemplateName;
742 if (Corrected.isKeyword()) {
743 // We corrected to a keyword.
744 diagnoseTypo(Corrected,
745 PDiag(IsTemplateName ? diag::err_no_template_suggest
746 : diag::err_unknown_typename_suggest)
747 << II);
748 II = Corrected.getCorrectionAsIdentifierInfo();
749 } else {
750 // We found a similarly-named type or interface; suggest that.
751 if (!SS || !SS->isSet()) {
752 diagnoseTypo(Corrected,
753 PDiag(IsTemplateName ? diag::err_no_template_suggest
754 : diag::err_unknown_typename_suggest)
755 << II, CanRecover);
756 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
757 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
758 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
759 II->getName().equals(CorrectedStr);
760 diagnoseTypo(Corrected,
761 PDiag(IsTemplateName
762 ? diag::err_no_member_template_suggest
763 : diag::err_unknown_nested_typename_suggest)
764 << II << DC << DroppedSpecifier << SS->getRange(),
765 CanRecover);
766 } else {
767 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", 767)
;
768 }
769
770 if (!CanRecover)
771 return;
772
773 CXXScopeSpec tmpSS;
774 if (Corrected.getCorrectionSpecifier())
775 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
776 SourceRange(IILoc));
777 // FIXME: Support class template argument deduction here.
778 SuggestedType =
779 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
780 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
781 /*IsCtorOrDtorName=*/false,
782 /*WantNontrivialTypeSourceInfo=*/true);
783 }
784 return;
785 }
786
787 if (getLangOpts().CPlusPlus && !IsTemplateName) {
788 // See if II is a class template that the user forgot to pass arguments to.
789 UnqualifiedId Name;
790 Name.setIdentifier(II, IILoc);
791 CXXScopeSpec EmptySS;
792 TemplateTy TemplateResult;
793 bool MemberOfUnknownSpecialization;
794 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
795 Name, nullptr, true, TemplateResult,
796 MemberOfUnknownSpecialization) == TNK_Type_template) {
797 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
798 return;
799 }
800 }
801
802 // FIXME: Should we move the logic that tries to recover from a missing tag
803 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
804
805 if (!SS || (!SS->isSet() && !SS->isInvalid()))
806 Diag(IILoc, IsTemplateName ? diag::err_no_template
807 : diag::err_unknown_typename)
808 << II;
809 else if (DeclContext *DC = computeDeclContext(*SS, false))
810 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
811 : diag::err_typename_nested_not_found)
812 << II << DC << SS->getRange();
813 else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
814 SuggestedType =
815 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
816 } else if (isDependentScopeSpecifier(*SS)) {
817 unsigned DiagID = diag::err_typename_missing;
818 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
819 DiagID = diag::ext_typename_missing;
820
821 Diag(SS->getRange().getBegin(), DiagID)
822 << SS->getScopeRep() << II->getName()
823 << SourceRange(SS->getRange().getBegin(), IILoc)
824 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
825 SuggestedType = ActOnTypenameType(S, SourceLocation(),
826 *SS, *II, IILoc).get();
827 } else {
828 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", 829, __extension__ __PRETTY_FUNCTION__
))
829 "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", 829, __extension__ __PRETTY_FUNCTION__
))
;
830 }
831}
832
833/// Determine whether the given result set contains either a type name
834/// or
835static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
836 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
837 NextToken.is(tok::less);
838
839 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
840 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
841 return true;
842
843 if (CheckTemplate && isa<TemplateDecl>(*I))
844 return true;
845 }
846
847 return false;
848}
849
850static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
851 Scope *S, CXXScopeSpec &SS,
852 IdentifierInfo *&Name,
853 SourceLocation NameLoc) {
854 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
855 SemaRef.LookupParsedName(R, S, &SS);
856 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
857 StringRef FixItTagName;
858 switch (Tag->getTagKind()) {
859 case TTK_Class:
860 FixItTagName = "class ";
861 break;
862
863 case TTK_Enum:
864 FixItTagName = "enum ";
865 break;
866
867 case TTK_Struct:
868 FixItTagName = "struct ";
869 break;
870
871 case TTK_Interface:
872 FixItTagName = "__interface ";
873 break;
874
875 case TTK_Union:
876 FixItTagName = "union ";
877 break;
878 }
879
880 StringRef TagName = FixItTagName.drop_back();
881 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
882 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
883 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
884
885 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
886 I != IEnd; ++I)
887 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
888 << Name << TagName;
889
890 // Replace lookup results with just the tag decl.
891 Result.clear(Sema::LookupTagName);
892 SemaRef.LookupParsedName(Result, S, &SS);
893 return true;
894 }
895
896 return false;
897}
898
899Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
900 IdentifierInfo *&Name,
901 SourceLocation NameLoc,
902 const Token &NextToken,
903 CorrectionCandidateCallback *CCC) {
904 DeclarationNameInfo NameInfo(Name, NameLoc);
905 ObjCMethodDecl *CurMethod = getCurMethodDecl();
906
907 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", 908, __extension__ __PRETTY_FUNCTION__
))
908 "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", 908, __extension__ __PRETTY_FUNCTION__
))
;
909 if (getLangOpts().CPlusPlus && SS.isSet() &&
910 isCurrentClassName(*Name, S, &SS)) {
911 // Per [class.qual]p2, this names the constructors of SS, not the
912 // injected-class-name. We don't have a classification for that.
913 // There's not much point caching this result, since the parser
914 // will reject it later.
915 return NameClassification::Unknown();
916 }
917
918 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
919 LookupParsedName(Result, S, &SS, !CurMethod);
920
921 if (SS.isInvalid())
922 return NameClassification::Error();
923
924 // For unqualified lookup in a class template in MSVC mode, look into
925 // dependent base classes where the primary class template is known.
926 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
927 if (ParsedType TypeInBase =
928 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
929 return TypeInBase;
930 }
931
932 // Perform lookup for Objective-C instance variables (including automatically
933 // synthesized instance variables), if we're in an Objective-C method.
934 // FIXME: This lookup really, really needs to be folded in to the normal
935 // unqualified lookup mechanism.
936 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
937 DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
938 if (Ivar.isInvalid())
939 return NameClassification::Error();
940 if (Ivar.isUsable())
941 return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
942
943 // We defer builtin creation until after ivar lookup inside ObjC methods.
944 if (Result.empty())
945 LookupBuiltin(Result);
946 }
947
948 bool SecondTry = false;
949 bool IsFilteredTemplateName = false;
950
951Corrected:
952 switch (Result.getResultKind()) {
953 case LookupResult::NotFound:
954 // If an unqualified-id is followed by a '(', then we have a function
955 // call.
956 if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
957 // In C++, this is an ADL-only call.
958 // FIXME: Reference?
959 if (getLangOpts().CPlusPlus)
960 return NameClassification::UndeclaredNonType();
961
962 // C90 6.3.2.2:
963 // If the expression that precedes the parenthesized argument list in a
964 // function call consists solely of an identifier, and if no
965 // declaration is visible for this identifier, the identifier is
966 // implicitly declared exactly as if, in the innermost block containing
967 // the function call, the declaration
968 //
969 // extern int identifier ();
970 //
971 // appeared.
972 //
973 // We also allow this in C99 as an extension. However, this is not
974 // allowed in all language modes as functions without prototypes may not
975 // be supported.
976 if (getLangOpts().implicitFunctionsAllowed()) {
977 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
978 return NameClassification::NonType(D);
979 }
980 }
981
982 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
983 // In C++20 onwards, this could be an ADL-only call to a function
984 // template, and we're required to assume that this is a template name.
985 //
986 // FIXME: Find a way to still do typo correction in this case.
987 TemplateName Template =
988 Context.getAssumedTemplateName(NameInfo.getName());
989 return NameClassification::UndeclaredTemplate(Template);
990 }
991
992 // In C, we first see whether there is a tag type by the same name, in
993 // which case it's likely that the user just forgot to write "enum",
994 // "struct", or "union".
995 if (!getLangOpts().CPlusPlus && !SecondTry &&
996 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
997 break;
998 }
999
1000 // Perform typo correction to determine if there is another name that is
1001 // close to this name.
1002 if (!SecondTry && CCC) {
1003 SecondTry = true;
1004 if (TypoCorrection Corrected =
1005 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
1006 &SS, *CCC, CTK_ErrorRecovery)) {
1007 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
1008 unsigned QualifiedDiag = diag::err_no_member_suggest;
1009
1010 NamedDecl *FirstDecl = Corrected.getFoundDecl();
1011 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
1012 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1013 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
1014 UnqualifiedDiag = diag::err_no_template_suggest;
1015 QualifiedDiag = diag::err_no_member_template_suggest;
1016 } else if (UnderlyingFirstDecl &&
1017 (isa<TypeDecl>(UnderlyingFirstDecl) ||
1018 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
1019 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
1020 UnqualifiedDiag = diag::err_unknown_typename_suggest;
1021 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
1022 }
1023
1024 if (SS.isEmpty()) {
1025 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
1026 } else {// FIXME: is this even reachable? Test it.
1027 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1028 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
1029 Name->getName().equals(CorrectedStr);
1030 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
1031 << Name << computeDeclContext(SS, false)
1032 << DroppedSpecifier << SS.getRange());
1033 }
1034
1035 // Update the name, so that the caller has the new name.
1036 Name = Corrected.getCorrectionAsIdentifierInfo();
1037
1038 // Typo correction corrected to a keyword.
1039 if (Corrected.isKeyword())
1040 return Name;
1041
1042 // Also update the LookupResult...
1043 // FIXME: This should probably go away at some point
1044 Result.clear();
1045 Result.setLookupName(Corrected.getCorrection());
1046 if (FirstDecl)
1047 Result.addDecl(FirstDecl);
1048
1049 // If we found an Objective-C instance variable, let
1050 // LookupInObjCMethod build the appropriate expression to
1051 // reference the ivar.
1052 // FIXME: This is a gross hack.
1053 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1054 DeclResult R =
1055 LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1056 if (R.isInvalid())
1057 return NameClassification::Error();
1058 if (R.isUsable())
1059 return NameClassification::NonType(Ivar);
1060 }
1061
1062 goto Corrected;
1063 }
1064 }
1065
1066 // We failed to correct; just fall through and let the parser deal with it.
1067 Result.suppressDiagnostics();
1068 return NameClassification::Unknown();
1069
1070 case LookupResult::NotFoundInCurrentInstantiation: {
1071 // We performed name lookup into the current instantiation, and there were
1072 // dependent bases, so we treat this result the same way as any other
1073 // dependent nested-name-specifier.
1074
1075 // C++ [temp.res]p2:
1076 // A name used in a template declaration or definition and that is
1077 // dependent on a template-parameter is assumed not to name a type
1078 // unless the applicable name lookup finds a type name or the name is
1079 // qualified by the keyword typename.
1080 //
1081 // FIXME: If the next token is '<', we might want to ask the parser to
1082 // perform some heroics to see if we actually have a
1083 // template-argument-list, which would indicate a missing 'template'
1084 // keyword here.
1085 return NameClassification::DependentNonType();
1086 }
1087
1088 case LookupResult::Found:
1089 case LookupResult::FoundOverloaded:
1090 case LookupResult::FoundUnresolvedValue:
1091 break;
1092
1093 case LookupResult::Ambiguous:
1094 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1095 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1096 /*AllowDependent=*/false)) {
1097 // C++ [temp.local]p3:
1098 // A lookup that finds an injected-class-name (10.2) can result in an
1099 // ambiguity in certain cases (for example, if it is found in more than
1100 // one base class). If all of the injected-class-names that are found
1101 // refer to specializations of the same class template, and if the name
1102 // is followed by a template-argument-list, the reference refers to the
1103 // class template itself and not a specialization thereof, and is not
1104 // ambiguous.
1105 //
1106 // This filtering can make an ambiguous result into an unambiguous one,
1107 // so try again after filtering out template names.
1108 FilterAcceptableTemplateNames(Result);
1109 if (!Result.isAmbiguous()) {
1110 IsFilteredTemplateName = true;
1111 break;
1112 }
1113 }
1114
1115 // Diagnose the ambiguity and return an error.
1116 return NameClassification::Error();
1117 }
1118
1119 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1120 (IsFilteredTemplateName ||
1121 hasAnyAcceptableTemplateNames(
1122 Result, /*AllowFunctionTemplates=*/true,
1123 /*AllowDependent=*/false,
1124 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1125 getLangOpts().CPlusPlus20))) {
1126 // C++ [temp.names]p3:
1127 // After name lookup (3.4) finds that a name is a template-name or that
1128 // an operator-function-id or a literal- operator-id refers to a set of
1129 // overloaded functions any member of which is a function template if
1130 // this is followed by a <, the < is always taken as the delimiter of a
1131 // template-argument-list and never as the less-than operator.
1132 // C++2a [temp.names]p2:
1133 // A name is also considered to refer to a template if it is an
1134 // unqualified-id followed by a < and name lookup finds either one
1135 // or more functions or finds nothing.
1136 if (!IsFilteredTemplateName)
1137 FilterAcceptableTemplateNames(Result);
1138
1139 bool IsFunctionTemplate;
1140 bool IsVarTemplate;
1141 TemplateName Template;
1142 if (Result.end() - Result.begin() > 1) {
1143 IsFunctionTemplate = true;
1144 Template = Context.getOverloadedTemplateName(Result.begin(),
1145 Result.end());
1146 } else if (!Result.empty()) {
1147 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1148 *Result.begin(), /*AllowFunctionTemplates=*/true,
1149 /*AllowDependent=*/false));
1150 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1151 IsVarTemplate = isa<VarTemplateDecl>(TD);
1152
1153 UsingShadowDecl *FoundUsingShadow =
1154 dyn_cast<UsingShadowDecl>(*Result.begin());
1155 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", 1156, __extension__ __PRETTY_FUNCTION__
))
1156 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", 1156, __extension__ __PRETTY_FUNCTION__
))
;
1157 Template =
1158 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
1159 if (SS.isNotEmpty())
1160 Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
1161 /*TemplateKeyword=*/false,
1162 Template);
1163 } else {
1164 // All results were non-template functions. This is a function template
1165 // name.
1166 IsFunctionTemplate = true;
1167 Template = Context.getAssumedTemplateName(NameInfo.getName());
1168 }
1169
1170 if (IsFunctionTemplate) {
1171 // Function templates always go through overload resolution, at which
1172 // point we'll perform the various checks (e.g., accessibility) we need
1173 // to based on which function we selected.
1174 Result.suppressDiagnostics();
1175
1176 return NameClassification::FunctionTemplate(Template);
1177 }
1178
1179 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1180 : NameClassification::TypeTemplate(Template);
1181 }
1182
1183 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1184 QualType T = Context.getTypeDeclType(Type);
1185 if (const auto *USD = dyn_cast<UsingShadowDecl>(Found))
1186 T = Context.getUsingType(USD, T);
1187 return buildNamedType(*this, &SS, T, NameLoc);
1188 };
1189
1190 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1191 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1192 DiagnoseUseOfDecl(Type, NameLoc);
1193 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1194 return BuildTypeFor(Type, *Result.begin());
1195 }
1196
1197 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1198 if (!Class) {
1199 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1200 if (ObjCCompatibleAliasDecl *Alias =
1201 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1202 Class = Alias->getClassInterface();
1203 }
1204
1205 if (Class) {
1206 DiagnoseUseOfDecl(Class, NameLoc);
1207
1208 if (NextToken.is(tok::period)) {
1209 // Interface. <something> is parsed as a property reference expression.
1210 // Just return "unknown" as a fall-through for now.
1211 Result.suppressDiagnostics();
1212 return NameClassification::Unknown();
1213 }
1214
1215 QualType T = Context.getObjCInterfaceType(Class);
1216 return ParsedType::make(T);
1217 }
1218
1219 if (isa<ConceptDecl>(FirstDecl))
1220 return NameClassification::Concept(
1221 TemplateName(cast<TemplateDecl>(FirstDecl)));
1222
1223 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1224 (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1225 return NameClassification::Error();
1226 }
1227
1228 // We can have a type template here if we're classifying a template argument.
1229 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1230 !isa<VarTemplateDecl>(FirstDecl))
1231 return NameClassification::TypeTemplate(
1232 TemplateName(cast<TemplateDecl>(FirstDecl)));
1233
1234 // Check for a tag type hidden by a non-type decl in a few cases where it
1235 // seems likely a type is wanted instead of the non-type that was found.
1236 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1237 if ((NextToken.is(tok::identifier) ||
1238 (NextIsOp &&
1239 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1240 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1241 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1242 DiagnoseUseOfDecl(Type, NameLoc);
1243 return BuildTypeFor(Type, *Result.begin());
1244 }
1245
1246 // If we already know which single declaration is referenced, just annotate
1247 // that declaration directly. Defer resolving even non-overloaded class
1248 // member accesses, as we need to defer certain access checks until we know
1249 // the context.
1250 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1251 if (Result.isSingleResult() && !ADL &&
1252 (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(FirstDecl)))
1253 return NameClassification::NonType(Result.getRepresentativeDecl());
1254
1255 // Otherwise, this is an overload set that we will need to resolve later.
1256 Result.suppressDiagnostics();
1257 return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1258 Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1259 Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
1260 Result.begin(), Result.end()));
1261}
1262
1263ExprResult
1264Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1265 SourceLocation NameLoc) {
1266 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", 1266, __extension__ __PRETTY_FUNCTION__
))
;
1267 CXXScopeSpec SS;
1268 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1269 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1270}
1271
1272ExprResult
1273Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1274 IdentifierInfo *Name,
1275 SourceLocation NameLoc,
1276 bool IsAddressOfOperand) {
1277 DeclarationNameInfo NameInfo(Name, NameLoc);
1278 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1279 NameInfo, IsAddressOfOperand,
1280 /*TemplateArgs=*/nullptr);
1281}
1282
1283ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1284 NamedDecl *Found,
1285 SourceLocation NameLoc,
1286 const Token &NextToken) {
1287 if (getCurMethodDecl() && SS.isEmpty())
1288 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1289 return BuildIvarRefExpr(S, NameLoc, Ivar);
1290
1291 // Reconstruct the lookup result.
1292 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1293 Result.addDecl(Found);
1294 Result.resolveKind();
1295
1296 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1297 return BuildDeclarationNameExpr(SS, Result, ADL, /*AcceptInvalidDecl=*/true);
1298}
1299
1300ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1301 // For an implicit class member access, transform the result into a member
1302 // access expression if necessary.
1303 auto *ULE = cast<UnresolvedLookupExpr>(E);
1304 if ((*ULE->decls_begin())->isCXXClassMember()) {
1305 CXXScopeSpec SS;
1306 SS.Adopt(ULE->getQualifierLoc());
1307
1308 // Reconstruct the lookup result.
1309 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1310 LookupOrdinaryName);
1311 Result.setNamingClass(ULE->getNamingClass());
1312 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1313 Result.addDecl(*I, I.getAccess());
1314 Result.resolveKind();
1315 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1316 nullptr, S);
1317 }
1318
1319 // Otherwise, this is already in the form we needed, and no further checks
1320 // are necessary.
1321 return ULE;
1322}
1323
1324Sema::TemplateNameKindForDiagnostics
1325Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1326 auto *TD = Name.getAsTemplateDecl();
1327 if (!TD)
1328 return TemplateNameKindForDiagnostics::DependentTemplate;
1329 if (isa<ClassTemplateDecl>(TD))
1330 return TemplateNameKindForDiagnostics::ClassTemplate;
1331 if (isa<FunctionTemplateDecl>(TD))
1332 return TemplateNameKindForDiagnostics::FunctionTemplate;
1333 if (isa<VarTemplateDecl>(TD))
1334 return TemplateNameKindForDiagnostics::VarTemplate;
1335 if (isa<TypeAliasTemplateDecl>(TD))
1336 return TemplateNameKindForDiagnostics::AliasTemplate;
1337 if (isa<TemplateTemplateParmDecl>(TD))
1338 return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1339 if (isa<ConceptDecl>(TD))
1340 return TemplateNameKindForDiagnostics::Concept;
1341 return TemplateNameKindForDiagnostics::DependentTemplate;
1342}
1343
1344void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1345 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", 1346, __extension__ __PRETTY_FUNCTION__
))
1346 "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", 1346, __extension__ __PRETTY_FUNCTION__
))
;
1347 CurContext = DC;
1348 S->setEntity(DC);
1349}
1350
1351void Sema::PopDeclContext() {
1352 assert(CurContext && "DeclContext imbalance!")(static_cast <bool> (CurContext && "DeclContext imbalance!"
) ? void (0) : __assert_fail ("CurContext && \"DeclContext imbalance!\""
, "clang/lib/Sema/SemaDecl.cpp", 1352, __extension__ __PRETTY_FUNCTION__
))
;
1353
1354 CurContext = CurContext->getLexicalParent();
1355 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", 1355, __extension__ __PRETTY_FUNCTION__
))
;
1356}
1357
1358Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1359 Decl *D) {
1360 // Unlike PushDeclContext, the context to which we return is not necessarily
1361 // the containing DC of TD, because the new context will be some pre-existing
1362 // TagDecl definition instead of a fresh one.
1363 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1364 CurContext = cast<TagDecl>(D)->getDefinition();
1365 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", 1365, __extension__ __PRETTY_FUNCTION__
))
;
1366 // Start lookups from the parent of the current context; we don't want to look
1367 // into the pre-existing complete definition.
1368 S->setEntity(CurContext->getLookupParent());
1369 return Result;
1370}
1371
1372void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1373 CurContext = static_cast<decltype(CurContext)>(Context);
1374}
1375
1376/// EnterDeclaratorContext - Used when we must lookup names in the context
1377/// of a declarator's nested name specifier.
1378///
1379void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1380 // C++0x [basic.lookup.unqual]p13:
1381 // A name used in the definition of a static data member of class
1382 // X (after the qualified-id of the static member) is looked up as
1383 // if the name was used in a member function of X.
1384 // C++0x [basic.lookup.unqual]p14:
1385 // If a variable member of a namespace is defined outside of the
1386 // scope of its namespace then any name used in the definition of
1387 // the variable member (after the declarator-id) is looked up as
1388 // if the definition of the variable member occurred in its
1389 // namespace.
1390 // Both of these imply that we should push a scope whose context
1391 // is the semantic context of the declaration. We can't use
1392 // PushDeclContext here because that context is not necessarily
1393 // lexically contained in the current context. Fortunately,
1394 // the containing scope should have the appropriate information.
1395
1396 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", 1396, __extension__ __PRETTY_FUNCTION__
))
;
1397
1398#ifndef NDEBUG
1399 Scope *Ancestor = S->getParent();
1400 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1401 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", 1401, __extension__ __PRETTY_FUNCTION__
))
;
1402#endif
1403
1404 CurContext = DC;
1405 S->setEntity(DC);
1406
1407 if (S->getParent()->isTemplateParamScope()) {
1408 // Also set the corresponding entities for all immediately-enclosing
1409 // template parameter scopes.
1410 EnterTemplatedContext(S->getParent(), DC);
1411 }
1412}
1413
1414void Sema::ExitDeclaratorContext(Scope *S) {
1415 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", 1415, __extension__ __PRETTY_FUNCTION__
))
;
1416
1417 // Switch back to the lexical context. The safety of this is
1418 // enforced by an assert in EnterDeclaratorContext.
1419 Scope *Ancestor = S->getParent();
1420 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1421 CurContext = Ancestor->getEntity();
1422
1423 // We don't need to do anything with the scope, which is going to
1424 // disappear.
1425}
1426
1427void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1428 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", 1429, __extension__ __PRETTY_FUNCTION__
))
1429 "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", 1429, __extension__ __PRETTY_FUNCTION__
))
;
1430
1431 // C++20 [temp.local]p7:
1432 // In the definition of a member of a class template that appears outside
1433 // of the class template definition, the name of a member of the class
1434 // template hides the name of a template-parameter of any enclosing class
1435 // templates (but not a template-parameter of the member if the member is a
1436 // class or function template).
1437 // C++20 [temp.local]p9:
1438 // In the definition of a class template or in the definition of a member
1439 // of such a template that appears outside of the template definition, for
1440 // each non-dependent base class (13.8.2.1), if the name of the base class
1441 // or the name of a member of the base class is the same as the name of a
1442 // template-parameter, the base class name or member name hides the
1443 // template-parameter name (6.4.10).
1444 //
1445 // This means that a template parameter scope should be searched immediately
1446 // after searching the DeclContext for which it is a template parameter
1447 // scope. For example, for
1448 // template<typename T> template<typename U> template<typename V>
1449 // void N::A<T>::B<U>::f(...)
1450 // we search V then B<U> (and base classes) then U then A<T> (and base
1451 // classes) then T then N then ::.
1452 unsigned ScopeDepth = getTemplateDepth(S);
1453 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1454 DeclContext *SearchDCAfterScope = DC;
1455 for (; DC; DC = DC->getLookupParent()) {
1456 if (const TemplateParameterList *TPL =
1457 cast<Decl>(DC)->getDescribedTemplateParams()) {
1458 unsigned DCDepth = TPL->getDepth() + 1;
1459 if (DCDepth > ScopeDepth)
1460 continue;
1461 if (ScopeDepth == DCDepth)
1462 SearchDCAfterScope = DC = DC->getLookupParent();
1463 break;
1464 }
1465 }
1466 S->setLookupEntity(SearchDCAfterScope);
1467 }
1468}
1469
1470void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1471 // We assume that the caller has already called
1472 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1473 FunctionDecl *FD = D->getAsFunction();
1474 if (!FD)
1475 return;
1476
1477 // Same implementation as PushDeclContext, but enters the context
1478 // from the lexical parent, rather than the top-level class.
1479 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", 1480, __extension__ __PRETTY_FUNCTION__
))
1480 "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", 1480, __extension__ __PRETTY_FUNCTION__
))
;
1481 CurContext = FD;
1482 S->setEntity(CurContext);
1483
1484 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1485 ParmVarDecl *Param = FD->getParamDecl(P);
1486 // If the parameter has an identifier, then add it to the scope
1487 if (Param->getIdentifier()) {
1488 S->AddDecl(Param);
1489 IdResolver.AddDecl(Param);
1490 }
1491 }
1492}
1493
1494void Sema::ActOnExitFunctionContext() {
1495 // Same implementation as PopDeclContext, but returns to the lexical parent,
1496 // rather than the top-level class.
1497 assert(CurContext && "DeclContext imbalance!")(static_cast <bool> (CurContext && "DeclContext imbalance!"
) ? void (0) : __assert_fail ("CurContext && \"DeclContext imbalance!\""
, "clang/lib/Sema/SemaDecl.cpp", 1497, __extension__ __PRETTY_FUNCTION__
))
;
1498 CurContext = CurContext->getLexicalParent();
1499 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", 1499, __extension__ __PRETTY_FUNCTION__
))
;
1500}
1501
1502/// Determine whether overloading is allowed for a new function
1503/// declaration considering prior declarations of the same name.
1504///
1505/// This routine determines whether overloading is possible, not
1506/// whether a new declaration actually overloads a previous one.
1507/// It will return true in C++ (where overloads are alway permitted)
1508/// or, as a C extension, when either the new declaration or a
1509/// previous one is declared with the 'overloadable' attribute.
1510static bool AllowOverloadingOfFunction(const LookupResult &Previous,
1511 ASTContext &Context,
1512 const FunctionDecl *New) {
1513 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1514 return true;
1515
1516 // Multiversion function declarations are not overloads in the
1517 // usual sense of that term, but lookup will report that an
1518 // overload set was found if more than one multiversion function
1519 // declaration is present for the same name. It is therefore
1520 // inadequate to assume that some prior declaration(s) had
1521 // the overloadable attribute; checking is required. Since one
1522 // declaration is permitted to omit the attribute, it is necessary
1523 // to check at least two; hence the 'any_of' check below. Note that
1524 // the overloadable attribute is implicitly added to declarations
1525 // that were required to have it but did not.
1526 if (Previous.getResultKind() == LookupResult::FoundOverloaded) {
1527 return llvm::any_of(Previous, [](const NamedDecl *ND) {
1528 return ND->hasAttr<OverloadableAttr>();
1529 });
1530 } else if (Previous.getResultKind() == LookupResult::Found)
1531 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1532
1533 return false;
1534}
1535
1536/// Add this decl to the scope shadowed decl chains.
1537void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1538 // Move up the scope chain until we find the nearest enclosing
1539 // non-transparent context. The declaration will be introduced into this
1540 // scope.
1541 while (S->getEntity() && S->getEntity()->isTransparentContext())
1542 S = S->getParent();
1543
1544 // Add scoped declarations into their context, so that they can be
1545 // found later. Declarations without a context won't be inserted
1546 // into any context.
1547 if (AddToContext)
1548 CurContext->addDecl(D);
1549
1550 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1551 // are function-local declarations.
1552 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1553 return;
1554
1555 // Template instantiations should also not be pushed into scope.
1556 if (isa<FunctionDecl>(D) &&
1557 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1558 return;
1559
1560 // If this replaces anything in the current scope,
1561 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1562 IEnd = IdResolver.end();
1563 for (; I != IEnd; ++I) {
1564 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1565 S->RemoveDecl(*I);
1566 IdResolver.RemoveDecl(*I);
1567
1568 // Should only need to replace one decl.
1569 break;
1570 }
1571 }
1572
1573 S->AddDecl(D);
1574
1575 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1576 // Implicitly-generated labels may end up getting generated in an order that
1577 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1578 // the label at the appropriate place in the identifier chain.
1579 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1580 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1581 if (IDC == CurContext) {
1582 if (!S->isDeclScope(*I))
1583 continue;
1584 } else if (IDC->Encloses(CurContext))
1585 break;
1586 }
1587
1588 IdResolver.InsertDeclAfter(I, D);
1589 } else {
1590 IdResolver.AddDecl(D);
1591 }
1592 warnOnReservedIdentifier(D);
1593}
1594
1595bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1596 bool AllowInlineNamespace) const {
1597 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1598}
1599
1600Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1601 DeclContext *TargetDC = DC->getPrimaryContext();
1602 do {
1603 if (DeclContext *ScopeDC = S->getEntity())
1604 if (ScopeDC->getPrimaryContext() == TargetDC)
1605 return S;
1606 } while ((S = S->getParent()));
1607
1608 return nullptr;
1609}
1610
1611static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1612 DeclContext*,
1613 ASTContext&);
1614
1615/// Filters out lookup results that don't fall within the given scope
1616/// as determined by isDeclInScope.
1617void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1618 bool ConsiderLinkage,
1619 bool AllowInlineNamespace) {
1620 LookupResult::Filter F = R.makeFilter();
1621 while (F.hasNext()) {
1622 NamedDecl *D = F.next();
1623
1624 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1625 continue;
1626
1627 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1628 continue;
1629
1630 F.erase();
1631 }
1632
1633 F.done();
1634}
1635
1636/// We've determined that \p New is a redeclaration of \p Old. Check that they
1637/// have compatible owning modules.
1638bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1639 // [module.interface]p7:
1640 // A declaration is attached to a module as follows:
1641 // - If the declaration is a non-dependent friend declaration that nominates a
1642 // function with a declarator-id that is a qualified-id or template-id or that
1643 // nominates a class other than with an elaborated-type-specifier with neither
1644 // a nested-name-specifier nor a simple-template-id, it is attached to the
1645 // module to which the friend is attached ([basic.link]).
1646 if (New->getFriendObjectKind() &&
1647 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1648 New->setLocalOwningModule(Old->getOwningModule());
1649 makeMergedDefinitionVisible(New);
1650 return false;
1651 }
1652
1653 Module *NewM = New->getOwningModule();
1654 Module *OldM = Old->getOwningModule();
1655
1656 if (NewM && NewM->isPrivateModule())
1657 NewM = NewM->Parent;
1658 if (OldM && OldM->isPrivateModule())
1659 OldM = OldM->Parent;
1660
1661 if (NewM == OldM)
1662 return false;
1663
1664 if (NewM && OldM) {
1665 // A module implementation unit has visibility of the decls in its
1666 // implicitly imported interface.
1667 if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1668 return false;
1669
1670 // Partitions are part of the module, but a partition could import another
1671 // module, so verify that the PMIs agree.
1672 if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1673 NewM->getPrimaryModuleInterfaceName() ==
1674 OldM->getPrimaryModuleInterfaceName())
1675 return false;
1676 }
1677
1678 bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1679 bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1680 if (NewIsModuleInterface || OldIsModuleInterface) {
1681 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1682 // if a declaration of D [...] appears in the purview of a module, all
1683 // other such declarations shall appear in the purview of the same module
1684 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1685 << New
1686 << NewIsModuleInterface
1687 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1688 << OldIsModuleInterface
1689 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1690 Diag(Old->getLocation(), diag::note_previous_declaration);
1691 New->setInvalidDecl();
1692 return true;
1693 }
1694
1695 return false;
1696}
1697
1698// [module.interface]p6:
1699// A redeclaration of an entity X is implicitly exported if X was introduced by
1700// an exported declaration; otherwise it shall not be exported.
1701bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) {
1702 // [module.interface]p1:
1703 // An export-declaration shall inhabit a namespace scope.
1704 //
1705 // So it is meaningless to talk about redeclaration which is not at namespace
1706 // scope.
1707 if (!New->getLexicalDeclContext()
1708 ->getNonTransparentContext()
1709 ->isFileContext() ||
1710 !Old->getLexicalDeclContext()
1711 ->getNonTransparentContext()
1712 ->isFileContext())
1713 return false;
1714
1715 bool IsNewExported = New->isInExportDeclContext();
1716 bool IsOldExported = Old->isInExportDeclContext();
1717
1718 // It should be irrevelant if both of them are not exported.
1719 if (!IsNewExported && !IsOldExported)
1720 return false;
1721
1722 if (IsOldExported)
1723 return false;
1724
1725 assert(IsNewExported)(static_cast <bool> (IsNewExported) ? void (0) : __assert_fail
("IsNewExported", "clang/lib/Sema/SemaDecl.cpp", 1725, __extension__
__PRETTY_FUNCTION__))
;
1726
1727 auto Lk = Old->getFormalLinkage();
1728 int S = 0;
1729 if (Lk == Linkage::InternalLinkage)
1730 S = 1;
1731 else if (Lk == Linkage::ModuleLinkage)
1732 S = 2;
1733 Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1734 Diag(Old->getLocation(), diag::note_previous_declaration);
1735 return true;
1736}
1737
1738// A wrapper function for checking the semantic restrictions of
1739// a redeclaration within a module.
1740bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) {
1741 if (CheckRedeclarationModuleOwnership(New, Old))
1742 return true;
1743
1744 if (CheckRedeclarationExported(New, Old))
1745 return true;
1746
1747 return false;
1748}
1749
1750// Check the redefinition in C++20 Modules.
1751//
1752// [basic.def.odr]p14:
1753// For any definable item D with definitions in multiple translation units,
1754// - if D is a non-inline non-templated function or variable, or
1755// - if the definitions in different translation units do not satisfy the
1756// following requirements,
1757// the program is ill-formed; a diagnostic is required only if the definable
1758// item is attached to a named module and a prior definition is reachable at
1759// the point where a later definition occurs.
1760// - Each such definition shall not be attached to a named module
1761// ([module.unit]).
1762// - Each such definition shall consist of the same sequence of tokens, ...
1763// ...
1764//
1765// Return true if the redefinition is not allowed. Return false otherwise.
1766bool Sema::IsRedefinitionInModule(const NamedDecl *New,
1767 const NamedDecl *Old) const {
1768 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", 1770, __extension__ __PRETTY_FUNCTION__
))
1769 "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", 1770, __extension__ __PRETTY_FUNCTION__
))
1770 "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", 1770, __extension__ __PRETTY_FUNCTION__
))
;
1771 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", 1773, __extension__ __PRETTY_FUNCTION__
))
1772 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", 1773, __extension__ __PRETTY_FUNCTION__
))
1773 "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", 1773, __extension__ __PRETTY_FUNCTION__
))
;
1774
1775 Module *NewM = New->getOwningModule();
1776 Module *OldM = Old->getOwningModule();
1777
1778 // We only checks for named modules here. The header like modules is skipped.
1779 // FIXME: This is not right if we import the header like modules in the module
1780 // purview.
1781 //
1782 // For example, assuming "header.h" provides definition for `D`.
1783 // ```C++
1784 // //--- M.cppm
1785 // export module M;
1786 // import "header.h"; // or #include "header.h" but import it by clang modules
1787 // actually.
1788 //
1789 // //--- Use.cpp
1790 // import M;
1791 // import "header.h"; // or uses clang modules.
1792 // ```
1793 //
1794 // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1795 // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1796 // reject it. But the current implementation couldn't detect the case since we
1797 // don't record the information about the importee modules.
1798 //
1799 // But this might not be painful in practice. Since the design of C++20 Named
1800 // Modules suggests us to use headers in global module fragment instead of
1801 // module purview.
1802 if (NewM && NewM->isHeaderLikeModule())
1803 NewM = nullptr;
1804 if (OldM && OldM->isHeaderLikeModule())
1805 OldM = nullptr;
1806
1807 if (!NewM && !OldM)
1808 return true;
1809
1810 // [basic.def.odr]p14.3
1811 // Each such definition shall not be attached to a named module
1812 // ([module.unit]).
1813 if ((NewM && NewM->isModulePurview()) || (OldM && OldM->isModulePurview()))
1814 return true;
1815
1816 // Then New and Old lives in the same TU if their share one same module unit.
1817 if (NewM)
1818 NewM = NewM->getTopLevelModule();
1819 if (OldM)
1820 OldM = OldM->getTopLevelModule();
1821 return OldM == NewM;
1822}
1823
1824static bool isUsingDecl(NamedDecl *D) {
1825 return isa<UsingShadowDecl>(D) ||
1826 isa<UnresolvedUsingTypenameDecl>(D) ||
1827 isa<UnresolvedUsingValueDecl>(D);
1828}
1829
1830/// Removes using shadow declarations from the lookup results.
1831static void RemoveUsingDecls(LookupResult &R) {
1832 LookupResult::Filter F = R.makeFilter();
1833 while (F.hasNext())
1834 if (isUsingDecl(F.next()))
1835 F.erase();
1836
1837 F.done();
1838}
1839
1840/// Check for this common pattern:
1841/// @code
1842/// class S {
1843/// S(const S&); // DO NOT IMPLEMENT
1844/// void operator=(const S&); // DO NOT IMPLEMENT
1845/// };
1846/// @endcode
1847static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1848 // FIXME: Should check for private access too but access is set after we get
1849 // the decl here.
1850 if (D->doesThisDeclarationHaveABody())
1851 return false;
1852
1853 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1854 return CD->isCopyConstructor();
1855 return D->isCopyAssignmentOperator();
1856}
1857
1858// We need this to handle
1859//
1860// typedef struct {
1861// void *foo() { return 0; }
1862// } A;
1863//
1864// When we see foo we don't know if after the typedef we will get 'A' or '*A'
1865// for example. If 'A', foo will have external linkage. If we have '*A',
1866// foo will have no linkage. Since we can't know until we get to the end
1867// of the typedef, this function finds out if D might have non-external linkage.
1868// Callers should verify at the end of the TU if it D has external linkage or
1869// not.
1870bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1871 const DeclContext *DC = D->getDeclContext();
1872 while (!DC->isTranslationUnit()) {
1873 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1874 if (!RD->hasNameForLinkage())
1875 return true;
1876 }
1877 DC = DC->getParent();
1878 }
1879
1880 return !D->isExternallyVisible();
1881}
1882
1883// FIXME: This needs to be refactored; some other isInMainFile users want
1884// these semantics.
1885static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1886 if (S.TUKind != TU_Complete || S.getLangOpts().IsHeaderFile)
1887 return false;
1888 return S.SourceMgr.isInMainFile(Loc);
1889}
1890
1891bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1892 assert(D)(static_cast <bool> (D) ? void (0) : __assert_fail ("D"
, "clang/lib/Sema/SemaDecl.cpp", 1892, __extension__ __PRETTY_FUNCTION__
))
;
1893
1894 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1895 return false;
1896
1897 // Ignore all entities declared within templates, and out-of-line definitions
1898 // of members of class templates.
1899 if (D->getDeclContext()->isDependentContext() ||
1900 D->getLexicalDeclContext()->isDependentContext())
1901 return false;
1902
1903 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1904 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1905 return false;
1906 // A non-out-of-line declaration of a member specialization was implicitly
1907 // instantiated; it's the out-of-line declaration that we're interested in.
1908 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1909 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1910 return false;
1911
1912 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1913 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1914 return false;
1915 } else {
1916 // 'static inline' functions are defined in headers; don't warn.
1917 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1918 return false;
1919 }
1920
1921 if (FD->doesThisDeclarationHaveABody() &&
1922 Context.DeclMustBeEmitted(FD))
1923 return false;
1924 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1925 // Constants and utility variables are defined in headers with internal
1926 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1927 // like "inline".)
1928 if (!isMainFileLoc(*this, VD->getLocation()))
1929 return false;
1930
1931 if (Context.DeclMustBeEmitted(VD))
1932 return false;
1933
1934 if (VD->isStaticDataMember() &&
1935 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1936 return false;
1937 if (VD->isStaticDataMember() &&
1938 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1939 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1940 return false;
1941
1942 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1943 return false;
1944 } else {
1945 return false;
1946 }
1947
1948 // Only warn for unused decls internal to the translation unit.
1949 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1950 // for inline functions defined in the main source file, for instance.
1951 return mightHaveNonExternalLinkage(D);
1952}
1953
1954void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1955 if (!D)
1956 return;
1957
1958 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1959 const FunctionDecl *First = FD->getFirstDecl();
1960 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1961 return; // First should already be in the vector.
1962 }
1963
1964 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1965 const VarDecl *First = VD->getFirstDecl();
1966 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1967 return; // First should already be in the vector.
1968 }
1969
1970 if (ShouldWarnIfUnusedFileScopedDecl(D))
1971 UnusedFileScopedDecls.push_back(D);
1972}
1973
1974static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1975 if (D->isInvalidDecl())
1976 return false;
1977
1978 if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1979 // For a decomposition declaration, warn if none of the bindings are
1980 // referenced, instead of if the variable itself is referenced (which
1981 // it is, by the bindings' expressions).
1982 for (auto *BD : DD->bindings())
1983 if (BD->isReferenced())
1984 return false;
1985 } else if (!D->getDeclName()) {
1986 return false;
1987 } else if (D->isReferenced() || D->isUsed()) {
1988 return false;
1989 }
1990
1991 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>())
1992 return false;
1993
1994 if (isa<LabelDecl>(D))
1995 return true;
1996
1997 // Except for labels, we only care about unused decls that are local to
1998 // functions.
1999 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
2000 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
2001 // For dependent types, the diagnostic is deferred.
2002 WithinFunction =
2003 WithinFunction || (R->isLocalClass() && !R->isDependentType());
2004 if (!WithinFunction)
2005 return false;
2006
2007 if (isa<TypedefNameDecl>(D))
2008 return true;
2009
2010 // White-list anything that isn't a local variable.
2011 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
2012 return false;
2013
2014 // Types of valid local variables should be complete, so this should succeed.
2015 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2016
2017 const Expr *Init = VD->getInit();
2018 if (const auto *Cleanups = dyn_cast_or_null<ExprWithCleanups>(Init))
2019 Init = Cleanups->getSubExpr();
2020
2021 const auto *Ty = VD->getType().getTypePtr();
2022
2023 // Only look at the outermost level of typedef.
2024 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
2025 // Allow anything marked with __attribute__((unused)).
2026 if (TT->getDecl()->hasAttr<UnusedAttr>())
2027 return false;
2028 }
2029
2030 // Warn for reference variables whose initializtion performs lifetime
2031 // extension.
2032 if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>(Init)) {
2033 if (MTE->getExtendingDecl()) {
2034 Ty = VD->getType().getNonReferenceType().getTypePtr();
2035 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
2036 }
2037 }
2038
2039 // If we failed to complete the type for some reason, or if the type is
2040 // dependent, don't diagnose the variable.
2041 if (Ty->isIncompleteType() || Ty->isDependentType())
2042 return false;
2043
2044 // Look at the element type to ensure that the warning behaviour is
2045 // consistent for both scalars and arrays.
2046 Ty = Ty->getBaseElementTypeUnsafe();
2047
2048 if (const TagType *TT = Ty->getAs<TagType>()) {
2049 const TagDecl *Tag = TT->getDecl();
2050 if (Tag->hasAttr<UnusedAttr>())
2051 return false;
2052
2053 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2054 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2055 return false;
2056
2057 if (Init) {
2058 const CXXConstructExpr *Construct =
2059 dyn_cast<CXXConstructExpr>(Init);
2060 if (Construct && !Construct->isElidable()) {
2061 CXXConstructorDecl *CD = Construct->getConstructor();
2062 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2063 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2064 return false;
2065 }
2066
2067 // Suppress the warning if we don't know how this is constructed, and
2068 // it could possibly be non-trivial constructor.
2069 if (Init->isTypeDependent()) {
2070 for (const CXXConstructorDecl *Ctor : RD->ctors())
2071 if (!Ctor->isTrivial())
2072 return false;
2073 }
2074
2075 // Suppress the warning if the constructor is unresolved because
2076 // its arguments are dependent.
2077 if (isa<CXXUnresolvedConstructExpr>(Init))
2078 return false;
2079 }
2080 }
2081 }
2082
2083 // TODO: __attribute__((unused)) templates?
2084 }
2085
2086 return true;
2087}
2088
2089static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
2090 FixItHint &Hint) {
2091 if (isa<LabelDecl>(D)) {
2092 SourceLocation AfterColon = Lexer::findLocationAfterToken(
2093 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
2094 true);
2095 if (AfterColon.isInvalid())
2096 return;
2097 Hint = FixItHint::CreateRemoval(
2098 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
2099 }
2100}
2101
2102void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
2103 DiagnoseUnusedNestedTypedefs(
2104 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2105}
2106
2107void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D,
2108 DiagReceiverTy DiagReceiver) {
2109 if (D->getTypeForDecl()->isDependentType())
2110 return;
2111
2112 for (auto *TmpD : D->decls()) {
2113 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2114 DiagnoseUnusedDecl(T, DiagReceiver);
2115 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2116 DiagnoseUnusedNestedTypedefs(R, DiagReceiver);
2117 }
2118}
2119
2120void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
2121 DiagnoseUnusedDecl(
2122 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2123}
2124
2125/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
2126/// unless they are marked attr(unused).
2127void Sema::DiagnoseUnusedDecl(const NamedDecl *D, DiagReceiverTy DiagReceiver) {
2128 if (!ShouldDiagnoseUnusedDecl(D))
2129 return;
2130
2131 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2132 // typedefs can be referenced later on, so the diagnostics are emitted
2133 // at end-of-translation-unit.
2134 UnusedLocalTypedefNameCandidates.insert(TD);
2135 return;
2136 }
2137
2138 FixItHint Hint;
2139 GenerateFixForUnusedDecl(D, Context, Hint);
2140
2141 unsigned DiagID;
2142 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2143 DiagID = diag::warn_unused_exception_param;
2144 else if (isa<LabelDecl>(D))
2145 DiagID = diag::warn_unused_label;
2146 else
2147 DiagID = diag::warn_unused_variable;
2148
2149 DiagReceiver(D->getLocation(), PDiag(DiagID) << D << Hint);
2150}
2151
2152void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD,
2153 DiagReceiverTy DiagReceiver) {
2154 // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2155 // it's not really unused.
2156 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>() ||
2157 VD->hasAttr<CleanupAttr>())
2158 return;
2159
2160 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2161
2162 if (Ty->isReferenceType() || Ty->isDependentType())
2163 return;
2164
2165 if (const TagType *TT = Ty->getAs<TagType>()) {
2166 const TagDecl *Tag = TT->getDecl();
2167 if (Tag->hasAttr<UnusedAttr>())
2168 return;
2169 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2170 // mimic gcc's behavior.
2171 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2172 if (!RD->hasAttr<WarnUnusedAttr>())
2173 return;
2174 }
2175 }
2176
2177 // Don't warn about __block Objective-C pointer variables, as they might
2178 // be assigned in the block but not used elsewhere for the purpose of lifetime
2179 // extension.
2180 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2181 return;
2182
2183 // Don't warn about Objective-C pointer variables with precise lifetime
2184 // semantics; they can be used to ensure ARC releases the object at a known
2185 // time, which may mean assignment but no other references.
2186 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2187 return;
2188
2189 auto iter = RefsMinusAssignments.find(VD);
2190 if (iter == RefsMinusAssignments.end())
2191 return;
2192
2193 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", 2194, __extension__ __PRETTY_FUNCTION__
))
2194 "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", 2194, __extension__ __PRETTY_FUNCTION__
))
;
2195 if (iter->getSecond() != 0)
2196 return;
2197 unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2198 : diag::warn_unused_but_set_variable;
2199 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2200}
2201
2202static void CheckPoppedLabel(LabelDecl *L, Sema &S,
2203 Sema::DiagReceiverTy DiagReceiver) {
2204 // Verify that we have no forward references left. If so, there was a goto
2205 // or address of a label taken, but no definition of it. Label fwd
2206 // definitions are indicated with a null substmt which is also not a resolved
2207 // MS inline assembly label name.
2208 bool Diagnose = false;
2209 if (L->isMSAsmLabel())
2210 Diagnose = !L->isResolvedMSAsmLabel();
2211 else
2212 Diagnose = L->getStmt() == nullptr;
2213 if (Diagnose)
2214 DiagReceiver(L->getLocation(), S.PDiag(diag::err_undeclared_label_use)
2215 << L);
2216}
2217
2218void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
2219 S->applyNRVO();
2220
2221 if (S->decl_empty()) return;
2222 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", 2223, __extension__ __PRETTY_FUNCTION__
))
2223 "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", 2223, __extension__ __PRETTY_FUNCTION__
))
;
2224
2225 /// We visit the decls in non-deterministic order, but we want diagnostics
2226 /// emitted in deterministic order. Collect any diagnostic that may be emitted
2227 /// and sort the diagnostics before emitting them, after we visited all decls.
2228 struct LocAndDiag {
2229 SourceLocation Loc;
2230 std::optional<SourceLocation> PreviousDeclLoc;
2231 PartialDiagnostic PD;
2232 };
2233 SmallVector<LocAndDiag, 16> DeclDiags;
2234 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2235 DeclDiags.push_back(LocAndDiag{Loc, std::nullopt, std::move(PD)});
2236 };
2237 auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2238 SourceLocation PreviousDeclLoc,
2239 PartialDiagnostic PD) {
2240 DeclDiags.push_back(LocAndDiag{Loc, PreviousDeclLoc, std::move(PD)});
2241 };
2242
2243 for (auto *TmpD : S->decls()) {
2244 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", 2244, __extension__ __PRETTY_FUNCTION__
))
;
2245
2246 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", 2246, __extension__ __PRETTY_FUNCTION__
))
;
2247 NamedDecl *D = cast<NamedDecl>(TmpD);
2248
2249 // Diagnose unused variables in this scope.
2250 if (!S->hasUnrecoverableErrorOccurred()) {
2251 DiagnoseUnusedDecl(D, addDiag);
2252 if (const auto *RD = dyn_cast<RecordDecl>(D))
2253 DiagnoseUnusedNestedTypedefs(RD, addDiag);
2254 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2255 DiagnoseUnusedButSetDecl(VD, addDiag);
2256 RefsMinusAssignments.erase(VD);
2257 }
2258 }
2259
2260 if (!D->getDeclName()) continue;
2261
2262 // If this was a forward reference to a label, verify it was defined.
2263 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2264 CheckPoppedLabel(LD, *this, addDiag);
2265
2266 // Remove this name from our lexical scope, and warn on it if we haven't
2267 // already.
2268 IdResolver.RemoveDecl(D);
2269 auto ShadowI = ShadowingDecls.find(D);
2270 if (ShadowI != ShadowingDecls.end()) {
2271 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2272 addDiagWithPrev(D->getLocation(), FD->getLocation(),
2273 PDiag(diag::warn_ctor_parm_shadows_field)
2274 << D << FD << FD->getParent());
2275 }
2276 ShadowingDecls.erase(ShadowI);
2277 }
2278 }
2279
2280 llvm::sort(DeclDiags,
2281 [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2282 // The particular order for diagnostics is not important, as long
2283 // as the order is deterministic. Using the raw location is going
2284 // to generally be in source order unless there are macro
2285 // expansions involved.
2286 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2287 });
2288 for (const LocAndDiag &D : DeclDiags) {
2289 Diag(D.Loc, D.PD);
2290 if (D.PreviousDeclLoc)
2291 Diag(*D.PreviousDeclLoc, diag::note_previous_declaration);
2292 }
2293}
2294
2295/// Look for an Objective-C class in the translation unit.
2296///
2297/// \param Id The name of the Objective-C class we're looking for. If
2298/// typo-correction fixes this name, the Id will be updated
2299/// to the fixed name.
2300///
2301/// \param IdLoc The location of the name in the translation unit.
2302///
2303/// \param DoTypoCorrection If true, this routine will attempt typo correction
2304/// if there is no class with the given name.
2305///
2306/// \returns The declaration of the named Objective-C class, or NULL if the
2307/// class could not be found.
2308ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
2309 SourceLocation IdLoc,
2310 bool DoTypoCorrection) {
2311 // The third "scope" argument is 0 since we aren't enabling lazy built-in
2312 // creation from this context.
2313 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
2314
2315 if (!IDecl && DoTypoCorrection) {
2316 // Perform typo correction at the given location, but only if we
2317 // find an Objective-C class name.
2318 DeclFilterCCC<ObjCInterfaceDecl> CCC{};
2319 if (TypoCorrection C =
2320 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
2321 TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
2322 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
2323 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
2324 Id = IDecl->getIdentifier();
2325 }
2326 }
2327 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
2328 // This routine must always return a class definition, if any.
2329 if (Def && Def->getDefinition())
2330 Def = Def->getDefinition();
2331 return Def;
2332}
2333
2334/// getNonFieldDeclScope - Retrieves the innermost scope, starting
2335/// from S, where a non-field would be declared. This routine copes
2336/// with the difference between C and C++ scoping rules in structs and
2337/// unions. For example, the following code is well-formed in C but
2338/// ill-formed in C++:
2339/// @code
2340/// struct S6 {
2341/// enum { BAR } e;
2342/// };
2343///
2344/// void test_S6() {
2345/// struct S6 a;
2346/// a.e = BAR;
2347/// }
2348/// @endcode
2349/// For the declaration of BAR, this routine will return a different
2350/// scope. The scope S will be the scope of the unnamed enumeration
2351/// within S6. In C++, this routine will return the scope associated
2352/// with S6, because the enumeration's scope is a transparent
2353/// context but structures can contain non-field names. In C, this
2354/// routine will return the translation unit scope, since the
2355/// enumeration's scope is a transparent context and structures cannot
2356/// contain non-field names.
2357Scope *Sema::getNonFieldDeclScope(Scope *S) {
2358 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2359 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2360 (S->isClassScope() && !getLangOpts().CPlusPlus))
2361 S = S->getParent();
2362 return S;
2363}
2364
2365static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2366 ASTContext::GetBuiltinTypeError Error) {
2367 switch (Error) {
2368 case ASTContext::GE_None:
2369 return "";
2370 case ASTContext::GE_Missing_type:
2371 return BuiltinInfo.getHeaderName(ID);
2372 case ASTContext::GE_Missing_stdio:
2373 return "stdio.h";
2374 case ASTContext::GE_Missing_setjmp:
2375 return "setjmp.h";
2376 case ASTContext::GE_Missing_ucontext:
2377 return "ucontext.h";
2378 }
2379 llvm_unreachable("unhandled error kind")::llvm::llvm_unreachable_internal("unhandled error kind", "clang/lib/Sema/SemaDecl.cpp"
, 2379)
;
2380}
2381
2382FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2383 unsigned ID, SourceLocation Loc) {
2384 DeclContext *Parent = Context.getTranslationUnitDecl();
2385
2386 if (getLangOpts().CPlusPlus) {
2387 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2388 Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
2389 CLinkageDecl->setImplicit();
2390 Parent->addDecl(CLinkageDecl);
2391 Parent = CLinkageDecl;
2392 }
2393
2394 FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2395 /*TInfo=*/nullptr, SC_Extern,
2396 getCurFPFeatures().isFPConstrained(),
2397 false, Type->isFunctionProtoType());
2398 New->setImplicit();
2399 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2400
2401 // Create Decl objects for each parameter, adding them to the
2402 // FunctionDecl.
2403 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2404 SmallVector<ParmVarDecl *, 16> Params;
2405 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2406 ParmVarDecl *parm = ParmVarDecl::Create(
2407 Context, New, SourceLocation(), SourceLocation(), nullptr,
2408 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2409 parm->setScopeInfo(0, i);
2410 Params.push_back(parm);
2411 }
2412 New->setParams(Params);
2413 }
2414
2415 AddKnownFunctionAttributes(New);
2416 return New;
2417}
2418
2419/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2420/// file scope. lazily create a decl for it. ForRedeclaration is true
2421/// if we're creating this built-in in anticipation of redeclaring the
2422/// built-in.
2423NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2424 Scope *S, bool ForRedeclaration,
2425 SourceLocation Loc) {
2426 LookupNecessaryTypesForBuiltin(S, ID);
2427
2428 ASTContext::GetBuiltinTypeError Error;
2429 QualType R = Context.GetBuiltinType(ID, Error);
2430 if (Error) {
2431 if (!ForRedeclaration)
2432 return nullptr;
2433
2434 // If we have a builtin without an associated type we should not emit a
2435 // warning when we were not able to find a type for it.
2436 if (Error == ASTContext::GE_Missing_type ||
2437 Context.BuiltinInfo.allowTypeMismatch(ID))
2438 return nullptr;
2439
2440 // If we could not find a type for setjmp it is because the jmp_buf type was
2441 // not defined prior to the setjmp declaration.
2442 if (Error == ASTContext::GE_Missing_setjmp) {
2443 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2444 << Context.BuiltinInfo.getName(ID);
2445 return nullptr;
2446 }
2447
2448 // Generally, we emit a warning that the declaration requires the
2449 // appropriate header.
2450 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2451 << getHeaderName(Context.BuiltinInfo, ID, Error)
2452 << Context.BuiltinInfo.getName(ID);
2453 return nullptr;
2454 }
2455
2456 if (!ForRedeclaration &&
2457 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2458 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2459 Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2460 : diag::ext_implicit_lib_function_decl)
2461 << Context.BuiltinInfo.getName(ID) << R;
2462 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2463 Diag(Loc, diag::note_include_header_or_declare)
2464 << Header << Context.BuiltinInfo.getName(ID);
2465 }
2466
2467 if (R.isNull())
2468 return nullptr;
2469
2470 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2471 RegisterLocallyScopedExternCDecl(New, S);
2472
2473 // TUScope is the translation-unit scope to insert this function into.
2474 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2475 // relate Scopes to DeclContexts, and probably eliminate CurContext
2476 // entirely, but we're not there yet.
2477 DeclContext *SavedContext = CurContext;
2478 CurContext = New->getDeclContext();
2479 PushOnScopeChains(New, TUScope);
2480 CurContext = SavedContext;
2481 return New;
2482}
2483
2484/// Typedef declarations don't have linkage, but they still denote the same
2485/// entity if their types are the same.
2486/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2487/// isSameEntity.
2488static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2489 TypedefNameDecl *Decl,
2490 LookupResult &Previous) {
2491 // This is only interesting when modules are enabled.
2492 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2493 return;
2494
2495 // Empty sets are uninteresting.
2496 if (Previous.empty())
2497 return;
2498
2499 LookupResult::Filter Filter = Previous.makeFilter();
2500 while (Filter.hasNext()) {
2501 NamedDecl *Old = Filter.next();
2502
2503 // Non-hidden declarations are never ignored.
2504 if (S.isVisible(Old))
2505 continue;
2506
2507 // Declarations of the same entity are not ignored, even if they have
2508 // different linkages.
2509 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2510 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2511 Decl->getUnderlyingType()))
2512 continue;
2513
2514 // If both declarations give a tag declaration a typedef name for linkage
2515 // purposes, then they declare the same entity.
2516 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2517 Decl->getAnonDeclWithTypedefName())
2518 continue;
2519 }
2520
2521 Filter.erase();
2522 }
2523
2524 Filter.done();
2525}
2526
2527bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2528 QualType OldType;
2529 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2530 OldType = OldTypedef->getUnderlyingType();
2531 else
2532 OldType = Context.getTypeDeclType(Old);
2533 QualType NewType = New->getUnderlyingType();
2534
2535 if (NewType->isVariablyModifiedType()) {
2536 // Must not redefine a typedef with a variably-modified type.
2537 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2538 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2539 << Kind << NewType;
2540 if (Old->getLocation().isValid())
2541 notePreviousDefinition(Old, New->getLocation());
2542 New->setInvalidDecl();
2543 return true;
2544 }
2545
2546 if (OldType != NewType &&
2547 !OldType->isDependentType() &&
2548 !NewType->isDependentType() &&
2549 !Context.hasSameType(OldType, NewType)) {
2550 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2551 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2552 << Kind << NewType << OldType;
2553 if (Old->getLocation().isValid())
2554 notePreviousDefinition(Old, New->getLocation());
2555 New->setInvalidDecl();
2556 return true;
2557 }
2558 return false;
2559}
2560
2561/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2562/// same name and scope as a previous declaration 'Old'. Figure out
2563/// how to resolve this situation, merging decls or emitting
2564/// diagnostics as appropriate. If there was an error, set New to be invalid.
2565///
2566void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2567 LookupResult &OldDecls) {
2568 // If the new decl is known invalid already, don't bother doing any
2569 // merging checks.
2570 if (New->isInvalidDecl()) return;
2571
2572 // Allow multiple definitions for ObjC built-in typedefs.
2573 // FIXME: Verify the underlying types are equivalent!
2574 if (getLangOpts().ObjC) {
2575 const IdentifierInfo *TypeID = New->getIdentifier();
2576 switch (TypeID->getLength()) {
2577 default: break;
2578 case 2:
2579 {
2580 if (!TypeID->isStr("id"))
2581 break;
2582 QualType T = New->getUnderlyingType();
2583 if (!T->isPointerType())
2584 break;
2585 if (!T->isVoidPointerType()) {
2586 QualType PT = T->castAs<PointerType>()->getPointeeType();
2587 if (!PT->isStructureType())
2588 break;
2589 }
2590 Context.setObjCIdRedefinitionType(T);
2591 // Install the built-in type for 'id', ignoring the current definition.
2592 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2593 return;
2594 }
2595 case 5:
2596 if (!TypeID->isStr("Class"))
2597 break;
2598 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2599 // Install the built-in type for 'Class', ignoring the current definition.
2600 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2601 return;
2602 case 3:
2603 if (!TypeID->isStr("SEL"))
2604 break;
2605 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2606 // Install the built-in type for 'SEL', ignoring the current definition.
2607 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2608 return;
2609 }
2610 // Fall through - the typedef name was not a builtin type.
2611 }
2612
2613 // Verify the old decl was also a type.
2614 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2615 if (!Old) {
2616 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2617 << New->getDeclName();
2618
2619 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2620 if (OldD->getLocation().isValid())
2621 notePreviousDefinition(OldD, New->getLocation());
2622
2623 return New->setInvalidDecl();
2624 }
2625
2626 // If the old declaration is invalid, just give up here.
2627 if (Old->isInvalidDecl())
2628 return New->setInvalidDecl();
2629
2630 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2631 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2632 auto *NewTag = New->getAnonDeclWithTypedefName();
2633 NamedDecl *Hidden = nullptr;
2634 if (OldTag && NewTag &&
2635 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2636 !hasVisibleDefinition(OldTag, &Hidden)) {
2637 // There is a definition of this tag, but it is not visible. Use it
2638 // instead of our tag.
2639 New->setTypeForDecl(OldTD->getTypeForDecl());
2640 if (OldTD->isModed())
2641 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2642 OldTD->getUnderlyingType());
2643 else
2644 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2645
2646 // Make the old tag definition visible.
2647 makeMergedDefinitionVisible(Hidden);
2648
2649 // If this was an unscoped enumeration, yank all of its enumerators
2650 // out of the scope.
2651 if (isa<EnumDecl>(NewTag)) {
2652 Scope *EnumScope = getNonFieldDeclScope(S);
2653 for (auto *D : NewTag->decls()) {
2654 auto *ED = cast<EnumConstantDecl>(D);
2655 assert(EnumScope->isDeclScope(ED))(static_cast <bool> (EnumScope->isDeclScope(ED)) ? void
(0) : __assert_fail ("EnumScope->isDeclScope(ED)", "clang/lib/Sema/SemaDecl.cpp"
, 2655, __extension__ __PRETTY_FUNCTION__))
;
2656 EnumScope->RemoveDecl(ED);
2657 IdResolver.RemoveDecl(ED);
2658 ED->getLexicalDeclContext()->removeDecl(ED);
2659 }
2660 }
2661 }
2662 }
2663
2664 // If the typedef types are not identical, reject them in all languages and
2665 // with any extensions enabled.
2666 if (isIncompatibleTypedef(Old, New))
2667 return;
2668
2669 // The types match. Link up the redeclaration chain and merge attributes if
2670 // the old declaration was a typedef.
2671 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2672 New->setPreviousDecl(Typedef);
2673 mergeDeclAttributes(New, Old);
2674 }
2675
2676 if (getLangOpts().MicrosoftExt)
2677 return;
2678
2679 if (getLangOpts().CPlusPlus) {
2680 // C++ [dcl.typedef]p2:
2681 // In a given non-class scope, a typedef specifier can be used to
2682 // redefine the name of any type declared in that scope to refer
2683 // to the type to which it already refers.
2684 if (!isa<CXXRecordDecl>(CurContext))
2685 return;
2686
2687 // C++0x [dcl.typedef]p4:
2688 // In a given class scope, a typedef specifier can be used to redefine
2689 // any class-name declared in that scope that is not also a typedef-name
2690 // to refer to the type to which it already refers.
2691 //
2692 // This wording came in via DR424, which was a correction to the
2693 // wording in DR56, which accidentally banned code like:
2694 //
2695 // struct S {
2696 // typedef struct A { } A;
2697 // };
2698 //
2699 // in the C++03 standard. We implement the C++0x semantics, which
2700 // allow the above but disallow
2701 //
2702 // struct S {
2703 // typedef int I;
2704 // typedef int I;
2705 // };
2706 //
2707 // since that was the intent of DR56.
2708 if (!isa<TypedefNameDecl>(Old))
2709 return;
2710
2711 Diag(New->getLocation(), diag::err_redefinition)
2712 << New->getDeclName();
2713 notePreviousDefinition(Old, New->getLocation());
2714 return New->setInvalidDecl();
2715 }
2716
2717 // Modules always permit redefinition of typedefs, as does C11.
2718 if (getLangOpts().Modules || getLangOpts().C11)
2719 return;
2720
2721 // If we have a redefinition of a typedef in C, emit a warning. This warning
2722 // is normally mapped to an error, but can be controlled with
2723 // -Wtypedef-redefinition. If either the original or the redefinition is
2724 // in a system header, don't emit this for compatibility with GCC.
2725 if (getDiagnostics().getSuppressSystemWarnings() &&
2726 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2727 (Old->isImplicit() ||
2728 Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2729 Context.getSourceManager().isInSystemHeader(New->getLocation())))
2730 return;
2731
2732 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2733 << New->getDeclName();
2734 notePreviousDefinition(Old, New->getLocation());
2735}
2736
2737/// DeclhasAttr - returns true if decl Declaration already has the target
2738/// attribute.
2739static bool DeclHasAttr(const Decl *D, const Attr *A) {
2740 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2741 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2742 for (const auto *i : D->attrs())
2743 if (i->getKind() == A->getKind()) {
2744 if (Ann) {
2745 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2746 return true;
2747 continue;
2748 }
2749 // FIXME: Don't hardcode this check
2750 if (OA && isa<OwnershipAttr>(i))
2751 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2752 return true;
2753 }
2754
2755 return false;
2756}
2757
2758static bool isAttributeTargetADefinition(Decl *D) {
2759 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2760 return VD->isThisDeclarationADefinition();
2761 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2762 return TD->isCompleteDefinition() || TD->isBeingDefined();
2763 return true;
2764}
2765
2766/// Merge alignment attributes from \p Old to \p New, taking into account the
2767/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2768///
2769/// \return \c true if any attributes were added to \p New.
2770static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2771 // Look for alignas attributes on Old, and pick out whichever attribute
2772 // specifies the strictest alignment requirement.
2773 AlignedAttr *OldAlignasAttr = nullptr;
2774 AlignedAttr *OldStrictestAlignAttr = nullptr;
2775 unsigned OldAlign = 0;
2776 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2777 // FIXME: We have no way of representing inherited dependent alignments
2778 // in a case like:
2779 // template<int A, int B> struct alignas(A) X;
2780 // template<int A, int B> struct alignas(B) X {};
2781 // For now, we just ignore any alignas attributes which are not on the
2782 // definition in such a case.
2783 if (I->isAlignmentDependent())
2784 return false;
2785
2786 if (I->isAlignas())
2787 OldAlignasAttr = I;
2788
2789 unsigned Align = I->getAlignment(S.Context);
2790 if (Align > OldAlign) {
2791 OldAlign = Align;
2792 OldStrictestAlignAttr = I;
2793 }
2794 }
2795
2796 // Look for alignas attributes on New.
2797 AlignedAttr *NewAlignasAttr = nullptr;
2798 unsigned NewAlign = 0;
2799 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2800 if (I->isAlignmentDependent())
2801 return false;
2802
2803 if (I->isAlignas())
2804 NewAlignasAttr = I;
2805
2806 unsigned Align = I->getAlignment(S.Context);
2807 if (Align > NewAlign)
2808 NewAlign = Align;
2809 }
2810
2811 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2812 // Both declarations have 'alignas' attributes. We require them to match.
2813 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2814 // fall short. (If two declarations both have alignas, they must both match
2815 // every definition, and so must match each other if there is a definition.)
2816
2817 // If either declaration only contains 'alignas(0)' specifiers, then it
2818 // specifies the natural alignment for the type.
2819 if (OldAlign == 0 || NewAlign == 0) {
2820 QualType Ty;
2821 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2822 Ty = VD->getType();
2823 else
2824 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2825
2826 if (OldAlign == 0)
2827 OldAlign = S.Context.getTypeAlign(Ty);
2828 if (NewAlign == 0)
2829 NewAlign = S.Context.getTypeAlign(Ty);
2830 }
2831
2832 if (OldAlign != NewAlign) {
2833 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2834 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2835 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2836 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2837 }
2838 }
2839
2840 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2841 // C++11 [dcl.align]p6:
2842 // if any declaration of an entity has an alignment-specifier,
2843 // every defining declaration of that entity shall specify an
2844 // equivalent alignment.
2845 // C11 6.7.5/7:
2846 // If the definition of an object does not have an alignment
2847 // specifier, any other declaration of that object shall also
2848 // have no alignment specifier.
2849 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2850 << OldAlignasAttr;
2851 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2852 << OldAlignasAttr;
2853 }
2854
2855 bool AnyAdded = false;
2856
2857 // Ensure we have an attribute representing the strictest alignment.
2858 if (OldAlign > NewAlign) {
2859 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2860 Clone->setInherited(true);
2861 New->addAttr(Clone);
2862 AnyAdded = true;
2863 }
2864
2865 // Ensure we have an alignas attribute if the old declaration had one.
2866 if (OldAlignasAttr && !NewAlignasAttr &&
2867 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2868 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2869 Clone->setInherited(true);
2870 New->addAttr(Clone);
2871 AnyAdded = true;
2872 }
2873
2874 return AnyAdded;
2875}
2876
2877#define WANT_DECL_MERGE_LOGIC
2878#include "clang/Sema/AttrParsedAttrImpl.inc"
2879#undef WANT_DECL_MERGE_LOGIC
2880
2881static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2882 const InheritableAttr *Attr,
2883 Sema::AvailabilityMergeKind AMK) {
2884 // Diagnose any mutual exclusions between the attribute that we want to add
2885 // and attributes that already exist on the declaration.
2886 if (!DiagnoseMutualExclusions(S, D, Attr))
2887 return false;
2888
2889 // This function copies an attribute Attr from a previous declaration to the
2890 // new declaration D if the new declaration doesn't itself have that attribute
2891 // yet or if that attribute allows duplicates.
2892 // If you're adding a new attribute that requires logic different from
2893 // "use explicit attribute on decl if present, else use attribute from
2894 // previous decl", for example if the attribute needs to be consistent
2895 // between redeclarations, you need to call a custom merge function here.
2896 InheritableAttr *NewAttr = nullptr;
2897 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2898 NewAttr = S.mergeAvailabilityAttr(
2899 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2900 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2901 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2902 AA->getPriority());
2903 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2904 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2905 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2906 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2907 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2908 NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2909 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2910 NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2911 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2912 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2913 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2914 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2915 FA->getFirstArg());
2916 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2917 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2918 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2919 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2920 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2921 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2922 IA->getInheritanceModel());
2923 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2924 NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2925 &S.Context.Idents.get(AA->getSpelling()));
2926 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2927 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2928 isa<CUDAGlobalAttr>(Attr))) {
2929 // CUDA target attributes are part of function signature for
2930 // overloading purposes and must not be merged.
2931 return false;
2932 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2933 NewAttr = S.mergeMinSizeAttr(D, *MA);
2934 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2935 NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2936 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2937 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2938 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2939 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2940 else if (isa<AlignedAttr>(Attr))
2941 // AlignedAttrs are handled separately, because we need to handle all
2942 // such attributes on a declaration at the same time.
2943 NewAttr = nullptr;
2944 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2945 (AMK == Sema::AMK_Override ||
2946 AMK == Sema::AMK_ProtocolImplementation ||
2947 AMK == Sema::AMK_OptionalProtocolImplementation))
2948 NewAttr = nullptr;
2949 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2950 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2951 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2952 NewAttr = S.mergeImportModuleAttr(D, *IMA);
2953 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2954 NewAttr = S.mergeImportNameAttr(D, *INA);
2955 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2956 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2957 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2958 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2959 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2960 NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2961 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
2962 NewAttr =
2963 S.mergeHLSLNumThreadsAttr(D, *NT, NT->getX(), NT->getY(), NT->getZ());
2964 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
2965 NewAttr = S.mergeHLSLShaderAttr(D, *SA, SA->getType());
2966 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2967 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2968
2969 if (NewAttr) {
2970 NewAttr->setInherited(true);
2971 D->addAttr(NewAttr);
2972 if (isa<MSInheritanceAttr>(NewAttr))
2973 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2974 return true;
2975 }
2976
2977 return false;
2978}
2979
2980static const NamedDecl *getDefinition(const Decl *D) {
2981 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2982 return TD->getDefinition();
2983 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2984 const VarDecl *Def = VD->getDefinition();
2985 if (Def)
2986 return Def;
2987 return VD->getActingDefinition();
2988 }
2989 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2990 const FunctionDecl *Def = nullptr;
2991 if (FD->isDefined(Def, true))
2992 return Def;
2993 }
2994 return nullptr;
2995}
2996
2997static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2998 for (const auto *Attribute : D->attrs())
2999 if (Attribute->getKind() == Kind)
3000 return true;
3001 return false;
3002}
3003
3004/// checkNewAttributesAfterDef - If we already have a definition, check that
3005/// there are no new attributes in this declaration.
3006static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
3007 if (!New->hasAttrs())
3008 return;
3009
3010 const NamedDecl *Def = getDefinition(Old);
3011 if (!Def || Def == New)
3012 return;
3013
3014 AttrVec &NewAttributes = New->getAttrs();
3015 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
3016 const Attr *NewAttribute = NewAttributes[I];
3017
3018 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
3019 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
3020 Sema::SkipBodyInfo SkipBody;
3021 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
3022
3023 // If we're skipping this definition, drop the "alias" attribute.
3024 if (SkipBody.ShouldSkip) {
3025 NewAttributes.erase(NewAttributes.begin() + I);
3026 --E;
3027 continue;
3028 }
3029 } else {
3030 VarDecl *VD = cast<VarDecl>(New);
3031 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
3032 VarDecl::TentativeDefinition
3033 ? diag::err_alias_after_tentative
3034 : diag::err_redefinition;
3035 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
3036 if (Diag == diag::err_redefinition)
3037 S.notePreviousDefinition(Def, VD->getLocation());
3038 else
3039 S.Diag(Def->getLocation(), diag::note_previous_definition);
3040 VD->setInvalidDecl();
3041 }
3042 ++I;
3043 continue;
3044 }
3045
3046 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
3047 // Tentative definitions are only interesting for the alias check above.
3048 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
3049 ++I;
3050 continue;
3051 }
3052 }
3053
3054 if (hasAttribute(Def, NewAttribute->getKind())) {
3055 ++I;
3056 continue; // regular attr merging will take care of validating this.
3057 }
3058
3059 if (isa<C11NoReturnAttr>(NewAttribute)) {
3060 // C's _Noreturn is allowed to be added to a function after it is defined.
3061 ++I;
3062 continue;
3063 } else if (isa<UuidAttr>(NewAttribute)) {
3064 // msvc will allow a subsequent definition to add an uuid to a class
3065 ++I;
3066 continue;
3067 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
3068 if (AA->isAlignas()) {
3069 // C++11 [dcl.align]p6:
3070 // if any declaration of an entity has an alignment-specifier,
3071 // every defining declaration of that entity shall specify an
3072 // equivalent alignment.
3073 // C11 6.7.5/7:
3074 // If the definition of an object does not have an alignment
3075 // specifier, any other declaration of that object shall also
3076 // have no alignment specifier.
3077 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
3078 << AA;
3079 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
3080 << AA;
3081 NewAttributes.erase(NewAttributes.begin() + I);
3082 --E;
3083 continue;
3084 }
3085 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
3086 // If there is a C definition followed by a redeclaration with this
3087 // attribute then there are two different definitions. In C++, prefer the
3088 // standard diagnostics.
3089 if (!S.getLangOpts().CPlusPlus) {
3090 S.Diag(NewAttribute->getLocation(),
3091 diag::err_loader_uninitialized_redeclaration);
3092 S.Diag(Def->getLocation(), diag::note_previous_definition);
3093 NewAttributes.erase(NewAttributes.begin() + I);
3094 --E;
3095 continue;
3096 }
3097 } else if (isa<SelectAnyAttr>(NewAttribute) &&
3098 cast<VarDecl>(New)->isInline() &&
3099 !cast<VarDecl>(New)->isInlineSpecified()) {
3100 // Don't warn about applying selectany to implicitly inline variables.
3101 // Older compilers and language modes would require the use of selectany
3102 // to make such variables inline, and it would have no effect if we
3103 // honored it.
3104 ++I;
3105 continue;
3106 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
3107 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3108 // declarations after definitions.
3109 ++I;
3110 continue;
3111 }
3112
3113 S.Diag(NewAttribute->getLocation(),
3114 diag::warn_attribute_precede_definition);
3115 S.Diag(Def->getLocation(), diag::note_previous_definition);
3116 NewAttributes.erase(NewAttributes.begin() + I);
3117 --E;
3118 }
3119}
3120
3121static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3122 const ConstInitAttr *CIAttr,
3123 bool AttrBeforeInit) {
3124 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3125
3126 // Figure out a good way to write this specifier on the old declaration.
3127 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3128 // enough of the attribute list spelling information to extract that without
3129 // heroics.
3130 std::string SuitableSpelling;
3131 if (S.getLangOpts().CPlusPlus20)
3132 SuitableSpelling = std::string(
3133 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
3134 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3135 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3136 InsertLoc, {tok::l_square, tok::l_square,
3137 S.PP.getIdentifierInfo("clang"), tok::coloncolon,
3138 S.PP.getIdentifierInfo("require_constant_initialization"),
3139 tok::r_square, tok::r_square}));
3140 if (SuitableSpelling.empty())
3141 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3142 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
3143 S.PP.getIdentifierInfo("require_constant_initialization"),
3144 tok::r_paren, tok::r_paren}));
3145 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3146 SuitableSpelling = "constinit";
3147 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3148 SuitableSpelling = "[[clang::require_constant_initialization]]";
3149 if (SuitableSpelling.empty())
3150 SuitableSpelling = "__attribute__((require_constant_initialization))";
3151 SuitableSpelling += " ";
3152
3153 if (AttrBeforeInit) {
3154 // extern constinit int a;
3155 // int a = 0; // error (missing 'constinit'), accepted as extension
3156 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", 3156, __extension__ __PRETTY_FUNCTION__
))
;
3157 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3158 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3159 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3160 } else {
3161 // int a = 0;
3162 // constinit extern int a; // error (missing 'constinit')
3163 S.Diag(CIAttr->getLocation(),
3164 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3165 : diag::warn_require_const_init_added_too_late)
3166 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3167 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3168 << CIAttr->isConstinit()
3169 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3170 }
3171}
3172
3173/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
3174void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
3175 AvailabilityMergeKind AMK) {
3176 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3177 UsedAttr *NewAttr = OldAttr->clone(Context);
3178 NewAttr->setInherited(true);
3179 New->addAttr(NewAttr);
3180 }
3181 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3182 RetainAttr *NewAttr = OldAttr->clone(Context);
3183 NewAttr->setInherited(true);
3184 New->addAttr(NewAttr);
3185 }
3186
3187 if (!Old->hasAttrs() && !New->hasAttrs())
3188 return;
3189
3190 // [dcl.constinit]p1:
3191 // If the [constinit] specifier is applied to any declaration of a
3192 // variable, it shall be applied to the initializing declaration.
3193 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3194 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3195 if (bool(OldConstInit) != bool(NewConstInit)) {
3196 const auto *OldVD = cast<VarDecl>(Old);
3197 auto *NewVD = cast<VarDecl>(New);
3198
3199 // Find the initializing declaration. Note that we might not have linked
3200 // the new declaration into the redeclaration chain yet.
3201 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3202 if (!InitDecl &&
3203 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3204 InitDecl = NewVD;
3205
3206 if (InitDecl == NewVD) {
3207 // This is the initializing declaration. If it would inherit 'constinit',
3208 // that's ill-formed. (Note that we do not apply this to the attribute
3209 // form).
3210 if (OldConstInit && OldConstInit->isConstinit())
3211 diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3212 /*AttrBeforeInit=*/true);
3213 } else if (NewConstInit) {
3214 // This is the first time we've been told that this declaration should
3215 // have a constant initializer. If we already saw the initializing
3216 // declaration, this is too late.
3217 if (InitDecl && InitDecl != NewVD) {
3218 diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3219 /*AttrBeforeInit=*/false);
3220 NewVD->dropAttr<ConstInitAttr>();
3221 }
3222 }
3223 }
3224
3225 // Attributes declared post-definition are currently ignored.
3226 checkNewAttributesAfterDef(*this, New, Old);
3227
3228 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3229 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3230 if (!OldA->isEquivalent(NewA)) {
3231 // This redeclaration changes __asm__ label.
3232 Diag(New->getLocation(), diag::err_different_asm_label);
3233 Diag(OldA->getLocation(), diag::note_previous_declaration);
3234 }
3235 } else if (Old->isUsed()) {
3236 // This redeclaration adds an __asm__ label to a declaration that has
3237 // already been ODR-used.
3238 Diag(New->getLocation(), diag::err_late_asm_label_name)
3239 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3240 }
3241 }
3242
3243 // Re-declaration cannot add abi_tag's.
3244 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3245 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3246 for (const auto &NewTag : NewAbiTagAttr->tags()) {
3247 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3248 Diag(NewAbiTagAttr->getLocation(),
3249 diag::err_new_abi_tag_on_redeclaration)
3250 << NewTag;
3251 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3252 }
3253 }
3254 } else {
3255 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3256 Diag(Old->getLocation(), diag::note_previous_declaration);
3257 }
3258 }
3259
3260 // This redeclaration adds a section attribute.
3261 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3262 if (auto *VD = dyn_cast<VarDecl>(New)) {
3263 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3264 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3265 Diag(Old->getLocation(), diag::note_previous_declaration);
3266 }
3267 }
3268 }
3269
3270 // Redeclaration adds code-seg attribute.
3271 const auto *NewCSA = New->getAttr<CodeSegAttr>();
3272 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3273 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3274 Diag(New->getLocation(), diag::warn_mismatched_section)
3275 << 0 /*codeseg*/;
3276 Diag(Old->getLocation(), diag::note_previous_declaration);
3277 }
3278
3279 if (!Old->hasAttrs())
3280 return;
3281
3282 bool foundAny = New->hasAttrs();
3283
3284 // Ensure that any moving of objects within the allocated map is done before
3285 // we process them.
3286 if (!foundAny) New->setAttrs(AttrVec());
3287
3288 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3289 // Ignore deprecated/unavailable/availability attributes if requested.
3290 AvailabilityMergeKind LocalAMK = AMK_None;
3291 if (isa<DeprecatedAttr>(I) ||
3292 isa<UnavailableAttr>(I) ||
3293 isa<AvailabilityAttr>(I)) {
3294 switch (AMK) {
3295 case AMK_None:
3296 continue;
3297
3298 case AMK_Redeclaration:
3299 case AMK_Override:
3300 case AMK_ProtocolImplementation:
3301 case AMK_OptionalProtocolImplementation:
3302 LocalAMK = AMK;
3303 break;
3304 }
3305 }
3306
3307 // Already handled.
3308 if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3309 continue;
3310
3311 if (mergeDeclAttribute(*this, New, I, LocalAMK))
3312 foundAny = true;
3313 }
3314
3315 if (mergeAlignedAttrs(*this, New, Old))
3316 foundAny = true;
3317
3318 if (!foundAny) New->dropAttrs();
3319}
3320
3321/// mergeParamDeclAttributes - Copy attributes from the old parameter
3322/// to the new one.
3323static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3324 const ParmVarDecl *oldDecl,
3325 Sema &S) {
3326 // C++11 [dcl.attr.depend]p2:
3327 // The first declaration of a function shall specify the
3328 // carries_dependency attribute for its declarator-id if any declaration
3329 // of the function specifies the carries_dependency attribute.
3330 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3331 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3332 S.Diag(CDA->getLocation(),
3333 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3334 // Find the first declaration of the parameter.
3335 // FIXME: Should we build redeclaration chains for function parameters?
3336 const FunctionDecl *FirstFD =
3337 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3338 const ParmVarDecl *FirstVD =
3339 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3340 S.Diag(FirstVD->getLocation(),
3341 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3342 }
3343
3344 if (!oldDecl->hasAttrs())
3345 return;
3346
3347 bool foundAny = newDecl->hasAttrs();
3348
3349 // Ensure that any moving of objects within the allocated map is
3350 // done before we process them.
3351 if (!foundAny) newDecl->setAttrs(AttrVec());
3352
3353 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3354 if (!DeclHasAttr(newDecl, I)) {
3355 InheritableAttr *newAttr =
3356 cast<InheritableParamAttr>(I->clone(S.Context));
3357 newAttr->setInherited(true);
3358 newDecl->addAttr(newAttr);
3359 foundAny = true;
3360 }
3361 }
3362
3363 if (!foundAny) newDecl->dropAttrs();
3364}
3365
3366static bool EquivalentArrayTypes(QualType Old, QualType New,
3367 const ASTContext &Ctx) {
3368
3369 auto NoSizeInfo = [&Ctx](QualType Ty) {
3370 if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3371 return true;
3372 if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))
3373 return VAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star;
3374 return false;
3375 };
3376
3377 // `type[]` is equivalent to `type *` and `type[*]`.
3378 if (NoSizeInfo(Old) && NoSizeInfo(New))
3379 return true;
3380
3381 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3382 if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3383 const auto *OldVAT = Ctx.getAsVariableArrayType(Old);
3384 const auto *NewVAT = Ctx.getAsVariableArrayType(New);
3385 if ((OldVAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star) ^
3386 (NewVAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star))
3387 return false;
3388 return true;
3389 }
3390
3391 // Only compare size, ignore Size modifiers and CVR.
3392 if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3393 return Ctx.getAsConstantArrayType(Old)->getSize() ==
3394 Ctx.getAsConstantArrayType(New)->getSize();
3395 }
3396
3397 // Don't try to compare dependent sized array
3398 if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) {
3399 return true;
3400 }
3401
3402 return Old == New;
3403}
3404
3405static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3406 const ParmVarDecl *OldParam,
3407 Sema &S) {
3408 if (auto Oldnullability = OldParam->getType()->getNullability()) {
3409 if (auto Newnullability = NewParam->getType()->getNullability()) {
3410 if (*Oldnullability != *Newnullability) {
3411 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3412 << DiagNullabilityKind(
3413 *Newnullability,
3414 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3415 != 0))
3416 << DiagNullabilityKind(
3417 *Oldnullability,
3418 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3419 != 0));
3420 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3421 }
3422 } else {
3423 QualType NewT = NewParam->getType();
3424 NewT = S.Context.getAttributedType(
3425 AttributedType::getNullabilityAttrKind(*Oldnullability),
3426 NewT, NewT);
3427 NewParam->setType(NewT);
3428 }
3429 }
3430 const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
3431 const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
3432 if (OldParamDT && NewParamDT &&
3433 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3434 QualType OldParamOT = OldParamDT->getOriginalType();
3435 QualType NewParamOT = NewParamDT->getOriginalType();
3436 if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) {
3437 S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
3438 << NewParam << NewParamOT;
3439 S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
3440 << OldParamOT;
3441 }
3442 }
3443}
3444
3445namespace {
3446
3447/// Used in MergeFunctionDecl to keep track of function parameters in
3448/// C.
3449struct GNUCompatibleParamWarning {
3450 ParmVarDecl *OldParm;
3451 ParmVarDecl *NewParm;
3452 QualType PromotedType;
3453};
3454
3455} // end anonymous namespace
3456
3457// Determine whether the previous declaration was a definition, implicit
3458// declaration, or a declaration.
3459template <typename T>
3460static std::pair<diag::kind, SourceLocation>
3461getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3462 diag::kind PrevDiag;
3463 SourceLocation OldLocation = Old->getLocation();
3464 if (Old->isThisDeclarationADefinition())
3465 PrevDiag = diag::note_previous_definition;
3466 else if (Old->isImplicit()) {
3467 PrevDiag = diag::note_previous_implicit_declaration;
3468 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3469 if (FD->getBuiltinID())
3470 PrevDiag = diag::note_previous_builtin_declaration;
3471 }
3472 if (OldLocation.isInvalid())
3473 OldLocation = New->getLocation();
3474 } else
3475 PrevDiag = diag::note_previous_declaration;
3476 return std::make_pair(PrevDiag, OldLocation);
3477}
3478
3479/// canRedefineFunction - checks if a function can be redefined. Currently,
3480/// only extern inline functions can be redefined, and even then only in
3481/// GNU89 mode.
3482static bool canRedefineFunction(const FunctionDecl *FD,
3483 const LangOptions& LangOpts) {
3484 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3485 !LangOpts.CPlusPlus &&
3486 FD->isInlineSpecified() &&
3487 FD->getStorageClass() == SC_Extern);
3488}
3489
3490const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3491 const AttributedType *AT = T->getAs<AttributedType>();
3492 while (AT && !AT->isCallingConv())
3493 AT = AT->getModifiedType()->getAs<AttributedType>();
3494 return AT;
3495}
3496
3497template <typename T>
3498static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3499 const DeclContext *DC = Old->getDeclContext();
3500 if (DC->isRecord())
3501 return false;
3502
3503 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3504 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3505 return true;
3506 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3507 return true;
3508 return false;
3509}
3510
3511template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3512static bool isExternC(VarTemplateDecl *) { return false; }
3513static bool isExternC(FunctionTemplateDecl *) { return false; }
3514
3515/// Check whether a redeclaration of an entity introduced by a
3516/// using-declaration is valid, given that we know it's not an overload
3517/// (nor a hidden tag declaration).
3518template<typename ExpectedDecl>
3519static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3520 ExpectedDecl *New) {
3521 // C++11 [basic.scope.declarative]p4:
3522 // Given a set of declarations in a single declarative region, each of
3523 // which specifies the same unqualified name,
3524 // -- they shall all refer to the same entity, or all refer to functions
3525 // and function templates; or
3526 // -- exactly one declaration shall declare a class name or enumeration
3527 // name that is not a typedef name and the other declarations shall all
3528 // refer to the same variable or enumerator, or all refer to functions
3529 // and function templates; in this case the class name or enumeration
3530 // name is hidden (3.3.10).
3531
3532 // C++11 [namespace.udecl]p14:
3533 // If a function declaration in namespace scope or block scope has the
3534 // same name and the same parameter-type-list as a function introduced
3535 // by a using-declaration, and the declarations do not declare the same
3536 // function, the program is ill-formed.
3537
3538 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3539 if (Old &&
3540 !Old->getDeclContext()->getRedeclContext()->Equals(
3541 New->getDeclContext()->getRedeclContext()) &&
3542 !(isExternC(Old) && isExternC(New)))
3543 Old = nullptr;
3544
3545 if (!Old) {
3546 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3547 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3548 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3549 return true;
3550 }
3551 return false;
3552}
3553
3554static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3555 const FunctionDecl *B) {
3556 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", 3556, __extension__ __PRETTY_FUNCTION__
))
;
3557
3558 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3559 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3560 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3561 if (AttrA == AttrB)
3562 return true;
3563 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3564 AttrA->isDynamic() == AttrB->isDynamic();
3565 };
3566
3567 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3568}
3569
3570/// If necessary, adjust the semantic declaration context for a qualified
3571/// declaration to name the correct inline namespace within the qualifier.
3572static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3573 DeclaratorDecl *OldD) {
3574 // The only case where we need to update the DeclContext is when
3575 // redeclaration lookup for a qualified name finds a declaration
3576 // in an inline namespace within the context named by the qualifier:
3577 //
3578 // inline namespace N { int f(); }
3579 // int ::f(); // Sema DC needs adjusting from :: to N::.
3580 //
3581 // For unqualified declarations, the semantic context *can* change
3582 // along the redeclaration chain (for local extern declarations,
3583 // extern "C" declarations, and friend declarations in particular).
3584 if (!NewD->getQualifier())
3585 return;
3586
3587 // NewD is probably already in the right context.
3588 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3589 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3590 if (NamedDC->Equals(SemaDC))
3591 return;
3592
3593 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", 3595, __extension__ __PRETTY_FUNCTION__
))
3594 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", 3595, __extension__ __PRETTY_FUNCTION__
))
3595 "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", 3595, __extension__ __PRETTY_FUNCTION__
))
;
3596
3597 auto *LexDC = NewD->getLexicalDeclContext();
3598 auto FixSemaDC = [=](NamedDecl *D) {
3599 if (!D)
3600 return;
3601 D->setDeclContext(SemaDC);
3602 D->setLexicalDeclContext(LexDC);
3603 };
3604
3605 FixSemaDC(NewD);
3606 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3607 FixSemaDC(FD->getDescribedFunctionTemplate());
3608 else if (auto *VD = dyn_cast<VarDecl>(NewD))
3609 FixSemaDC(VD->getDescribedVarTemplate());
3610}
3611
3612/// MergeFunctionDecl - We just parsed a function 'New' from
3613/// declarator D which has the same name and scope as a previous
3614/// declaration 'Old'. Figure out how to resolve this situation,
3615/// merging decls or emitting diagnostics as appropriate.
3616///
3617/// In C++, New and Old must be declarations that are not
3618/// overloaded. Use IsOverload to determine whether New and Old are
3619/// overloaded, and to select the Old declaration that New should be
3620/// merged with.
3621///
3622/// Returns true if there was an error, false otherwise.
3623bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S,
3624 bool MergeTypeWithOld, bool NewDeclIsDefn) {
3625 // Verify the old decl was also a function.
3626 FunctionDecl *Old = OldD->getAsFunction();
3627 if (!Old) {
3628 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3629 if (New->getFriendObjectKind()) {
3630 Diag(New->getLocation(), diag::err_using_decl_friend);
3631 Diag(Shadow->getTargetDecl()->getLocation(),
3632 diag::note_using_decl_target);
3633 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3634 << 0;
3635 return true;
3636 }
3637
3638 // Check whether the two declarations might declare the same function or
3639 // function template.
3640 if (FunctionTemplateDecl *NewTemplate =
3641 New->getDescribedFunctionTemplate()) {
3642 if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3643 NewTemplate))
3644 return true;
3645 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3646 ->getAsFunction();
3647 } else {
3648 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3649 return true;
3650 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3651 }
3652 } else {
3653 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3654 << New->getDeclName();
3655 notePreviousDefinition(OldD, New->getLocation());
3656 return true;
3657 }
3658 }
3659
3660 // If the old declaration was found in an inline namespace and the new
3661 // declaration was qualified, update the DeclContext to match.
3662 adjustDeclContextForDeclaratorDecl(New, Old);
3663
3664 // If the old declaration is invalid, just give up here.
3665 if (Old->isInvalidDecl())
3666 return true;
3667
3668 // Disallow redeclaration of some builtins.
3669 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3670 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3671 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3672 << Old << Old->getType();
3673 return true;
3674 }
3675
3676 diag::kind PrevDiag;
3677 SourceLocation OldLocation;
3678 std::tie(PrevDiag, OldLocation) =
3679 getNoteDiagForInvalidRedeclaration(Old, New);
3680
3681 // Don't complain about this if we're in GNU89 mode and the old function
3682 // is an extern inline function.
3683 // Don't complain about specializations. They are not supposed to have
3684 // storage classes.
3685 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3686 New->getStorageClass() == SC_Static &&
3687 Old->hasExternalFormalLinkage() &&
3688 !New->getTemplateSpecializationInfo() &&
3689 !canRedefineFunction(Old, getLangOpts())) {
3690 if (getLangOpts().MicrosoftExt) {
3691 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3692 Diag(OldLocation, PrevDiag);
3693 } else {
3694 Diag(New->getLocation(), diag::err_static_non_static) << New;
3695 Diag(OldLocation, PrevDiag);
3696 return true;
3697 }
3698 }
3699
3700 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3701 if (!Old->hasAttr<InternalLinkageAttr>()) {
3702 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3703 << ILA;
3704 Diag(Old->getLocation(), diag::note_previous_declaration);
3705 New->dropAttr<InternalLinkageAttr>();
3706 }
3707
3708 if (auto *EA = New->getAttr<ErrorAttr>()) {
3709 if (!Old->hasAttr<ErrorAttr>()) {
3710 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3711 Diag(Old->getLocation(), diag::note_previous_declaration);
3712 New->dropAttr<ErrorAttr>();
3713 }
3714 }
3715
3716 if (CheckRedeclarationInModule(New, Old))
3717 return true;
3718
3719 if (!getLangOpts().CPlusPlus) {
3720 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3721 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3722 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3723 << New << OldOvl;
3724
3725 // Try our best to find a decl that actually has the overloadable
3726 // attribute for the note. In most cases (e.g. programs with only one
3727 // broken declaration/definition), this won't matter.
3728 //
3729 // FIXME: We could do this if we juggled some extra state in
3730 // OverloadableAttr, rather than just removing it.
3731 const Decl *DiagOld = Old;
3732 if (OldOvl) {
3733 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3734 const auto *A = D->getAttr<OverloadableAttr>();
3735 return A && !A->isImplicit();
3736 });
3737 // If we've implicitly added *all* of the overloadable attrs to this
3738 // chain, emitting a "previous redecl" note is pointless.
3739 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3740 }
3741
3742 if (DiagOld)
3743 Diag(DiagOld->getLocation(),
3744 diag::note_attribute_overloadable_prev_overload)
3745 << OldOvl;
3746
3747 if (OldOvl)
3748 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3749 else
3750 New->dropAttr<OverloadableAttr>();
3751 }
3752 }
3753
3754 // If a function is first declared with a calling convention, but is later
3755 // declared or defined without one, all following decls assume the calling
3756 // convention of the first.
3757 //
3758 // It's OK if a function is first declared without a calling convention,
3759 // but is later declared or defined with the default calling convention.
3760 //
3761 // To test if either decl has an explicit calling convention, we look for
3762 // AttributedType sugar nodes on the type as written. If they are missing or
3763 // were canonicalized away, we assume the calling convention was implicit.
3764 //
3765 // Note also that we DO NOT return at this point, because we still have
3766 // other tests to run.
3767 QualType OldQType = Context.getCanonicalType(Old->getType());
3768 QualType NewQType = Context.getCanonicalType(New->getType());
3769 const FunctionType *OldType = cast<FunctionType>(OldQType);
3770 const FunctionType *NewType = cast<FunctionType>(NewQType);
3771 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3772 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3773 bool RequiresAdjustment = false;
3774
3775 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3776 FunctionDecl *First = Old->getFirstDecl();
3777 const FunctionType *FT =
3778 First->getType().getCanonicalType()->castAs<FunctionType>();
3779 FunctionType::ExtInfo FI = FT->getExtInfo();
3780 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3781 if (!NewCCExplicit) {
3782 // Inherit the CC from the previous declaration if it was specified
3783 // there but not here.
3784 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3785 RequiresAdjustment = true;
3786 } else if (Old->getBuiltinID()) {
3787 // Builtin attribute isn't propagated to the new one yet at this point,
3788 // so we check if the old one is a builtin.
3789
3790 // Calling Conventions on a Builtin aren't really useful and setting a
3791 // default calling convention and cdecl'ing some builtin redeclarations is
3792 // common, so warn and ignore the calling convention on the redeclaration.
3793 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3794 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3795 << (int)CallingConventionIgnoredReason::BuiltinFunction;
3796 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3797 RequiresAdjustment = true;
3798 } else {
3799 // Calling conventions aren't compatible, so complain.
3800 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3801 Diag(New->getLocation(), diag::err_cconv_change)
3802 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3803 << !FirstCCExplicit
3804 << (!FirstCCExplicit ? "" :
3805 FunctionType::getNameForCallConv(FI.getCC()));
3806
3807 // Put the note on the first decl, since it is the one that matters.
3808 Diag(First->getLocation(), diag::note_previous_declaration);
3809 return true;
3810 }
3811 }
3812
3813 // FIXME: diagnose the other way around?
3814 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3815 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3816 RequiresAdjustment = true;
3817 }
3818
3819 // Merge regparm attribute.
3820 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3821 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3822 if (NewTypeInfo.getHasRegParm()) {
3823 Diag(New->getLocation(), diag::err_regparm_mismatch)
3824 << NewType->getRegParmType()
3825 << OldType->getRegParmType();
3826 Diag(OldLocation, diag::note_previous_declaration);
3827 return true;
3828 }
3829
3830 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3831 RequiresAdjustment = true;
3832 }
3833
3834 // Merge ns_returns_retained attribute.
3835 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3836 if (NewTypeInfo.getProducesResult()) {
3837 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3838 << "'ns_returns_retained'";
3839 Diag(OldLocation, diag::note_previous_declaration);
3840 return true;
3841 }
3842
3843 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3844 RequiresAdjustment = true;
3845 }
3846
3847 if (OldTypeInfo.getNoCallerSavedRegs() !=
3848 NewTypeInfo.getNoCallerSavedRegs()) {
3849 if (NewTypeInfo.getNoCallerSavedRegs()) {
3850 AnyX86NoCallerSavedRegistersAttr *Attr =
3851 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3852 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3853 Diag(OldLocation, diag::note_previous_declaration);
3854 return true;
3855 }
3856
3857 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3858 RequiresAdjustment = true;
3859 }
3860
3861 if (RequiresAdjustment) {
3862 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3863 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3864 New->setType(QualType(AdjustedType, 0));
3865 NewQType = Context.getCanonicalType(New->getType());
3866 }
3867
3868 // If this redeclaration makes the function inline, we may need to add it to
3869 // UndefinedButUsed.
3870 if (!Old->isInlined() && New->isInlined() &&
3871 !New->hasAttr<GNUInlineAttr>() &&
3872 !getLangOpts().GNUInline &&
3873 Old->isUsed(false) &&
3874 !Old->isDefined() && !New->isThisDeclarationADefinition())
3875 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3876 SourceLocation()));
3877
3878 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3879 // about it.
3880 if (New->hasAttr<GNUInlineAttr>() &&
3881 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3882 UndefinedButUsed.erase(Old->getCanonicalDecl());
3883 }
3884
3885 // If pass_object_size params don't match up perfectly, this isn't a valid
3886 // redeclaration.
3887 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3888 !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3889 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3890 << New->getDeclName();
3891 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3892 return true;
3893 }
3894
3895 if (getLangOpts().CPlusPlus) {
3896 // C++1z [over.load]p2
3897 // Certain function declarations cannot be overloaded:
3898 // -- Function declarations that differ only in the return type,
3899 // the exception specification, or both cannot be overloaded.
3900
3901 // Check the exception specifications match. This may recompute the type of
3902 // both Old and New if it resolved exception specifications, so grab the
3903 // types again after this. Because this updates the type, we do this before
3904 // any of the other checks below, which may update the "de facto" NewQType
3905 // but do not necessarily update the type of New.
3906 if (CheckEquivalentExceptionSpec(Old, New))
3907 return true;
3908 OldQType = Context.getCanonicalType(Old->getType());
3909 NewQType = Context.getCanonicalType(New->getType());
3910
3911 // Go back to the type source info to compare the declared return types,
3912 // per C++1y [dcl.type.auto]p13:
3913 // Redeclarations or specializations of a function or function template
3914 // with a declared return type that uses a placeholder type shall also
3915 // use that placeholder, not a deduced type.
3916 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3917 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3918 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3919 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3920 OldDeclaredReturnType)) {
3921 QualType ResQT;
3922 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3923 OldDeclaredReturnType->isObjCObjectPointerType())
3924 // FIXME: This does the wrong thing for a deduced return type.
3925 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3926 if (ResQT.isNull()) {
3927 if (New->isCXXClassMember() && New->isOutOfLine())
3928 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3929 << New << New->getReturnTypeSourceRange();
3930 else
3931 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3932 << New->getReturnTypeSourceRange();
3933 Diag(OldLocation, PrevDiag) << Old << Old->getType()
3934 << Old->getReturnTypeSourceRange();
3935 return true;
3936 }
3937 else
3938 NewQType = ResQT;
3939 }
3940
3941 QualType OldReturnType = OldType->getReturnType();
3942 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3943 if (OldReturnType != NewReturnType) {
3944 // If this function has a deduced return type and has already been
3945 // defined, copy the deduced value from the old declaration.
3946 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3947 if (OldAT && OldAT->isDeduced()) {
3948 QualType DT = OldAT->getDeducedType();
3949 if (DT.isNull()) {
3950 New->setType(SubstAutoTypeDependent(New->getType()));
3951 NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
3952 } else {
3953 New->setType(SubstAutoType(New->getType(), DT));
3954 NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
3955 }
3956 }
3957 }
3958
3959 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3960 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3961 if (OldMethod && NewMethod) {
3962 // Preserve triviality.
3963 NewMethod->setTrivial(OldMethod->isTrivial());
3964
3965 // MSVC allows explicit template specialization at class scope:
3966 // 2 CXXMethodDecls referring to the same function will be injected.
3967 // We don't want a redeclaration error.
3968 bool IsClassScopeExplicitSpecialization =
3969 OldMethod->isFunctionTemplateSpecialization() &&
3970 NewMethod->isFunctionTemplateSpecialization();
3971 bool isFriend = NewMethod->getFriendObjectKind();
3972
3973 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3974 !IsClassScopeExplicitSpecialization) {
3975 // -- Member function declarations with the same name and the
3976 // same parameter types cannot be overloaded if any of them
3977 // is a static member function declaration.
3978 if (OldMethod->isStatic() != NewMethod->isStatic()) {
3979 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3980 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3981 return true;
3982 }
3983
3984 // C++ [class.mem]p1:
3985 // [...] A member shall not be declared twice in the
3986 // member-specification, except that a nested class or member
3987 // class template can be declared and then later defined.
3988 if (!inTemplateInstantiation()) {
3989 unsigned NewDiag;
3990 if (isa<CXXConstructorDecl>(OldMethod))
3991 NewDiag = diag::err_constructor_redeclared;
3992 else if (isa<CXXDestructorDecl>(NewMethod))
3993 NewDiag = diag::err_destructor_redeclared;
3994 else if (isa<CXXConversionDecl>(NewMethod))
3995 NewDiag = diag::err_conv_function_redeclared;
3996 else
3997 NewDiag = diag::err_member_redeclared;
3998
3999 Diag(New->getLocation(), NewDiag);
4000 } else {
4001 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
4002 << New << New->getType();
4003 }
4004 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4005 return true;
4006
4007 // Complain if this is an explicit declaration of a special
4008 // member that was initially declared implicitly.
4009 //
4010 // As an exception, it's okay to befriend such methods in order
4011 // to permit the implicit constructor/destructor/operator calls.
4012 } else if (OldMethod->isImplicit()) {
4013 if (isFriend) {
4014 NewMethod->setImplicit();
4015 } else {
4016 Diag(NewMethod->getLocation(),
4017 diag::err_definition_of_implicitly_declared_member)
4018 << New << getSpecialMember(OldMethod);
4019 return true;
4020 }
4021 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
4022 Diag(NewMethod->getLocation(),
4023 diag::err_definition_of_explicitly_defaulted_member)
4024 << getSpecialMember(OldMethod);
4025 return true;
4026 }
4027 }
4028
4029 // C++11 [dcl.attr.noreturn]p1:
4030 // The first declaration of a function shall specify the noreturn
4031 // attribute if any declaration of that function specifies the noreturn
4032 // attribute.
4033 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4034 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4035 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
4036 << NRA;
4037 Diag(Old->getLocation(), diag::note_previous_declaration);
4038 }
4039
4040 // C++11 [dcl.attr.depend]p2:
4041 // The first declaration of a function shall specify the
4042 // carries_dependency attribute for its declarator-id if any declaration
4043 // of the function specifies the carries_dependency attribute.
4044 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
4045 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
4046 Diag(CDA->getLocation(),
4047 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
4048 Diag(Old->getFirstDecl()->getLocation(),
4049 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
4050 }
4051
4052 // (C++98 8.3.5p3):
4053 // All declarations for a function shall agree exactly in both the
4054 // return type and the parameter-type-list.
4055 // We also want to respect all the extended bits except noreturn.
4056
4057 // noreturn should now match unless the old type info didn't have it.
4058 QualType OldQTypeForComparison = OldQType;
4059 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4060 auto *OldType = OldQType->castAs<FunctionProtoType>();
4061 const FunctionType *OldTypeForComparison
4062 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
4063 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4064 assert(OldQTypeForComparison.isCanonical())(static_cast <bool> (OldQTypeForComparison.isCanonical(
)) ? void (0) : __assert_fail ("OldQTypeForComparison.isCanonical()"
, "clang/lib/Sema/SemaDecl.cpp", 4064, __extension__ __PRETTY_FUNCTION__
))
;
4065 }
4066
4067 if (haveIncompatibleLanguageLinkages(Old, New)) {
4068 // As a special case, retain the language linkage from previous
4069 // declarations of a friend function as an extension.
4070 //
4071 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4072 // and is useful because there's otherwise no way to specify language
4073 // linkage within class scope.
4074 //
4075 // Check cautiously as the friend object kind isn't yet complete.
4076 if (New->getFriendObjectKind() != Decl::FOK_None) {
4077 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
4078 Diag(OldLocation, PrevDiag);
4079 } else {
4080 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4081 Diag(OldLocation, PrevDiag);
4082 return true;
4083 }
4084 }
4085
4086 // If the function types are compatible, merge the declarations. Ignore the
4087 // exception specifier because it was already checked above in
4088 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4089 // about incompatible types under -fms-compatibility.
4090 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
4091 NewQType))
4092 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4093
4094 // If the types are imprecise (due to dependent constructs in friends or
4095 // local extern declarations), it's OK if they differ. We'll check again
4096 // during instantiation.
4097 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
4098 return false;
4099
4100 // Fall through for conflicting redeclarations and redefinitions.
4101 }
4102
4103 // C: Function types need to be compatible, not identical. This handles
4104 // duplicate function decls like "void f(int); void f(enum X);" properly.
4105 if (!getLangOpts().CPlusPlus) {
4106 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4107 // type is specified by a function definition that contains a (possibly
4108 // empty) identifier list, both shall agree in the number of parameters
4109 // and the type of each parameter shall be compatible with the type that
4110 // results from the application of default argument promotions to the
4111 // type of the corresponding identifier. ...
4112 // This cannot be handled by ASTContext::typesAreCompatible() because that
4113 // doesn't know whether the function type is for a definition or not when
4114 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4115 // we need to cover here is that the number of arguments agree as the
4116 // default argument promotion rules were already checked by
4117 // ASTContext::typesAreCompatible().
4118 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4119 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4120 if (Old->hasInheritedPrototype())
4121 Old = Old->getCanonicalDecl();
4122 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4123 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
4124 return true;
4125 }
4126
4127 // If we are merging two functions where only one of them has a prototype,
4128 // we may have enough information to decide to issue a diagnostic that the
4129 // function without a protoype will change behavior in C2x. This handles
4130 // cases like:
4131 // void i(); void i(int j);
4132 // void i(int j); void i();
4133 // void i(); void i(int j) {}
4134 // See ActOnFinishFunctionBody() for other cases of the behavior change
4135 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4136 // type without a prototype.
4137 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4138 !New->isImplicit() && !Old->isImplicit()) {
4139 const FunctionDecl *WithProto, *WithoutProto;
4140 if (New->hasWrittenPrototype()) {
4141 WithProto = New;
4142 WithoutProto = Old;
4143 } else {
4144 WithProto = Old;
4145 WithoutProto = New;
4146 }
4147
4148 if (WithProto->getNumParams() != 0) {
4149 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4150 // The one without the prototype will be changing behavior in C2x, so
4151 // warn about that one so long as it's a user-visible declaration.
4152 bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4153 if (WithoutProto == New)
4154 IsWithoutProtoADef = NewDeclIsDefn;
4155 else
4156 IsWithProtoADef = NewDeclIsDefn;
4157 Diag(WithoutProto->getLocation(),
4158 diag::warn_non_prototype_changes_behavior)
4159 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4160 << (WithoutProto == Old) << IsWithProtoADef;
4161
4162 // The reason the one without the prototype will be changing behavior
4163 // is because of the one with the prototype, so note that so long as
4164 // it's a user-visible declaration. There is one exception to this:
4165 // when the new declaration is a definition without a prototype, the
4166 // old declaration with a prototype is not the cause of the issue,
4167 // and that does not need to be noted because the one with a
4168 // prototype will not change behavior in C2x.
4169 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4170 !IsWithoutProtoADef)
4171 Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
4172 }
4173 }
4174 }
4175
4176 if (Context.typesAreCompatible(OldQType, NewQType)) {
4177 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4178 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4179 const FunctionProtoType *OldProto = nullptr;
4180 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
4181 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
4182 // The old declaration provided a function prototype, but the
4183 // new declaration does not. Merge in the prototype.
4184 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", 4184, __extension__ __PRETTY_FUNCTION__
))
;
4185 NewQType = Context.getFunctionType(NewFuncType->getReturnType(),
4186 OldProto->getParamTypes(),
4187 OldProto->getExtProtoInfo());
4188 New->setType(NewQType);
4189 New->setHasInheritedPrototype();
4190
4191 // Synthesize parameters with the same types.
4192 SmallVector<ParmVarDecl *, 16> Params;
4193 for (const auto &ParamType : OldProto->param_types()) {
4194 ParmVarDecl *Param = ParmVarDecl::Create(
4195 Context, New, SourceLocation(), SourceLocation(), nullptr,
4196 ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4197 Param->setScopeInfo(0, Params.size());
4198 Param->setImplicit();
4199 Params.push_back(Param);
4200 }
4201
4202 New->setParams(Params);
4203 }
4204
4205 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4206 }
4207 }
4208
4209 // Check if the function types are compatible when pointer size address
4210 // spaces are ignored.
4211 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4212 return false;
4213
4214 // GNU C permits a K&R definition to follow a prototype declaration
4215 // if the declared types of the parameters in the K&R definition
4216 // match the types in the prototype declaration, even when the
4217 // promoted types of the parameters from the K&R definition differ
4218 // from the types in the prototype. GCC then keeps the types from
4219 // the prototype.
4220 //
4221 // If a variadic prototype is followed by a non-variadic K&R definition,
4222 // the K&R definition becomes variadic. This is sort of an edge case, but
4223 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4224 // C99 6.9.1p8.
4225 if (!getLangOpts().CPlusPlus &&
4226 Old->hasPrototype() && !New->hasPrototype() &&
4227 New->getType()->getAs<FunctionProtoType>() &&
4228 Old->getNumParams() == New->getNumParams()) {
4229 SmallVector<QualType, 16> ArgTypes;
4230 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
4231 const FunctionProtoType *OldProto
4232 = Old->getType()->getAs<FunctionProtoType>();
4233 const FunctionProtoType *NewProto
4234 = New->getType()->getAs<FunctionProtoType>();
4235
4236 // Determine whether this is the GNU C extension.
4237 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4238 NewProto->getReturnType());
4239 bool LooseCompatible = !MergedReturn.isNull();
4240 for (unsigned Idx = 0, End = Old->getNumParams();
4241 LooseCompatible && Idx != End; ++Idx) {
4242 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4243 ParmVarDecl *NewParm = New->getParamDecl(Idx);
4244 if (Context.typesAreCompatible(OldParm->getType(),
4245 NewProto->getParamType(Idx))) {
4246 ArgTypes.push_back(NewParm->getType());
4247 } else if (Context.typesAreCompatible(OldParm->getType(),
4248 NewParm->getType(),
4249 /*CompareUnqualified=*/true)) {
4250 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4251 NewProto->getParamType(Idx) };
4252 Warnings.push_back(Warn);
4253 ArgTypes.push_back(NewParm->getType());
4254 } else
4255 LooseCompatible = false;
4256 }
4257
4258 if (LooseCompatible) {
4259 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4260 Diag(Warnings[Warn].NewParm->getLocation(),
4261 diag::ext_param_promoted_not_compatible_with_prototype)
4262 << Warnings[Warn].PromotedType
4263 << Warnings[Warn].OldParm->getType();
4264 if (Warnings[Warn].OldParm->getLocation().isValid())
4265 Diag(Warnings[Warn].OldParm->getLocation(),
4266 diag::note_previous_declaration);
4267 }
4268
4269 if (MergeTypeWithOld)
4270 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4271 OldProto->getExtProtoInfo()));
4272 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4273 }
4274
4275 // Fall through to diagnose conflicting types.
4276 }
4277
4278 // A function that has already been declared has been redeclared or
4279 // defined with a different type; show an appropriate diagnostic.
4280
4281 // If the previous declaration was an implicitly-generated builtin
4282 // declaration, then at the very least we should use a specialized note.
4283 unsigned BuiltinID;
4284 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4285 // If it's actually a library-defined builtin function like 'malloc'
4286 // or 'printf', just warn about the incompatible redeclaration.
4287 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4288 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4289 Diag(OldLocation, diag::note_previous_builtin_declaration)
4290 << Old << Old->getType();
4291 return false;
4292 }
4293
4294 PrevDiag = diag::note_previous_builtin_declaration;
4295 }
4296
4297 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4298 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4299 return true;
4300}
4301
4302/// Completes the merge of two function declarations that are
4303/// known to be compatible.
4304///
4305/// This routine handles the merging of attributes and other
4306/// properties of function declarations from the old declaration to
4307/// the new declaration, once we know that New is in fact a
4308/// redeclaration of Old.
4309///
4310/// \returns false
4311bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4312 Scope *S, bool MergeTypeWithOld) {
4313 // Merge the attributes
4314 mergeDeclAttributes(New, Old);
4315
4316 // Merge "pure" flag.
4317 if (Old->isPure())
4318 New->setPure();
4319
4320 // Merge "used" flag.
4321 if (Old->getMostRecentDecl()->isUsed(false))
4322 New->setIsUsed();
4323
4324 // Merge attributes from the parameters. These can mismatch with K&R
4325 // declarations.
4326 if (New->getNumParams() == Old->getNumParams())
4327 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4328 ParmVarDecl *NewParam = New->getParamDecl(i);
4329 ParmVarDecl *OldParam = Old->getParamDecl(i);
4330 mergeParamDeclAttributes(NewParam, OldParam, *this);
4331 mergeParamDeclTypes(NewParam, OldParam, *this);
4332 }
4333
4334 if (getLangOpts().CPlusPlus)
4335 return MergeCXXFunctionDecl(New, Old, S);
4336
4337 // Merge the function types so the we get the composite types for the return
4338 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4339 // was visible.
4340 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4341 if (!Merged.isNull() && MergeTypeWithOld)
4342 New->setType(Merged);
4343
4344 return false;
4345}
4346
4347void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
4348 ObjCMethodDecl *oldMethod) {
4349 // Merge the attributes, including deprecated/unavailable
4350 AvailabilityMergeKind MergeKind =
4351 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
4352 ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
4353 : AMK_ProtocolImplementation)
4354 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
4355 : AMK_Override;
4356
4357 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4358
4359 // Merge attributes from the parameters.
4360 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
4361 oe = oldMethod->param_end();
4362 for (ObjCMethodDecl::param_iterator
4363 ni = newMethod->param_begin(), ne = newMethod->param_end();
4364 ni != ne && oi != oe; ++ni, ++oi)
4365 mergeParamDeclAttributes(*ni, *oi, *this);
4366
4367 CheckObjCMethodOverride(newMethod, oldMethod);
4368}
4369
4370static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
4371 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", 4371, __extension__ __PRETTY_FUNCTION__
))
;
4372
4373 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
4374 ? diag::err_redefinition_different_type
4375 : diag::err_redeclaration_different_type)
4376 << New->getDeclName() << New->getType() << Old->getType();
4377
4378 diag::kind PrevDiag;
4379 SourceLocation OldLocation;
4380 std::tie(PrevDiag, OldLocation)
4381 = getNoteDiagForInvalidRedeclaration(Old, New);
4382 S.Diag(OldLocation, PrevDiag);
4383 New->setInvalidDecl();
4384}
4385
4386/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4387/// scope as a previous declaration 'Old'. Figure out how to merge their types,
4388/// emitting diagnostics as appropriate.
4389///
4390/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
4391/// to here in AddInitializerToDecl. We can't check them before the initializer
4392/// is attached.
4393void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
4394 bool MergeTypeWithOld) {
4395 if (New->isInvalidDecl() || Old->isInvalidDecl())
4396 return;
4397
4398 QualType MergedT;
4399 if (getLangOpts().CPlusPlus) {
4400 if (New->getType()->isUndeducedType()) {
4401 // We don't know what the new type is until the initializer is attached.
4402 return;
4403 } else if (Context.hasSameType(New->getType(), Old->getType())) {
4404 // These could still be something that needs exception specs checked.
4405 return MergeVarDeclExceptionSpecs(New, Old);
4406 }
4407 // C++ [basic.link]p10:
4408 // [...] the types specified by all declarations referring to a given
4409 // object or function shall be identical, except that declarations for an
4410 // array object can specify array types that differ by the presence or
4411 // absence of a major array bound (8.3.4).
4412 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4413 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4414 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4415
4416 // We are merging a variable declaration New into Old. If it has an array
4417 // bound, and that bound differs from Old's bound, we should diagnose the
4418 // mismatch.
4419 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4420 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4421 PrevVD = PrevVD->getPreviousDecl()) {
4422 QualType PrevVDTy = PrevVD->getType();
4423 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4424 continue;
4425
4426 if (!Context.hasSameType(New->getType(), PrevVDTy))
4427 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4428 }
4429 }
4430
4431 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4432 if (Context.hasSameType(OldArray->getElementType(),
4433 NewArray->getElementType()))
4434 MergedT = New->getType();
4435 }
4436 // FIXME: Check visibility. New is hidden but has a complete type. If New
4437 // has no array bound, it should not inherit one from Old, if Old is not
4438 // visible.
4439 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4440 if (Context.hasSameType(OldArray->getElementType(),
4441 NewArray->getElementType()))
4442 MergedT = Old->getType();
4443 }
4444 }
4445 else if (New->getType()->isObjCObjectPointerType() &&
4446 Old->getType()->isObjCObjectPointerType()) {
4447 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4448 Old->getType());
4449 }
4450 } else {
4451 // C 6.2.7p2:
4452 // All declarations that refer to the same object or function shall have
4453 // compatible type.
4454 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4455 }
4456 if (MergedT.isNull()) {
4457 // It's OK if we couldn't merge types if either type is dependent, for a
4458 // block-scope variable. In other cases (static data members of class
4459 // templates, variable templates, ...), we require the types to be
4460 // equivalent.
4461 // FIXME: The C++ standard doesn't say anything about this.
4462 if ((New->getType()->isDependentType() ||
4463 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4464 // If the old type was dependent, we can't merge with it, so the new type
4465 // becomes dependent for now. We'll reproduce the original type when we
4466 // instantiate the TypeSourceInfo for the variable.
4467 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4468 New->setType(Context.DependentTy);
4469 return;
4470 }
4471 return diagnoseVarDeclTypeMismatch(*this, New, Old);
4472 }
4473
4474 // Don't actually update the type on the new declaration if the old
4475 // declaration was an extern declaration in a different scope.
4476 if (MergeTypeWithOld)
4477 New->setType(MergedT);
4478}
4479
4480static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4481 LookupResult &Previous) {
4482 // C11 6.2.7p4:
4483 // For an identifier with internal or external linkage declared
4484 // in a scope in which a prior declaration of that identifier is
4485 // visible, if the prior declaration specifies internal or
4486 // external linkage, the type of the identifier at the later
4487 // declaration becomes the composite type.
4488 //
4489 // If the variable isn't visible, we do not merge with its type.
4490 if (Previous.isShadowed())
4491 return false;
4492
4493 if (S.getLangOpts().CPlusPlus) {
4494 // C++11 [dcl.array]p3:
4495 // If there is a preceding declaration of the entity in the same
4496 // scope in which the bound was specified, an omitted array bound
4497 // is taken to be the same as in that earlier declaration.
4498 return NewVD->isPreviousDeclInSameBlockScope() ||
4499 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4500 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4501 } else {
4502 // If the old declaration was function-local, don't merge with its
4503 // type unless we're in the same function.
4504 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4505 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4506 }
4507}
4508
4509/// MergeVarDecl - We just parsed a variable 'New' which has the same name
4510/// and scope as a previous declaration 'Old'. Figure out how to resolve this
4511/// situation, merging decls or emitting diagnostics as appropriate.
4512///
4513/// Tentative definition rules (C99 6.9.2p2) are checked by
4514/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4515/// definitions here, since the initializer hasn't been attached.
4516///
4517void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4518 // If the new decl is already invalid, don't do any other checking.
4519 if (New->isInvalidDecl())
4520 return;
4521
4522 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4523 return;
4524
4525 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4526
4527 // Verify the old decl was also a variable or variable template.
4528 VarDecl *Old = nullptr;
4529 VarTemplateDecl *OldTemplate = nullptr;
4530 if (Previous.isSingleResult()) {
4531 if (NewTemplate) {
4532 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4533 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4534
4535 if (auto *Shadow =
4536 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4537 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4538 return New->setInvalidDecl();
4539 } else {
4540 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4541
4542 if (auto *Shadow =
4543 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4544 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4545 return New->setInvalidDecl();
4546 }
4547 }
4548 if (!Old) {
4549 Diag(New->getLocation(), diag::err_redefinition_different_kind)
4550 << New->getDeclName();
4551 notePreviousDefinition(Previous.getRepresentativeDecl(),
4552 New->getLocation());
4553 return New->setInvalidDecl();
4554 }
4555
4556 // If the old declaration was found in an inline namespace and the new
4557 // declaration was qualified, update the DeclContext to match.
4558 adjustDeclContextForDeclaratorDecl(New, Old);
4559
4560 // Ensure the template parameters are compatible.
4561 if (NewTemplate &&
4562 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4563 OldTemplate->getTemplateParameters(),
4564 /*Complain=*/true, TPL_TemplateMatch))
4565 return New->setInvalidDecl();
4566
4567 // C++ [class.mem]p1:
4568 // A member shall not be declared twice in the member-specification [...]
4569 //
4570 // Here, we need only consider static data members.
4571 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4572 Diag(New->getLocation(), diag::err_duplicate_member)
4573 << New->getIdentifier();
4574 Diag(Old->getLocation(), diag::note_previous_declaration);
4575 New->setInvalidDecl();
4576 }
4577
4578 mergeDeclAttributes(New, Old);
4579 // Warn if an already-declared variable is made a weak_import in a subsequent
4580 // declaration
4581 if (New->hasAttr<WeakImportAttr>() &&
4582 Old->getStorageClass() == SC_None &&
4583 !Old->hasAttr<WeakImportAttr>()) {
4584 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4585 Diag(Old->getLocation(), diag::note_previous_declaration);
4586 // Remove weak_import attribute on new declaration.
4587 New->dropAttr<WeakImportAttr>();
4588 }
4589
4590 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4591 if (!Old->hasAttr<InternalLinkageAttr>()) {
4592 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4593 << ILA;
4594 Diag(Old->getLocation(), diag::note_previous_declaration);
4595 New->dropAttr<InternalLinkageAttr>();
4596 }
4597
4598 // Merge the types.
4599 VarDecl *MostRecent = Old->getMostRecentDecl();
4600 if (MostRecent != Old) {
4601 MergeVarDeclTypes(New, MostRecent,
4602 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4603 if (New->isInvalidDecl())
4604 return;
4605 }
4606
4607 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4608 if (New->isInvalidDecl())
4609 return;
4610
4611 diag::kind PrevDiag;
4612 SourceLocation OldLocation;
4613 std::tie(PrevDiag, OldLocation) =
4614 getNoteDiagForInvalidRedeclaration(Old, New);
4615
4616 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4617 if (New->getStorageClass() == SC_Static &&
4618 !New->isStaticDataMember() &&
4619 Old->hasExternalFormalLinkage()) {
4620 if (getLangOpts().MicrosoftExt) {
4621 Diag(New->getLocation(), diag::ext_static_non_static)
4622 << New->getDeclName();
4623 Diag(OldLocation, PrevDiag);
4624 } else {
4625 Diag(New->getLocation(), diag::err_static_non_static)
4626 << New->getDeclName();
4627 Diag(OldLocation, PrevDiag);
4628 return New->setInvalidDecl();
4629 }
4630 }
4631 // C99 6.2.2p4:
4632 // For an identifier declared with the storage-class specifier
4633 // extern in a scope in which a prior declaration of that
4634 // identifier is visible,23) if the prior declaration specifies
4635 // internal or external linkage, the linkage of the identifier at
4636 // the later declaration is the same as the linkage specified at
4637 // the prior declaration. If no prior declaration is visible, or
4638 // if the prior declaration specifies no linkage, then the
4639 // identifier has external linkage.
4640 if (New->hasExternalStorage() && Old->hasLinkage())
4641 /* Okay */;
4642 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4643 !New->isStaticDataMember() &&
4644 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4645 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4646 Diag(OldLocation, PrevDiag);
4647 return New->setInvalidDecl();
4648 }
4649
4650 // Check if extern is followed by non-extern and vice-versa.
4651 if (New->hasExternalStorage() &&
4652 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4653 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4654 Diag(OldLocation, PrevDiag);
4655 return New->setInvalidDecl();
4656 }
4657 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4658 !New->hasExternalStorage()) {
4659 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4660 Diag(OldLocation, PrevDiag);
4661 return New->setInvalidDecl();
4662 }
4663
4664 if (CheckRedeclarationInModule(New, Old))
4665 return;
4666
4667 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4668
4669 // FIXME: The test for external storage here seems wrong? We still
4670 // need to check for mismatches.
4671 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4672 // Don't complain about out-of-line definitions of static members.
4673 !(Old->getLexicalDeclContext()->isRecord() &&
4674 !New->getLexicalDeclContext()->isRecord())) {
4675 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4676 Diag(OldLocation, PrevDiag);
4677 return New->setInvalidDecl();
4678 }
4679
4680 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4681 if (VarDecl *Def = Old->getDefinition()) {
4682 // C++1z [dcl.fcn.spec]p4:
4683 // If the definition of a variable appears in a translation unit before
4684 // its first declaration as inline, the program is ill-formed.
4685 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4686 Diag(Def->getLocation(), diag::note_previous_definition);
4687 }
4688 }
4689
4690 // If this redeclaration makes the variable inline, we may need to add it to
4691 // UndefinedButUsed.
4692 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4693 !Old->getDefinition() && !New->isThisDeclarationADefinition())
4694 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4695 SourceLocation()));
4696
4697 if (New->getTLSKind() != Old->getTLSKind()) {
4698 if (!Old->getTLSKind()) {
4699 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4700 Diag(OldLocation, PrevDiag);
4701 } else if (!New->getTLSKind()) {
4702 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4703 Diag(OldLocation, PrevDiag);
4704 } else {
4705 // Do not allow redeclaration to change the variable between requiring
4706 // static and dynamic initialization.
4707 // FIXME: GCC allows this, but uses the TLS keyword on the first
4708 // declaration to determine the kind. Do we need to be compatible here?
4709 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4710 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4711 Diag(OldLocation, PrevDiag);
4712 }
4713 }
4714
4715 // C++ doesn't have tentative definitions, so go right ahead and check here.
4716 if (getLangOpts().CPlusPlus) {
4717 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4718 Old->getCanonicalDecl()->isConstexpr()) {
4719 // This definition won't be a definition any more once it's been merged.
4720 Diag(New->getLocation(),
4721 diag::warn_deprecated_redundant_constexpr_static_def);
4722 } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4723 VarDecl *Def = Old->getDefinition();
4724 if (Def && checkVarDeclRedefinition(Def, New))
4725 return;
4726 }
4727 }
4728
4729 if (haveIncompatibleLanguageLinkages(Old, New)) {
4730 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4731 Diag(OldLocation, PrevDiag);
4732 New->setInvalidDecl();
4733 return;
4734 }
4735
4736 // Merge "used" flag.
4737 if (Old->getMostRecentDecl()->isUsed(false))
4738 New->setIsUsed();
4739
4740 // Keep a chain of previous declarations.
4741 New->setPreviousDecl(Old);
4742 if (NewTemplate)
4743 NewTemplate->setPreviousDecl(OldTemplate);
4744
4745 // Inherit access appropriately.
4746 New->setAccess(Old->getAccess());
4747 if (NewTemplate)
4748 NewTemplate->setAccess(New->getAccess());
4749
4750 if (Old->isInline())
4751 New->setImplicitlyInline();
4752}
4753
4754void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4755 SourceManager &SrcMgr = getSourceManager();
4756 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4757 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4758 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4759 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4760 auto &HSI = PP.getHeaderSearchInfo();
4761 StringRef HdrFilename =
4762 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4763
4764 auto noteFromModuleOrInclude = [&](Module *Mod,
4765 SourceLocation IncLoc) -> bool {
4766 // Redefinition errors with modules are common with non modular mapped
4767 // headers, example: a non-modular header H in module A that also gets
4768 // included directly in a TU. Pointing twice to the same header/definition
4769 // is confusing, try to get better diagnostics when modules is on.
4770 if (IncLoc.isValid()) {
4771 if (Mod) {
4772 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4773 << HdrFilename.str() << Mod->getFullModuleName();
4774 if (!Mod->DefinitionLoc.isInvalid())
4775 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4776 << Mod->getFullModuleName();
4777 } else {
4778 Diag(IncLoc, diag::note_redefinition_include_same_file)
4779 << HdrFilename.str();
4780 }
4781 return true;
4782 }
4783
4784 return false;
4785 };
4786
4787 // Is it the same file and same offset? Provide more information on why
4788 // this leads to a redefinition error.
4789 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4790 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4791 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4792 bool EmittedDiag =
4793 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4794 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4795
4796 // If the header has no guards, emit a note suggesting one.
4797 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4798 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4799
4800 if (EmittedDiag)
4801 return;
4802 }
4803
4804 // Redefinition coming from different files or couldn't do better above.
4805 if (Old->getLocation().isValid())
4806 Diag(Old->getLocation(), diag::note_previous_definition);
4807}
4808
4809/// We've just determined that \p Old and \p New both appear to be definitions
4810/// of the same variable. Either diagnose or fix the problem.
4811bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4812 if (!hasVisibleDefinition(Old) &&
4813 (New->getFormalLinkage() == InternalLinkage ||
4814 New->isInline() ||
4815 isa<VarTemplateSpecializationDecl>(New) ||
4816 New->getDescribedVarTemplate() ||
4817 New->getNumTemplateParameterLists() ||
4818 New->getDeclContext()->isDependentContext())) {
4819 // The previous definition is hidden, and multiple definitions are
4820 // permitted (in separate TUs). Demote this to a declaration.
4821 New->demoteThisDefinitionToDeclaration();
4822
4823 // Make the canonical definition visible.
4824 if (auto *OldTD = Old->getDescribedVarTemplate())
4825 makeMergedDefinitionVisible(OldTD);
4826 makeMergedDefinitionVisible(Old);
4827 return false;
4828 } else {
4829 Diag(New->getLocation(), diag::err_redefinition) << New;
4830 notePreviousDefinition(Old, New->getLocation());
4831 New->setInvalidDecl();
4832 return true;
4833 }
4834}
4835
4836/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4837/// no declarator (e.g. "struct foo;") is parsed.
4838Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
4839 DeclSpec &DS,
4840 const ParsedAttributesView &DeclAttrs,
4841 RecordDecl *&AnonRecord) {
4842 return ParsedFreeStandingDeclSpec(
4843 S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);
4844}
4845
4846// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4847// disambiguate entities defined in different scopes.
4848// While the VS2015 ABI fixes potential miscompiles, it is also breaks
4849// compatibility.
4850// We will pick our mangling number depending on which version of MSVC is being
4851// targeted.
4852static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4853 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4854 ? S->getMSCurManglingNumber()
4855 : S->getMSLastManglingNumber();
4856}
4857
4858void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4859 if (!Context.getLangOpts().CPlusPlus)
4860 return;
4861
4862 if (isa<CXXRecordDecl>(Tag->getParent())) {
4863 // If this tag is the direct child of a class, number it if
4864 // it is anonymous.
4865 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4866 return;
4867 MangleNumberingContext &MCtx =
4868 Context.getManglingNumberContext(Tag->getParent());
4869 Context.setManglingNumber(
4870 Tag, MCtx.getManglingNumber(
4871 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4872 return;
4873 }
4874
4875 // If this tag isn't a direct child of a class, number it if it is local.
4876 MangleNumberingContext *MCtx;
4877 Decl *ManglingContextDecl;
4878 std::tie(MCtx, ManglingContextDecl) =
4879 getCurrentMangleNumberContext(Tag->getDeclContext());
4880 if (MCtx) {
4881 Context.setManglingNumber(
4882 Tag, MCtx->getManglingNumber(
4883 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4884 }
4885}
4886
4887namespace {
4888struct NonCLikeKind {
4889 enum {
4890 None,
4891 BaseClass,
4892 DefaultMemberInit,
4893 Lambda,
4894 Friend,
4895 OtherMember,
4896 Invalid,
4897 } Kind = None;
4898 SourceRange Range;
4899
4900 explicit operator bool() { return Kind != None; }
4901};
4902}
4903
4904/// Determine whether a class is C-like, according to the rules of C++
4905/// [dcl.typedef] for anonymous classes with typedef names for linkage.
4906static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4907 if (RD->isInvalidDecl())
4908 return {NonCLikeKind::Invalid, {}};
4909
4910 // C++ [dcl.typedef]p9: [P1766R1]
4911 // An unnamed class with a typedef name for linkage purposes shall not
4912 //
4913 // -- have any base classes
4914 if (RD->getNumBases())
4915 return {NonCLikeKind::BaseClass,
4916 SourceRange(RD->bases_begin()->getBeginLoc(),
4917 RD->bases_end()[-1].getEndLoc())};
4918 bool Invalid = false;
4919 for (Decl *D : RD->decls()) {
4920 // Don't complain about things we already diagnosed.
4921 if (D->isInvalidDecl()) {
4922 Invalid = true;
4923 continue;
4924 }
4925
4926 // -- have any [...] default member initializers
4927 if (auto *FD = dyn_cast<FieldDecl>(D)) {
4928 if (FD->hasInClassInitializer()) {
4929 auto *Init = FD->getInClassInitializer();
4930 return {NonCLikeKind::DefaultMemberInit,
4931 Init ? Init->getSourceRange() : D->getSourceRange()};
4932 }
4933 continue;
4934 }
4935
4936 // FIXME: We don't allow friend declarations. This violates the wording of
4937 // P1766, but not the intent.
4938 if (isa<FriendDecl>(D))
4939 return {NonCLikeKind::Friend, D->getSourceRange()};
4940
4941 // -- declare any members other than non-static data members, member
4942 // enumerations, or member classes,
4943 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4944 isa<EnumDecl>(D))
4945 continue;
4946 auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4947 if (!MemberRD) {
4948 if (D->isImplicit())
4949 continue;
4950 return {NonCLikeKind::OtherMember, D->getSourceRange()};
4951 }
4952
4953 // -- contain a lambda-expression,
4954 if (MemberRD->isLambda())
4955 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4956
4957 // and all member classes shall also satisfy these requirements
4958 // (recursively).
4959 if (MemberRD->isThisDeclarationADefinition()) {
4960 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4961 return Kind;
4962 }
4963 }
4964
4965 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4966}
4967
4968void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4969 TypedefNameDecl *NewTD) {
4970 if (TagFromDeclSpec->isInvalidDecl())
4971 return;
4972
4973 // Do nothing if the tag already has a name for linkage purposes.
4974 if (TagFromDeclSpec->hasNameForLinkage())
4975 return;
4976
4977 // A well-formed anonymous tag must always be a TUK_Definition.
4978 assert(TagFromDeclSpec->isThisDeclarationADefinition())(static_cast <bool> (TagFromDeclSpec->isThisDeclarationADefinition
()) ? void (0) : __assert_fail ("TagFromDeclSpec->isThisDeclarationADefinition()"
, "clang/lib/Sema/SemaDecl.cpp", 4978, __extension__ __PRETTY_FUNCTION__
))
;
4979
4980 // The type must match the tag exactly; no qualifiers allowed.
4981 if (!Context.hasSameType(NewTD->getUnderlyingType(),
4982 Context.getTagDeclType(TagFromDeclSpec))) {
4983 if (getLangOpts().CPlusPlus)
4984 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4985 return;
4986 }
4987
4988 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4989 // An unnamed class with a typedef name for linkage purposes shall [be
4990 // C-like].
4991 //
4992 // FIXME: Also diagnose if we've already computed the linkage. That ideally
4993 // shouldn't happen, but there are constructs that the language rule doesn't
4994 // disallow for which we can't reasonably avoid computing linkage early.
4995 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4996 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4997 : NonCLikeKind();
4998 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4999 if (NonCLike || ChangesLinkage) {
5000 if (NonCLike.Kind == NonCLikeKind::Invalid)
5001 return;
5002
5003 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
5004 if (ChangesLinkage) {
5005 // If the linkage changes, we can't accept this as an extension.
5006 if (NonCLike.Kind == NonCLikeKind::None)
5007 DiagID = diag::err_typedef_changes_linkage;
5008 else
5009 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
5010 }
5011
5012 SourceLocation FixitLoc =
5013 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
5014 llvm::SmallString<40> TextToInsert;
5015 TextToInsert += ' ';
5016 TextToInsert += NewTD->getIdentifier()->getName();
5017
5018 Diag(FixitLoc, DiagID)
5019 << isa<TypeAliasDecl>(NewTD)
5020 << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
5021 if (NonCLike.Kind != NonCLikeKind::None) {
5022 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
5023 << NonCLike.Kind - 1 << NonCLike.Range;
5024 }
5025 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
5026 << NewTD << isa<TypeAliasDecl>(NewTD);
5027
5028 if (ChangesLinkage)
5029 return;
5030 }
5031
5032 // Otherwise, set this as the anon-decl typedef for the tag.
5033 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
5034}
5035
5036static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {
5037 DeclSpec::TST T = DS.getTypeSpecType();
5038 switch (T) {
5039 case DeclSpec::TST_class:
5040 return 0;
5041 case DeclSpec::TST_struct:
5042 return 1;
5043 case DeclSpec::TST_interface:
5044 return 2;
5045 case DeclSpec::TST_union:
5046 return 3;
5047 case DeclSpec::TST_enum:
5048 if (const auto *ED = dyn_cast<EnumDecl>(DS.getRepAsDecl())) {
5049 if (ED->isScopedUsingClassTag())
5050 return 5;
5051 if (ED->isScoped())
5052 return 6;
5053 }
5054 return 4;
5055 default:
5056 llvm_unreachable("unexpected type specifier")::llvm::llvm_unreachable_internal("unexpected type specifier"
, "clang/lib/Sema/SemaDecl.cpp", 5056)
;
5057 }
5058}
5059/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
5060/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
5061/// parameters to cope with template friend declarations.
5062Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
5063 DeclSpec &DS,
5064 const ParsedAttributesView &DeclAttrs,
5065 MultiTemplateParamsArg TemplateParams,
5066 bool IsExplicitInstantiation,
5067 RecordDecl *&AnonRecord) {
5068 Decl *TagD = nullptr;
5069 TagDecl *Tag = nullptr;
5070 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
5071 DS.getTypeSpecType() == DeclSpec::TST_struct ||
5072 DS.getTypeSpecType() == DeclSpec::TST_interface ||
5073 DS.getTypeSpecType() == DeclSpec::TST_union ||
5074 DS.getTypeSpecType() == DeclSpec::TST_enum) {
5075 TagD = DS.getRepAsDecl();
5076
5077 if (!TagD) // We probably had an error
5078 return nullptr;
5079
5080 // Note that the above type specs guarantee that the
5081 // type rep is a Decl, whereas in many of the others
5082 // it's a Type.
5083 if (isa<TagDecl>(TagD))
5084 Tag = cast<TagDecl>(TagD);
5085 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
5086 Tag = CTD->getTemplatedDecl();
5087 }
5088
5089 if (Tag) {
5090 handleTagNumbering(Tag, S);
5091 Tag->setFreeStanding();
5092 if (Tag->isInvalidDecl())
5093 return Tag;
5094 }
5095
5096 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5097 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5098 // or incomplete types shall not be restrict-qualified."
5099 if (TypeQuals & DeclSpec::TQ_restrict)
5100 Diag(DS.getRestrictSpecLoc(),
5101 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5102 << DS.getSourceRange();
5103 }
5104
5105 if (DS.isInlineSpecified())
5106 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
5107 << getLangOpts().CPlusPlus17;
5108
5109 if (DS.hasConstexprSpecifier()) {
5110 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5111 // and definitions of functions and variables.
5112 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5113 // the declaration of a function or function template
5114 if (Tag)
5115 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
5116 << GetDiagnosticTypeSpecifierID(DS)
5117 << static_cast<int>(DS.getConstexprSpecifier());
5118 else
5119 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
5120 << static_cast<int>(DS.getConstexprSpecifier());
5121 // Don't emit warnings after this error.
5122 return TagD;
5123 }
5124
5125 DiagnoseFunctionSpecifiers(DS);
5126
5127 if (DS.isFriendSpecified()) {
5128 // If we're dealing with a decl but not a TagDecl, assume that
5129 // whatever routines created it handled the friendship aspect.
5130 if (TagD && !Tag)
5131 return nullptr;
5132 return ActOnFriendTypeDecl(S, DS, TemplateParams);
5133 }
5134
5135 const CXXScopeSpec &SS = DS.getTypeSpecScope();
5136 bool IsExplicitSpecialization =
5137 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
5138 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
5139 !IsExplicitInstantiation && !IsExplicitSpecialization &&
5140 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
5141 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
5142 // nested-name-specifier unless it is an explicit instantiation
5143 // or an explicit specialization.
5144 //
5145 // FIXME: We allow class template partial specializations here too, per the
5146 // obvious intent of DR1819.
5147 //
5148 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
5149 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
5150 << GetDiagnosticTypeSpecifierID(DS) << SS.getRange();
5151 return nullptr;
5152 }
5153
5154 // Track whether this decl-specifier declares anything.
5155 bool DeclaresAnything = true;
5156
5157 // Handle anonymous struct definitions.
5158 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
5159 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5160 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
5161 if (getLangOpts().CPlusPlus ||
5162 Record->getDeclContext()->isRecord()) {
5163 // If CurContext is a DeclContext that can contain statements,
5164 // RecursiveASTVisitor won't visit the decls that
5165 // BuildAnonymousStructOrUnion() will put into CurContext.
5166 // Also store them here so that they can be part of the
5167 // DeclStmt that gets created in this case.
5168 // FIXME: Also return the IndirectFieldDecls created by
5169 // BuildAnonymousStructOr union, for the same reason?
5170 if (CurContext->isFunctionOrMethod())
5171 AnonRecord = Record;
5172 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5173 Context.getPrintingPolicy());
5174 }
5175
5176 DeclaresAnything = false;
5177 }
5178 }
5179
5180 // C11 6.7.2.1p2:
5181 // A struct-declaration that does not declare an anonymous structure or
5182 // anonymous union shall contain a struct-declarator-list.
5183 //
5184 // This rule also existed in C89 and C99; the grammar for struct-declaration
5185 // did not permit a struct-declaration without a struct-declarator-list.
5186 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5187 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
5188 // Check for Microsoft C extension: anonymous struct/union member.
5189 // Handle 2 kinds of anonymous struct/union:
5190 // struct STRUCT;
5191 // union UNION;
5192 // and
5193 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5194 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5195 if ((Tag && Tag->getDeclName()) ||
5196 DS.getTypeSpecType() == DeclSpec::TST_typename) {
5197 RecordDecl *Record = nullptr;
5198 if (Tag)
5199 Record = dyn_cast<RecordDecl>(Tag);
5200 else if (const RecordType *RT =
5201 DS.getRepAsType().get()->getAsStructureType())
5202 Record = RT->getDecl();
5203 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
5204 Record = UT->getDecl();
5205
5206 if (Record && getLangOpts().MicrosoftExt) {
5207 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5208 << Record->isUnion() << DS.getSourceRange();
5209 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
5210 }
5211
5212 DeclaresAnything = false;
5213 }
5214 }
5215
5216 // Skip all the checks below if we have a type error.
5217 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
5218 (TagD && TagD->isInvalidDecl()))
5219 return TagD;
5220
5221 if (getLangOpts().CPlusPlus &&
5222 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
5223 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5224 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
5225 !Enum->getIdentifier() && !Enum->isInvalidDecl())
5226 DeclaresAnything = false;
5227
5228 if (!DS.isMissingDeclaratorOk()) {
5229 // Customize diagnostic for a typedef missing a name.
5230 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
5231 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5232 << DS.getSourceRange();
5233 else
5234 DeclaresAnything = false;
5235 }
5236
5237 if (DS.isModulePrivateSpecified() &&
5238 Tag && Tag->getDeclContext()->isFunctionOrMethod())
5239 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5240 << Tag->getTagKind()
5241 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
5242
5243 ActOnDocumentableDecl(TagD);
5244
5245 // C 6.7/2:
5246 // A declaration [...] shall declare at least a declarator [...], a tag,
5247 // or the members of an enumeration.
5248 // C++ [dcl.dcl]p3:
5249 // [If there are no declarators], and except for the declaration of an
5250 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5251 // names into the program, or shall redeclare a name introduced by a
5252 // previous declaration.
5253 if (!DeclaresAnything) {
5254 // In C, we allow this as a (popular) extension / bug. Don't bother
5255 // producing further diagnostics for redundant qualifiers after this.
5256 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5257 ? diag::err_no_declarators
5258 : diag::ext_no_declarators)
5259 << DS.getSourceRange();
5260 return TagD;
5261 }
5262
5263 // C++ [dcl.stc]p1:
5264 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5265 // init-declarator-list of the declaration shall not be empty.
5266 // C++ [dcl.fct.spec]p1:
5267 // If a cv-qualifier appears in a decl-specifier-seq, the
5268 // init-declarator-list of the declaration shall not be empty.
5269 //
5270 // Spurious qualifiers here appear to be valid in C.
5271 unsigned DiagID = diag::warn_standalone_specifier;
5272 if (getLangOpts().CPlusPlus)
5273 DiagID = diag::ext_standalone_specifier;
5274
5275 // Note that a linkage-specification sets a storage class, but
5276 // 'extern "C" struct foo;' is actually valid and not theoretically
5277 // useless.
5278 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5279 if (SCS == DeclSpec::SCS_mutable)
5280 // Since mutable is not a viable storage class specifier in C, there is
5281 // no reason to treat it as an extension. Instead, diagnose as an error.
5282 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5283 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5284 Diag(DS.getStorageClassSpecLoc(), DiagID)
5285 << DeclSpec::getSpecifierName(SCS);
5286 }
5287
5288 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
5289 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
5290 << DeclSpec::getSpecifierName(TSCS);
5291 if (DS.getTypeQualifiers()) {
5292 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5293 Diag(DS.getConstSpecLoc(), DiagID) << "const";
5294 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5295 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5296 // Restrict is covered above.
5297 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5298 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5299 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5300 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5301 }
5302
5303 // Warn about ignored type attributes, for example:
5304 // __attribute__((aligned)) struct A;
5305 // Attributes should be placed after tag to apply to type declaration.
5306 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5307 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5308 if (TypeSpecType == DeclSpec::TST_class ||
5309 TypeSpecType == DeclSpec::TST_struct ||
5310 TypeSpecType == DeclSpec::TST_interface ||
5311 TypeSpecType == DeclSpec::TST_union ||
5312 TypeSpecType == DeclSpec::TST_enum) {
5313 for (const ParsedAttr &AL : DS.getAttributes())
5314 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
5315 << AL << GetDiagnosticTypeSpecifierID(DS);
5316 for (const ParsedAttr &AL : DeclAttrs)
5317 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
5318 << AL << GetDiagnosticTypeSpecifierID(DS);
5319 }
5320 }
5321
5322 return TagD;
5323}
5324
5325/// We are trying to inject an anonymous member into the given scope;
5326/// check if there's an existing declaration that can't be overloaded.
5327///
5328/// \return true if this is a forbidden redeclaration
5329static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
5330 Scope *S,
5331 DeclContext *Owner,
5332 DeclarationName Name,
5333 SourceLocation NameLoc,
5334 bool IsUnion) {
5335 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
5336 Sema::ForVisibleRedeclaration);
5337 if (!SemaRef.LookupName(R, S)) return false;
5338
5339 // Pick a representative declaration.
5340 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5341 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", 5341, __extension__ __PRETTY_FUNCTION__
))
;
5342
5343 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5344 return false;
5345
5346 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5347 << IsUnion << Name;
5348 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5349
5350 return true;
5351}
5352
5353/// InjectAnonymousStructOrUnionMembers - Inject the members of the
5354/// anonymous struct or union AnonRecord into the owning context Owner
5355/// and scope S. This routine will be invoked just after we realize
5356/// that an unnamed union or struct is actually an anonymous union or
5357/// struct, e.g.,
5358///
5359/// @code
5360/// union {
5361/// int i;
5362/// float f;
5363/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5364/// // f into the surrounding scope.x
5365/// @endcode
5366///
5367/// This routine is recursive, injecting the names of nested anonymous
5368/// structs/unions into the owning context and scope as well.
5369static bool
5370InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
5371 RecordDecl *AnonRecord, AccessSpecifier AS,
5372 SmallVectorImpl<NamedDecl *> &Chaining) {
5373 bool Invalid = false;
5374
5375 // Look every FieldDecl and IndirectFieldDecl with a name.
5376 for (auto *D : AnonRecord->decls()) {
5377 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5378 cast<NamedDecl>(D)->getDeclName()) {
5379 ValueDecl *VD = cast<ValueDecl>(D);
5380 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
5381 VD->getLocation(),
5382 AnonRecord->isUnion())) {
5383 // C++ [class.union]p2:
5384 // The names of the members of an anonymous union shall be
5385 // distinct from the names of any other entity in the
5386 // scope in which the anonymous union is declared.
5387 Invalid = true;
5388 } else {
5389 // C++ [class.union]p2:
5390 // For the purpose of name lookup, after the anonymous union
5391 // definition, the members of the anonymous union are
5392 // considered to have been defined in the scope in which the
5393 // anonymous union is declared.
5394 unsigned OldChainingSize = Chaining.size();
5395 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5396 Chaining.append(IF->chain_begin(), IF->chain_end());
5397 else
5398 Chaining.push_back(VD);
5399
5400 assert(Chaining.size() >= 2)(static_cast <bool> (Chaining.size() >= 2) ? void (0
) : __assert_fail ("Chaining.size() >= 2", "clang/lib/Sema/SemaDecl.cpp"
, 5400, __extension__ __PRETTY_FUNCTION__))
;
5401 NamedDecl **NamedChain =
5402 new (SemaRef.Context)NamedDecl*[Chaining.size()];
5403 for (unsigned i = 0; i < Chaining.size(); i++)
5404 NamedChain[i] = Chaining[i];
5405
5406 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
5407 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5408 VD->getType(), {NamedChain, Chaining.size()});
5409
5410 for (const auto *Attr : VD->attrs())
5411 IndirectField->addAttr(Attr->clone(SemaRef.Context));
5412
5413 IndirectField->setAccess(AS);
5414 IndirectField->setImplicit();
5415 SemaRef.PushOnScopeChains(IndirectField, S);
5416
5417 // That includes picking up the appropriate access specifier.
5418 if (AS != AS_none) IndirectField->setAccess(AS);
5419
5420 Chaining.resize(OldChainingSize);
5421 }
5422 }
5423 }
5424
5425 return Invalid;
5426}
5427
5428/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5429/// a VarDecl::StorageClass. Any error reporting is up to the caller:
5430/// illegal input values are mapped to SC_None.
5431static StorageClass
5432StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5433 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5434 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", 5435, __extension__ __PRETTY_FUNCTION__
))
5435 "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", 5435, __extension__ __PRETTY_FUNCTION__
))
;
5436 switch (StorageClassSpec) {
5437 case DeclSpec::SCS_unspecified: return SC_None;
5438 case DeclSpec::SCS_extern:
5439 if (DS.isExternInLinkageSpec())
5440 return SC_None;
5441 return SC_Extern;
5442 case DeclSpec::SCS_static: return SC_Static;
5443 case DeclSpec::SCS_auto: return SC_Auto;
5444 case DeclSpec::SCS_register: return SC_Register;
5445 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5446 // Illegal SCSs map to None: error reporting is up to the caller.
5447 case DeclSpec::SCS_mutable: // Fall through.
5448 case DeclSpec::SCS_typedef: return SC_None;
5449 }
5450 llvm_unreachable("unknown storage class specifier")::llvm::llvm_unreachable_internal("unknown storage class specifier"
, "clang/lib/Sema/SemaDecl.cpp", 5450)
;
5451}
5452
5453static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5454 assert(Record->hasInClassInitializer())(static_cast <bool> (Record->hasInClassInitializer()
) ? void (0) : __assert_fail ("Record->hasInClassInitializer()"
, "clang/lib/Sema/SemaDecl.cpp", 5454, __extension__ __PRETTY_FUNCTION__
))
;
5455
5456 for (const auto *I : Record->decls()) {
5457 const auto *FD = dyn_cast<FieldDecl>(I);
5458 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5459 FD = IFD->getAnonField();
5460 if (FD && FD->hasInClassInitializer())
5461 return FD->getLocation();
5462 }
5463
5464 llvm_unreachable("couldn't find in-class initializer")::llvm::llvm_unreachable_internal("couldn't find in-class initializer"
, "clang/lib/Sema/SemaDecl.cpp", 5464)
;
5465}
5466
5467static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5468 SourceLocation DefaultInitLoc) {
5469 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5470 return;
5471
5472 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5473 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5474}
5475
5476static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5477 CXXRecordDecl *AnonUnion) {
5478 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5479 return;
5480
5481 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
5482}
5483
5484/// BuildAnonymousStructOrUnion - Handle the declaration of an
5485/// anonymous structure or union. Anonymous unions are a C++ feature
5486/// (C++ [class.union]) and a C11 feature; anonymous structures
5487/// are a C11 feature and GNU C++ extension.
5488Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5489 AccessSpecifier AS,
5490 RecordDecl *Record,
5491 const PrintingPolicy &Policy) {
5492 DeclContext *Owner = Record->getDeclContext();
5493
5494 // Diagnose whether this anonymous struct/union is an extension.
5495 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5496 Diag(Record->getLocation(), diag::ext_anonymous_union);
5497 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5498 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5499 else if (!Record->isUnion() && !getLangOpts().C11)
5500 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5501
5502 // C and C++ require different kinds of checks for anonymous
5503 // structs/unions.
5504 bool Invalid = false;
5505 if (getLangOpts().CPlusPlus) {
5506 const char *PrevSpec = nullptr;
5507 if (Record->isUnion()) {
5508 // C++ [class.union]p6:
5509 // C++17 [class.union.anon]p2:
5510 // Anonymous unions declared in a named namespace or in the
5511 // global namespace shall be declared static.
5512 unsigned DiagID;
5513 DeclContext *OwnerScope = Owner->getRedeclContext();
5514 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5515 (OwnerScope->isTranslationUnit() ||
5516 (OwnerScope->isNamespace() &&
5517 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5518 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5519 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5520
5521 // Recover by adding 'static'.
5522 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5523 PrevSpec, DiagID, Policy);
5524 }
5525 // C++ [class.union]p6:
5526 // A storage class is not allowed in a declaration of an
5527 // anonymous union in a class scope.
5528 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5529 isa<RecordDecl>(Owner)) {
5530 Diag(DS.getStorageClassSpecLoc(),
5531 diag::err_anonymous_union_with_storage_spec)
5532 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5533
5534 // Recover by removing the storage specifier.
5535 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5536 SourceLocation(),
5537 PrevSpec, DiagID, Context.getPrintingPolicy());
5538 }
5539 }
5540
5541 // Ignore const/volatile/restrict qualifiers.
5542 if (DS.getTypeQualifiers()) {
5543 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5544 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5545 << Record->isUnion() << "const"
5546 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5547 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5548 Diag(DS.getVolatileSpecLoc(),
5549 diag::ext_anonymous_struct_union_qualified)
5550 << Record->isUnion() << "volatile"
5551 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5552 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5553 Diag(DS.getRestrictSpecLoc(),
5554 diag::ext_anonymous_struct_union_qualified)
5555 << Record->isUnion() << "restrict"
5556 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5557 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5558 Diag(DS.getAtomicSpecLoc(),
5559 diag::ext_anonymous_struct_union_qualified)
5560 << Record->isUnion() << "_Atomic"
5561 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5562 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5563 Diag(DS.getUnalignedSpecLoc(),
5564 diag::ext_anonymous_struct_union_qualified)
5565 << Record->isUnion() << "__unaligned"
5566 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5567
5568 DS.ClearTypeQualifiers();
5569 }
5570
5571 // C++ [class.union]p2:
5572 // The member-specification of an anonymous union shall only
5573 // define non-static data members. [Note: nested types and
5574 // functions cannot be declared within an anonymous union. ]
5575 for (auto *Mem : Record->decls()) {
5576 // Ignore invalid declarations; we already diagnosed them.
5577 if (Mem->isInvalidDecl())
5578 continue;
5579
5580 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5581 // C++ [class.union]p3:
5582 // An anonymous union shall not have private or protected
5583 // members (clause 11).
5584 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"
, 5584, __extension__ __PRETTY_FUNCTION__))
;
5585 if (FD->getAccess() != AS_public) {
5586 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5587 << Record->isUnion() << (FD->getAccess() == AS_protected);
5588 Invalid = true;
5589 }
5590
5591 // C++ [class.union]p1
5592 // An object of a class with a non-trivial constructor, a non-trivial
5593 // copy constructor, a non-trivial destructor, or a non-trivial copy
5594 // assignment operator cannot be a member of a union, nor can an
5595 // array of such objects.
5596 if (CheckNontrivialField(FD))
5597 Invalid = true;
5598 } else if (Mem->isImplicit()) {
5599 // Any implicit members are fine.
5600 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5601 // This is a type that showed up in an
5602 // elaborated-type-specifier inside the anonymous struct or
5603 // union, but which actually declares a type outside of the
5604 // anonymous struct or union. It's okay.
5605 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5606 if (!MemRecord->isAnonymousStructOrUnion() &&
5607 MemRecord->getDeclName()) {
5608 // Visual C++ allows type definition in anonymous struct or union.
5609 if (getLangOpts().MicrosoftExt)
5610 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5611 << Record->isUnion();
5612 else {
5613 // This is a nested type declaration.
5614 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5615 << Record->isUnion();
5616 Invalid = true;
5617 }
5618 } else {
5619 // This is an anonymous type definition within another anonymous type.
5620 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5621 // not part of standard C++.
5622 Diag(MemRecord->getLocation(),
5623 diag::ext_anonymous_record_with_anonymous_type)
5624 << Record->isUnion();
5625 }
5626 } else if (isa<AccessSpecDecl>(Mem)) {
5627 // Any access specifier is fine.
5628 } else if (isa<StaticAssertDecl>(Mem)) {
5629 // In C++1z, static_assert declarations are also fine.
5630 } else {
5631 // We have something that isn't a non-static data
5632 // member. Complain about it.
5633 unsigned DK = diag::err_anonymous_record_bad_member;
5634 if (isa<TypeDecl>(Mem))
5635 DK = diag::err_anonymous_record_with_type;
5636 else if (isa<FunctionDecl>(Mem))
5637 DK = diag::err_anonymous_record_with_function;
5638 else if (isa<VarDecl>(Mem))
5639 DK = diag::err_anonymous_record_with_static;
5640
5641 // Visual C++ allows type definition in anonymous struct or union.
5642 if (getLangOpts().MicrosoftExt &&
5643 DK == diag::err_anonymous_record_with_type)
5644 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5645 << Record->isUnion();
5646 else {
5647 Diag(Mem->getLocation(), DK) << Record->isUnion();
5648 Invalid = true;
5649 }
5650 }
5651 }
5652
5653 // C++11 [class.union]p8 (DR1460):
5654 // At most one variant member of a union may have a
5655 // brace-or-equal-initializer.
5656 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5657 Owner->isRecord())
5658 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5659 cast<CXXRecordDecl>(Record));
5660 }
5661
5662 if (!Record->isUnion() && !Owner->isRecord()) {
5663 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5664 << getLangOpts().CPlusPlus;
5665 Invalid = true;
5666 }
5667
5668 // C++ [dcl.dcl]p3:
5669 // [If there are no declarators], and except for the declaration of an
5670 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5671 // names into the program
5672 // C++ [class.mem]p2:
5673 // each such member-declaration shall either declare at least one member
5674 // name of the class or declare at least one unnamed bit-field
5675 //
5676 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5677 if (getLangOpts().CPlusPlus && Record->field_empty())
5678 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5679
5680 // Mock up a declarator.
5681 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::Member);
5682 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5683 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", 5683, __extension__ __PRETTY_FUNCTION__
))
;
5684
5685 // Create a declaration for this anonymous struct/union.
5686 NamedDecl *Anon = nullptr;
5687 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5688 Anon = FieldDecl::Create(
5689 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5690 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5691 /*BitWidth=*/nullptr, /*Mutable=*/false,
5692 /*InitStyle=*/ICIS_NoInit);
5693 Anon->setAccess(AS);
5694 ProcessDeclAttributes(S, Anon, Dc);
5695
5696 if (getLangOpts().CPlusPlus)
5697 FieldCollector->Add(cast<FieldDecl>(Anon));
5698 } else {
5699 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5700 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5701 if (SCSpec == DeclSpec::SCS_mutable) {
5702 // mutable can only appear on non-static class members, so it's always
5703 // an error here
5704 Diag(Record->getLocation(), diag::err_mutable_nonmember);
5705 Invalid = true;
5706 SC = SC_None;
5707 }
5708
5709 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", 5709, __extension__ __PRETTY_FUNCTION__
))
;
5710 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5711 Record->getLocation(), /*IdentifierInfo=*/nullptr,
5712 Context.getTypeDeclType(Record), TInfo, SC);
5713
5714 // Default-initialize the implicit variable. This initialization will be
5715 // trivial in almost all cases, except if a union member has an in-class
5716 // initializer:
5717 // union { int n = 0; };
5718 ActOnUninitializedDecl(Anon);
5719 }
5720 Anon->setImplicit();
5721
5722 // Mark this as an anonymous struct/union type.
5723 Record->setAnonymousStructOrUnion(true);
5724
5725 // Add the anonymous struct/union object to the current
5726 // context. We'll be referencing this object when we refer to one of
5727 // its members.
5728 Owner->addDecl(Anon);
5729
5730 // Inject the members of the anonymous struct/union into the owning
5731 // context and into the identifier resolver chain for name lookup
5732 // purposes.
5733 SmallVector<NamedDecl*, 2> Chain;
5734 Chain.push_back(Anon);
5735
5736 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5737 Invalid = true;
5738
5739 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5740 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5741 MangleNumberingContext *MCtx;
5742 Decl *ManglingContextDecl;
5743 std::tie(MCtx, ManglingContextDecl) =
5744 getCurrentMangleNumberContext(NewVD->getDeclContext());
5745 if (MCtx) {
5746 Context.setManglingNumber(
5747 NewVD, MCtx->getManglingNumber(
5748 NewVD, getMSManglingNumber(getLangOpts(), S)));
5749 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5750 }
5751 }
5752 }
5753
5754 if (Invalid)
5755 Anon->setInvalidDecl();
5756
5757 return Anon;
5758}
5759
5760/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5761/// Microsoft C anonymous structure.
5762/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5763/// Example:
5764///
5765/// struct A { int a; };
5766/// struct B { struct A; int b; };
5767///
5768/// void foo() {
5769/// B var;
5770/// var.a = 3;
5771/// }
5772///
5773Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5774 RecordDecl *Record) {
5775 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", 5775, __extension__ __PRETTY_FUNCTION__
))
;
5776
5777 // Mock up a declarator.
5778 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::TypeName);
5779 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5780 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", 5780, __extension__ __PRETTY_FUNCTION__
))
;
5781
5782 auto *ParentDecl = cast<RecordDecl>(CurContext);
5783 QualType RecTy = Context.getTypeDeclType(Record);
5784
5785 // Create a declaration for this anonymous struct.
5786 NamedDecl *Anon =
5787 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5788 /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5789 /*BitWidth=*/nullptr, /*Mutable=*/false,
5790 /*InitStyle=*/ICIS_NoInit);
5791 Anon->setImplicit();
5792
5793 // Add the anonymous struct object to the current context.
5794 CurContext->addDecl(Anon);
5795
5796 // Inject the members of the anonymous struct into the current
5797 // context and into the identifier resolver chain for name lookup
5798 // purposes.
5799 SmallVector<NamedDecl*, 2> Chain;
5800 Chain.push_back(Anon);
5801
5802 RecordDecl *RecordDef = Record->getDefinition();
5803 if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5804 diag::err_field_incomplete_or_sizeless) ||
5805 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5806 AS_none, Chain)) {
5807 Anon->setInvalidDecl();
5808 ParentDecl->setInvalidDecl();
5809 }
5810
5811 return Anon;
5812}
5813
5814/// GetNameForDeclarator - Determine the full declaration name for the
5815/// given Declarator.
5816DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5817 return GetNameFromUnqualifiedId(D.getName());
5818}
5819
5820/// Retrieves the declaration name from a parsed unqualified-id.
5821DeclarationNameInfo
5822Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5823 DeclarationNameInfo NameInfo;
5824 NameInfo.setLoc(Name.StartLocation);
5825
5826 switch (Name.getKind()) {
5827
5828 case UnqualifiedIdKind::IK_ImplicitSelfParam:
5829 case UnqualifiedIdKind::IK_Identifier:
5830 NameInfo.setName(Name.Identifier);
5831 return NameInfo;
5832
5833 case UnqualifiedIdKind::IK_DeductionGuideName: {
5834 // C++ [temp.deduct.guide]p3:
5835 // The simple-template-id shall name a class template specialization.
5836 // The template-name shall be the same identifier as the template-name
5837 // of the simple-template-id.
5838 // These together intend to imply that the template-name shall name a
5839 // class template.
5840 // FIXME: template<typename T> struct X {};
5841 // template<typename T> using Y = X<T>;
5842 // Y(int) -> Y<int>;
5843 // satisfies these rules but does not name a class template.
5844 TemplateName TN = Name.TemplateName.get().get();
5845 auto *Template = TN.getAsTemplateDecl();
5846 if (!Template || !isa<ClassTemplateDecl>(Template)) {
5847 Diag(Name.StartLocation,
5848 diag::err_deduction_guide_name_not_class_template)
5849 << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5850 if (Template)
5851 Diag(Template->getLocation(), diag::note_template_decl_here);
5852 return DeclarationNameInfo();
5853 }
5854
5855 NameInfo.setName(
5856 Context.DeclarationNames.getCXXDeductionGuideName(Template));
5857 return NameInfo;
5858 }
5859
5860 case UnqualifiedIdKind::IK_OperatorFunctionId:
5861 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5862 Name.OperatorFunctionId.Operator));
5863 NameInfo.setCXXOperatorNameRange(SourceRange(
5864 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5865 return NameInfo;
5866
5867 case UnqualifiedIdKind::IK_LiteralOperatorId:
5868 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5869 Name.Identifier));
5870 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5871 return NameInfo;
5872
5873 case UnqualifiedIdKind::IK_ConversionFunctionId: {
5874 TypeSourceInfo *TInfo;
5875 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5876 if (Ty.isNull())
5877 return DeclarationNameInfo();
5878 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5879 Context.getCanonicalType(Ty)));
5880 NameInfo.setNamedTypeInfo(TInfo);
5881 return NameInfo;
5882 }
5883
5884 case UnqualifiedIdKind::IK_ConstructorName: {
5885 TypeSourceInfo *TInfo;
5886 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5887 if (Ty.isNull())
5888 return DeclarationNameInfo();
5889 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5890 Context.getCanonicalType(Ty)));
5891 NameInfo.setNamedTypeInfo(TInfo);
5892 return NameInfo;
5893 }
5894
5895 case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5896 // In well-formed code, we can only have a constructor
5897 // template-id that refers to the current context, so go there
5898 // to find the actual type being constructed.
5899 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5900 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5901 return DeclarationNameInfo();
5902
5903 // Determine the type of the class being constructed.
5904 QualType CurClassType = Context.getTypeDeclType(CurClass);
5905
5906 // FIXME: Check two things: that the template-id names the same type as
5907 // CurClassType, and that the template-id does not occur when the name
5908 // was qualified.
5909
5910 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5911 Context.getCanonicalType(CurClassType)));
5912 // FIXME: should we retrieve TypeSourceInfo?
5913 NameInfo.setNamedTypeInfo(nullptr);
5914 return NameInfo;
5915 }
5916
5917 case UnqualifiedIdKind::IK_DestructorName: {
5918 TypeSourceInfo *TInfo;
5919 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5920 if (Ty.isNull())
5921 return DeclarationNameInfo();
5922 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5923 Context.getCanonicalType(Ty)));
5924 NameInfo.setNamedTypeInfo(TInfo);
5925 return NameInfo;
5926 }
5927
5928 case UnqualifiedIdKind::IK_TemplateId: {
5929 TemplateName TName = Name.TemplateId->Template.get();
5930 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5931 return Context.getNameForTemplate(TName, TNameLoc);
5932 }
5933
5934 } // switch (Name.getKind())
5935
5936 llvm_unreachable("Unknown name kind")::llvm::llvm_unreachable_internal("Unknown name kind", "clang/lib/Sema/SemaDecl.cpp"
, 5936)
;
5937}
5938
5939static QualType getCoreType(QualType Ty) {
5940 do {
5941 if (Ty->isPointerType() || Ty->isReferenceType())
5942 Ty = Ty->getPointeeType();
5943 else if (Ty->isArrayType())
5944 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5945 else
5946 return Ty.withoutLocalFastQualifiers();
5947 } while (true);
5948}
5949
5950/// hasSimilarParameters - Determine whether the C++ functions Declaration
5951/// and Definition have "nearly" matching parameters. This heuristic is
5952/// used to improve diagnostics in the case where an out-of-line function
5953/// definition doesn't match any declaration within the class or namespace.
5954/// Also sets Params to the list of indices to the parameters that differ
5955/// between the declaration and the definition. If hasSimilarParameters
5956/// returns true and Params is empty, then all of the parameters match.
5957static bool hasSimilarParameters(ASTContext &Context,
5958 FunctionDecl *Declaration,
5959 FunctionDecl *Definition,
5960 SmallVectorImpl<unsigned> &Params) {
5961 Params.clear();
5962 if (Declaration->param_size() != Definition->param_size())
5963 return false;
5964 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5965 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5966 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5967
5968 // The parameter types are identical
5969 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5970 continue;
5971
5972 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5973 QualType DefParamBaseTy = getCoreType(DefParamTy);
5974 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5975 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5976
5977 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5978 (DeclTyName && DeclTyName == DefTyName))
5979 Params.push_back(Idx);
5980 else // The two parameters aren't even close
5981 return false;
5982 }
5983
5984 return true;
5985}
5986
5987/// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
5988/// declarator needs to be rebuilt in the current instantiation.
5989/// Any bits of declarator which appear before the name are valid for
5990/// consideration here. That's specifically the type in the decl spec
5991/// and the base type in any member-pointer chunks.
5992static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5993 DeclarationName Name) {
5994 // The types we specifically need to rebuild are:
5995 // - typenames, typeofs, and decltypes
5996 // - types which will become injected class names
5997 // Of course, we also need to rebuild any type referencing such a
5998 // type. It's safest to just say "dependent", but we call out a
5999 // few cases here.
6000
6001 DeclSpec &DS = D.getMutableDeclSpec();
6002 switch (DS.getTypeSpecType()) {
6003 case DeclSpec::TST_typename:
6004 case DeclSpec::TST_typeofType:
6005 case DeclSpec::TST_typeof_unqualType:
6006#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
6007#include "clang/Basic/TransformTypeTraits.def"
6008 case DeclSpec::TST_atomic: {
6009 // Grab the type from the parser.
6010 TypeSourceInfo *TSI = nullptr;
6011 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
6012 if (T.isNull() || !T->isInstantiationDependentType()) break;
6013
6014 // Make sure there's a type source info. This isn't really much
6015 // of a waste; most dependent types should have type source info
6016 // attached already.
6017 if (!TSI)
6018 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
6019
6020 // Rebuild the type in the current instantiation.
6021 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
6022 if (!TSI) return true;
6023
6024 // Store the new type back in the decl spec.
6025 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
6026 DS.UpdateTypeRep(LocType);
6027 break;
6028 }
6029
6030 case DeclSpec::TST_decltype:
6031 case DeclSpec::TST_typeof_unqualExpr:
6032 case DeclSpec::TST_typeofExpr: {
6033 Expr *E = DS.getRepAsExpr();
6034 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
6035 if (Result.isInvalid()) return true;
6036 DS.UpdateExprRep(Result.get());
6037 break;
6038 }
6039
6040 default:
6041 // Nothing to do for these decl specs.
6042 break;
6043 }
6044
6045 // It doesn't matter what order we do this in.
6046 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
6047 DeclaratorChunk &Chunk = D.getTypeObject(I);
6048
6049 // The only type information in the declarator which can come
6050 // before the declaration name is the base type of a member
6051 // pointer.
6052 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
6053 continue;
6054
6055 // Rebuild the scope specifier in-place.
6056 CXXScopeSpec &SS = Chunk.Mem.Scope();
6057 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
6058 return true;
6059 }
6060
6061 return false;
6062}
6063
6064/// Returns true if the declaration is declared in a system header or from a
6065/// system macro.
6066static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
6067 return SM.isInSystemHeader(D->getLocation()) ||
6068 SM.isInSystemMacro(D->getLocation());
6069}
6070
6071void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
6072 // Avoid warning twice on the same identifier, and don't warn on redeclaration
6073 // of system decl.
6074 if (D->getPreviousDecl() || D->isImplicit())
6075 return;
6076 ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
6077 if (Status != ReservedIdentifierStatus::NotReserved &&
6078 !isFromSystemHeader(Context.getSourceManager(), D)) {
6079 Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
6080 << D << static_cast<int>(Status);
6081 }
6082}
6083
6084Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
6085 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
6086
6087 // Check if we are in an `omp begin/end declare variant` scope. Handle this
6088 // declaration only if the `bind_to_declaration` extension is set.
6089 SmallVector<FunctionDecl *, 4> Bases;
6090 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
6091 if (getOMPTraitInfoForSurroundingScope()->isExtensionActive(llvm::omp::TraitProperty::
6092 implementation_extension_bind_to_declaration))
6093 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
6094 S, D, MultiTemplateParamsArg(), Bases);
6095
6096 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
6097
6098 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
6099 Dcl && Dcl->getDeclContext()->isFileContext())
6100 Dcl->setTopLevelDeclInObjCContainer();
6101
6102 if (!Bases.empty())
6103 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
6104
6105 return Dcl;
6106}
6107
6108/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
6109/// If T is the name of a class, then each of the following shall have a
6110/// name different from T:
6111/// - every static data member of class T;
6112/// - every member function of class T
6113/// - every member of class T that is itself a type;
6114/// \returns true if the declaration name violates these rules.
6115bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
6116 DeclarationNameInfo NameInfo) {
6117 DeclarationName Name = NameInfo.getName();
6118
6119 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
6120 while (Record && Record->isAnonymousStructOrUnion())
6121 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
6122 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6123 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
6124 return true;
6125 }
6126
6127 return false;
6128}
6129
6130/// Diagnose a declaration whose declarator-id has the given
6131/// nested-name-specifier.
6132///
6133/// \param SS The nested-name-specifier of the declarator-id.
6134///
6135/// \param DC The declaration context to which the nested-name-specifier
6136/// resolves.
6137///
6138/// \param Name The name of the entity being declared.
6139///
6140/// \param Loc The location of the name of the entity being declared.
6141///
6142/// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
6143/// we're declaring an explicit / partial specialization / instantiation.
6144///
6145/// \returns true if we cannot safely recover from this error, false otherwise.
6146bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
6147 DeclarationName Name,
6148 SourceLocation Loc, bool IsTemplateId) {
6149 DeclContext *Cur = CurContext;
6150 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
6151 Cur = Cur->getParent();
6152
6153 // If the user provided a superfluous scope specifier that refers back to the
6154 // class in which the entity is already declared, diagnose and ignore it.
6155 //
6156 // class X {
6157 // void X::f();
6158 // };
6159 //
6160 // Note, it was once ill-formed to give redundant qualification in all
6161 // contexts, but that rule was removed by DR482.
6162 if (Cur->Equals(DC)) {
6163 if (Cur->isRecord()) {
6164 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6165 : diag::err_member_extra_qualification)
6166 << Name << FixItHint::CreateRemoval(SS.getRange());
6167 SS.clear();
6168 } else {
6169 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
6170 }
6171 return false;
6172 }
6173
6174 // Check whether the qualifying scope encloses the scope of the original
6175 // declaration. For a template-id, we perform the checks in
6176 // CheckTemplateSpecializationScope.
6177 if (!Cur->Encloses(DC) && !IsTemplateId) {
6178 if (Cur->isRecord())
6179 Diag(Loc, diag::err_member_qualification)
6180 << Name << SS.getRange();
6181 else if (isa<TranslationUnitDecl>(DC))
6182 Diag(Loc, diag::err_invalid_declarator_global_scope)
6183 << Name << SS.getRange();
6184 else if (isa<FunctionDecl>(Cur))
6185 Diag(Loc, diag::err_invalid_declarator_in_function)
6186 << Name << SS.getRange();
6187 else if (isa<BlockDecl>(Cur))
6188 Diag(Loc, diag::err_invalid_declarator_in_block)
6189 << Name << SS.getRange();
6190 else if (isa<ExportDecl>(Cur)) {
6191 if (!isa<NamespaceDecl>(DC))
6192 Diag(Loc, diag::err_export_non_namespace_scope_name)
6193 << Name << SS.getRange();
6194 else
6195 // The cases that DC is not NamespaceDecl should be handled in
6196 // CheckRedeclarationExported.
6197 return false;
6198 } else
6199 Diag(Loc, diag::err_invalid_declarator_scope)
6200 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
6201
6202 return true;
6203 }
6204
6205 if (Cur->isRecord()) {
6206 // Cannot qualify members within a class.
6207 Diag(Loc, diag::err_member_qualification)
6208 << Name << SS.getRange();
6209 SS.clear();
6210
6211 // C++ constructors and destructors with incorrect scopes can break
6212 // our AST invariants by having the wrong underlying types. If
6213 // that's the case, then drop this declaration entirely.
6214 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
6215 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
6216 !Context.hasSameType(Name.getCXXNameType(),
6217 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
6218 return true;
6219
6220 return false;
6221 }
6222
6223 // C++11 [dcl.meaning]p1:
6224 // [...] "The nested-name-specifier of the qualified declarator-id shall
6225 // not begin with a decltype-specifer"
6226 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
6227 while (SpecLoc.getPrefix())
6228 SpecLoc = SpecLoc.getPrefix();
6229 if (isa_and_nonnull<DecltypeType>(
6230 SpecLoc.getNestedNameSpecifier()->getAsType()))
6231 Diag(Loc, diag::err_decltype_in_declarator)
6232 << SpecLoc.getTypeLoc().getSourceRange();
6233
6234 return false;
6235}
6236
6237NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
6238 MultiTemplateParamsArg TemplateParamLists) {
6239 // TODO: consider using NameInfo for diagnostic.
6240 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6241 DeclarationName Name = NameInfo.getName();
6242
6243 // All of these full declarators require an identifier. If it doesn't have
6244 // one, the ParsedFreeStandingDeclSpec action should be used.
6245 if (D.isDecompositionDeclarator()) {
6246 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6247 } else if (!Name) {
6248 if (!D.isInvalidType()) // Reject this if we think it is valid.
6249 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6250 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
6251 return nullptr;
6252 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
6253 return nullptr;
6254
6255 // The scope passed in may not be a decl scope. Zip up the scope tree until
6256 // we find one that is.
6257 while ((S->getFlags() & Scope::DeclScope) == 0 ||
6258 (S->getFlags() & Scope::TemplateParamScope) != 0)
6259 S = S->getParent();
6260
6261 DeclContext *DC = CurContext;
6262 if (D.getCXXScopeSpec().isInvalid())
6263 D.setInvalidType();
6264 else if (D.getCXXScopeSpec().isSet()) {
6265 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
6266 UPPC_DeclarationQualifier))
6267 return nullptr;
6268
6269 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6270 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
6271 if (!DC || isa<EnumDecl>(DC)) {
6272 // If we could not compute the declaration context, it's because the
6273 // declaration context is dependent but does not refer to a class,
6274 // class template, or class template partial specialization. Complain
6275 // and return early, to avoid the coming semantic disaster.
6276 Diag(D.getIdentifierLoc(),
6277 diag::err_template_qualified_declarator_no_match)
6278 << D.getCXXScopeSpec().getScopeRep()
6279 << D.getCXXScopeSpec().getRange();
6280 return nullptr;
6281 }
6282 bool IsDependentContext = DC->isDependentContext();
6283
6284 if (!IsDependentContext &&
6285 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
6286 return nullptr;
6287
6288 // If a class is incomplete, do not parse entities inside it.
6289 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
6290 Diag(D.getIdentifierLoc(),
6291 diag::err_member_def_undefined_record)
6292 << Name << DC << D.getCXXScopeSpec().getRange();
6293 return nullptr;
6294 }
6295 if (!D.getDeclSpec().isFriendSpecified()) {
6296 if (diagnoseQualifiedDeclaration(
6297 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
6298 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
6299 if (DC->isRecord())
6300 return nullptr;
6301
6302 D.setInvalidType();
6303 }
6304 }
6305
6306 // Check whether we need to rebuild the type of the given
6307 // declaration in the current instantiation.
6308 if (EnteringContext && IsDependentContext &&
6309 TemplateParamLists.size() != 0) {
6310 ContextRAII SavedContext(*this, DC);
6311 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
6312 D.setInvalidType();
6313 }
6314 }
6315
6316 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6317 QualType R = TInfo->getType();
6318
6319 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6320 UPPC_DeclarationType))
6321 D.setInvalidType();
6322
6323 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6324 forRedeclarationInCurContext());
6325
6326 // See if this is a redefinition of a variable in the same scope.
6327 if (!D.getCXXScopeSpec().isSet()) {
6328 bool IsLinkageLookup = false;
6329 bool CreateBuiltins = false;
6330
6331 // If the declaration we're planning to build will be a function
6332 // or object with linkage, then look for another declaration with
6333 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6334 //
6335 // If the declaration we're planning to build will be declared with
6336 // external linkage in the translation unit, create any builtin with
6337 // the same name.
6338 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
6339 /* Do nothing*/;
6340 else if (CurContext->isFunctionOrMethod() &&
6341 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
6342 R->isFunctionType())) {
6343 IsLinkageLookup = true;
6344 CreateBuiltins =
6345 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6346 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6347 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
6348 CreateBuiltins = true;
6349
6350 if (IsLinkageLookup) {
6351 Previous.clear(LookupRedeclarationWithLinkage);
6352 Previous.setRedeclarationKind(ForExternalRedeclaration);
6353 }
6354
6355 LookupName(Previous, S, CreateBuiltins);
6356 } else { // Something like "int foo::x;"
6357 LookupQualifiedName(Previous, DC);
6358
6359 // C++ [dcl.meaning]p1:
6360 // When the declarator-id is qualified, the declaration shall refer to a
6361 // previously declared member of the class or namespace to which the
6362 // qualifier refers (or, in the case of a namespace, of an element of the
6363 // inline namespace set of that namespace (7.3.1)) or to a specialization
6364 // thereof; [...]
6365 //
6366 // Note that we already checked the context above, and that we do not have
6367 // enough information to make sure that Previous contains the declaration
6368 // we want to match. For example, given:
6369 //
6370 // class X {
6371 // void f();
6372 // void f(float);
6373 // };
6374 //
6375 // void X::f(int) { } // ill-formed
6376 //
6377 // In this case, Previous will point to the overload set
6378 // containing the two f's declared in X, but neither of them
6379 // matches.
6380
6381 // C++ [dcl.meaning]p1:
6382 // [...] the member shall not merely have been introduced by a
6383 // using-declaration in the scope of the class or namespace nominated by
6384 // the nested-name-specifier of the declarator-id.
6385 RemoveUsingDecls(Previous);
6386 }
6387
6388 if (Previous.isSingleResult() &&
6389 Previous.getFoundDecl()->isTemplateParameter()) {
6390 // Maybe we will complain about the shadowed template parameter.
6391 if (!D.isInvalidType())
6392 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
6393 Previous.getFoundDecl());
6394
6395 // Just pretend that we didn't see the previous declaration.
6396 Previous.clear();
6397 }
6398
6399 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6400 // Forget that the previous declaration is the injected-class-name.
6401 Previous.clear();
6402
6403 // In C++, the previous declaration we find might be a tag type
6404 // (class or enum). In this case, the new declaration will hide the
6405 // tag type. Note that this applies to functions, function templates, and
6406 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6407 if (Previous.isSingleTagDecl() &&
6408 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6409 (TemplateParamLists.size() == 0 || R->isFunctionType()))
6410 Previous.clear();
6411
6412 // Check that there are no default arguments other than in the parameters
6413 // of a function declaration (C++ only).
6414 if (getLangOpts().CPlusPlus)
6415 CheckExtraCXXDefaultArguments(D);
6416
6417 NamedDecl *New;
6418
6419 bool AddToScope = true;
6420 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6421 if (TemplateParamLists.size()) {
6422 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6423 return nullptr;
6424 }
6425
6426 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6427 } else if (R->isFunctionType()) {
6428 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6429 TemplateParamLists,
6430 AddToScope);
6431 } else {
6432 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6433 AddToScope);
6434 }
6435
6436 if (!New)
6437 return nullptr;
6438
6439 // If this has an identifier and is not a function template specialization,
6440 // add it to the scope stack.
6441 if (New->getDeclName() && AddToScope)
6442 PushOnScopeChains(New, S);
6443
6444 if (isInOpenMPDeclareTargetContext())
6445 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
6446
6447 return New;
6448}
6449
6450/// Helper method to turn variable array types into constant array
6451/// types in certain situations which would otherwise be errors (for
6452/// GCC compatibility).
6453static QualType TryToFixInvalidVariablyModifiedType(QualType T,
6454 ASTContext &Context,
6455 bool &SizeIsNegative,
6456 llvm::APSInt &Oversized) {
6457 // This method tries to turn a variable array into a constant
6458 // array even when the size isn't an ICE. This is necessary
6459 // for compatibility with code that depends on gcc's buggy
6460 // constant expression folding, like struct {char x[(int)(char*)2];}
6461 SizeIsNegative = false;
6462 Oversized = 0;
6463
6464 if (T->isDependentType())
6465 return QualType();
6466
6467 QualifierCollector Qs;
6468 const Type *Ty = Qs.strip(T);
6469
6470 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6471 QualType Pointee = PTy->getPointeeType();
6472 QualType FixedType =
6473 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6474 Oversized);
6475 if (FixedType.isNull()) return FixedType;
6476 FixedType = Context.getPointerType(FixedType);
6477 return Qs.apply(Context, FixedType);
6478 }
6479 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6480 QualType Inner = PTy->getInnerType();
6481 QualType FixedType =
6482 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6483 Oversized);
6484 if (FixedType.isNull()) return FixedType;
6485 FixedType = Context.getParenType(FixedType);
6486 return Qs.apply(Context, FixedType);
6487 }
6488
6489 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6490 if (!VLATy)
6491 return QualType();
6492
6493 QualType ElemTy = VLATy->getElementType();
6494 if (ElemTy->isVariablyModifiedType()) {
6495 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6496 SizeIsNegative, Oversized);
6497 if (ElemTy.isNull())
6498 return QualType();
6499 }
6500
6501 Expr::EvalResult Result;
6502 if (!VLATy->getSizeExpr() ||
6503 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6504 return QualType();
6505
6506 llvm::APSInt Res = Result.Val.getInt();
6507
6508 // Check whether the array size is negative.
6509 if (Res.isSigned() && Res.isNegative()) {
6510 SizeIsNegative = true;
6511 return QualType();
6512 }
6513
6514 // Check whether the array is too large to be addressed.
6515 unsigned ActiveSizeBits =
6516 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6517 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6518 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6519 : Res.getActiveBits();
6520 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6521 Oversized = Res;
6522 return QualType();
6523 }
6524
6525 QualType FoldedArrayType = Context.getConstantArrayType(
6526 ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
6527 return Qs.apply(Context, FoldedArrayType);
6528}
6529
6530static void
6531FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6532 SrcTL = SrcTL.getUnqualifiedLoc();
6533 DstTL = DstTL.getUnqualifiedLoc();
6534 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6535 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6536 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6537 DstPTL.getPointeeLoc());
6538 DstPTL.setStarLoc(SrcPTL.getStarLoc());
6539 return;
6540 }
6541 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6542 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6543 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6544 DstPTL.getInnerLoc());
6545 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6546 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6547 return;
6548 }
6549 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6550 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6551 TypeLoc SrcElemTL = SrcATL.getElementLoc();
6552 TypeLoc DstElemTL = DstATL.getElementLoc();
6553 if (VariableArrayTypeLoc SrcElemATL =
6554 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6555 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6556 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6557 } else {
6558 DstElemTL.initializeFullCopy(SrcElemTL);
6559 }
6560 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6561 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6562 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6563}
6564
6565/// Helper method to turn variable array types into constant array
6566/// types in certain situations which would otherwise be errors (for
6567/// GCC compatibility).
6568static TypeSourceInfo*
6569TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6570 ASTContext &Context,
6571 bool &SizeIsNegative,
6572 llvm::APSInt &Oversized) {
6573 QualType FixedTy
6574 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6575 SizeIsNegative, Oversized);
6576 if (FixedTy.isNull())
6577 return nullptr;
6578 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6579 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6580 FixedTInfo->getTypeLoc());
6581 return FixedTInfo;
6582}
6583
6584/// Attempt to fold a variable-sized type to a constant-sized type, returning
6585/// true if we were successful.
6586bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6587 QualType &T, SourceLocation Loc,
6588 unsigned FailedFoldDiagID) {
6589 bool SizeIsNegative;
6590 llvm::APSInt Oversized;
6591 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6592 TInfo, Context, SizeIsNegative, Oversized);
6593 if (FixedTInfo) {
6594 Diag(Loc, diag::ext_vla_folded_to_constant);
6595 TInfo = FixedTInfo;
6596 T = FixedTInfo->getType();
6597 return true;
6598 }
6599
6600 if (SizeIsNegative)
6601 Diag(Loc, diag::err_typecheck_negative_array_size);
6602 else if (Oversized.getBoolValue())
6603 Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6604 else if (FailedFoldDiagID)
6605 Diag(Loc, FailedFoldDiagID);
6606 return false;
6607}
6608
6609/// Register the given locally-scoped extern "C" declaration so
6610/// that it can be found later for redeclarations. We include any extern "C"
6611/// declaration that is not visible in the translation unit here, not just
6612/// function-scope declarations.
6613void
6614Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6615 if (!getLangOpts().CPlusPlus &&
6616 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6617 // Don't need to track declarations in the TU in C.
6618 return;
6619
6620 // Note that we have a locally-scoped external with this name.
6621 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6622}
6623
6624NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6625 // FIXME: We can have multiple results via __attribute__((overloadable)).
6626 auto Result = Context.getExternCContextDecl()->lookup(Name);
6627 return Result.empty() ? nullptr : *Result.begin();
6628}
6629
6630/// Diagnose function specifiers on a declaration of an identifier that
6631/// does not identify a function.
6632void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6633 // FIXME: We should probably indicate the identifier in question to avoid
6634 // confusion for constructs like "virtual int a(), b;"
6635 if (DS.isVirtualSpecified())
6636 Diag(DS.getVirtualSpecLoc(),
6637 diag::err_virtual_non_function);
6638
6639 if (DS.hasExplicitSpecifier())
6640 Diag(DS.getExplicitSpecLoc(),
6641 diag::err_explicit_non_function);
6642
6643 if (DS.isNoreturnSpecified())
6644 Diag(DS.getNoreturnSpecLoc(),
6645 diag::err_noreturn_non_function);
6646}
6647
6648NamedDecl*
6649Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6650 TypeSourceInfo *TInfo, LookupResult &Previous) {
6651 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6652 if (D.getCXXScopeSpec().isSet()) {
6653 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6654 << D.getCXXScopeSpec().getRange();
6655 D.setInvalidType();
6656 // Pretend we didn't see the scope specifier.
6657 DC = CurContext;
6658 Previous.clear();
6659 }
6660
6661 DiagnoseFunctionSpecifiers(D.getDeclSpec());
6662
6663 if (D.getDeclSpec().isInlineSpecified())
6664 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6665 << getLangOpts().CPlusPlus17;
6666 if (D.getDeclSpec().hasConstexprSpecifier())
6667 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6668 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6669
6670 if (D.getName().getKind() != UnqualifiedIdKind::IK_Identifier) {
6671 if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName)
6672 Diag(D.getName().StartLocation,
6673 diag::err_deduction_guide_invalid_specifier)
6674 << "typedef";
6675 else
6676 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6677 << D.getName().getSourceRange();
6678 return nullptr;
6679 }
6680
6681 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6682 if (!NewTD) return nullptr;
6683
6684 // Handle attributes prior to checking for duplicates in MergeVarDecl
6685 ProcessDeclAttributes(S, NewTD, D);
6686
6687 CheckTypedefForVariablyModifiedType(S, NewTD);
6688
6689 bool Redeclaration = D.isRedeclaration();
6690 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6691 D.setRedeclaration(Redeclaration);
6692 return ND;
6693}
6694
6695void
6696Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6697 // C99 6.7.7p2: If a typedef name specifies a variably modified type
6698 // then it shall have block scope.
6699 // Note that variably modified types must be fixed before merging the decl so
6700 // that redeclarations will match.
6701 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6702 QualType T = TInfo->getType();
6703 if (T->isVariablyModifiedType()) {
6704 setFunctionHasBranchProtectedScope();
6705
6706 if (S->getFnParent() == nullptr) {
6707 bool SizeIsNegative;
6708 llvm::APSInt Oversized;
6709 TypeSourceInfo *FixedTInfo =
6710 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6711 SizeIsNegative,
6712 Oversized);
6713 if (FixedTInfo) {
6714 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6715 NewTD->setTypeSourceInfo(FixedTInfo);
6716 } else {
6717 if (SizeIsNegative)
6718 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6719 else if (T->isVariableArrayType())
6720 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6721 else if (Oversized.getBoolValue())
6722 Diag(NewTD->getLocation(), diag::err_array_too_large)
6723 << toString(Oversized, 10);
6724 else
6725 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6726 NewTD->setInvalidDecl();
6727 }
6728 }
6729 }
6730}
6731
6732/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6733/// declares a typedef-name, either using the 'typedef' type specifier or via
6734/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6735NamedDecl*
6736Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6737 LookupResult &Previous, bool &Redeclaration) {
6738
6739 // Find the shadowed declaration before filtering for scope.
6740 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6741
6742 // Merge the decl with the existing one if appropriate. If the decl is
6743 // in an outer scope, it isn't the same thing.
6744 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6745 /*AllowInlineNamespace*/false);
6746 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6747 if (!Previous.empty()) {
6748 Redeclaration = true;
6749 MergeTypedefNameDecl(S, NewTD, Previous);
6750 } else {
6751 inferGslPointerAttribute(NewTD);
6752 }
6753
6754 if (ShadowedDecl && !Redeclaration)
6755 CheckShadow(NewTD, ShadowedDecl, Previous);
6756
6757 // If this is the C FILE type, notify the AST context.
6758 if (IdentifierInfo *II = NewTD->getIdentifier())
6759 if (!NewTD->isInvalidDecl() &&
6760 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6761 if (II->isStr("FILE"))
6762 Context.setFILEDecl(NewTD);
6763 else if (II->isStr("jmp_buf"))
6764 Context.setjmp_bufDecl(NewTD);
6765 else if (II->isStr("sigjmp_buf"))
6766 Context.setsigjmp_bufDecl(NewTD);
6767 else if (II->isStr("ucontext_t"))
6768 Context.setucontext_tDecl(NewTD);
6769 }
6770
6771 return NewTD;
6772}
6773
6774/// Determines whether the given declaration is an out-of-scope
6775/// previous declaration.
6776///
6777/// This routine should be invoked when name lookup has found a
6778/// previous declaration (PrevDecl) that is not in the scope where a
6779/// new declaration by the same name is being introduced. If the new
6780/// declaration occurs in a local scope, previous declarations with
6781/// linkage may still be considered previous declarations (C99
6782/// 6.2.2p4-5, C++ [basic.link]p6).
6783///
6784/// \param PrevDecl the previous declaration found by name
6785/// lookup
6786///
6787/// \param DC the context in which the new declaration is being
6788/// declared.
6789///
6790/// \returns true if PrevDecl is an out-of-scope previous declaration
6791/// for a new delcaration with the same name.
6792static bool
6793isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6794 ASTContext &Context) {
6795 if (!PrevDecl)
6796 return false;
6797
6798 if (!PrevDecl->hasLinkage())
6799 return false;
6800
6801 if (Context.getLangOpts().CPlusPlus) {
6802 // C++ [basic.link]p6:
6803 // If there is a visible declaration of an entity with linkage
6804 // having the same name and type, ignoring entities declared
6805 // outside the innermost enclosing namespace scope, the block
6806 // scope declaration declares that same entity and receives the
6807 // linkage of the previous declaration.
6808 DeclContext *OuterContext = DC->getRedeclContext();
6809 if (!OuterContext->isFunctionOrMethod())
6810 // This rule only applies to block-scope declarations.
6811 return false;
6812
6813 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6814 if (PrevOuterContext->isRecord())
6815 // We found a member function: ignore it.
6816 return false;
6817
6818 // Find the innermost enclosing namespace for the new and
6819 // previous declarations.
6820 OuterContext = OuterContext->getEnclosingNamespaceContext();
6821 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6822
6823 // The previous declaration is in a different namespace, so it
6824 // isn't the same function.
6825 if (!OuterContext->Equals(PrevOuterContext))
6826 return false;
6827 }
6828
6829 return true;
6830}
6831
6832static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6833 CXXScopeSpec &SS = D.getCXXScopeSpec();
6834 if (!SS.isSet()) return;
6835 DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6836}
6837
6838bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6839 QualType type = decl->getType();
6840 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6841 if (lifetime == Qualifiers::OCL_Autoreleasing) {
6842 // Various kinds of declaration aren't allowed to be __autoreleasing.
6843 unsigned kind = -1U;
6844 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6845 if (var->hasAttr<BlocksAttr>())
6846 kind = 0; // __block
6847 else if (!var->hasLocalStorage())
6848 kind = 1; // global
6849 } else if (isa<ObjCIvarDecl>(decl)) {
6850 kind = 3; // ivar
6851 } else if (isa<FieldDecl>(decl)) {
6852 kind = 2; // field
6853 }
6854
6855 if (kind != -1U) {
6856 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6857 << kind;
6858 }
6859 } else if (lifetime == Qualifiers::OCL_None) {
6860 // Try to infer lifetime.
6861 if (!type->isObjCLifetimeType())
6862 return false;
6863
6864 lifetime = type->getObjCARCImplicitLifetime();
6865 type = Context.getLifetimeQualifiedType(type, lifetime);
6866 decl->setType(type);
6867 }
6868
6869 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6870 // Thread-local variables cannot have lifetime.
6871 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6872 var->getTLSKind()) {
6873 Diag(var->getLocation(), diag::err_arc_thread_ownership)
6874 << var->getType();
6875 return true;
6876 }
6877 }
6878
6879 return false;
6880}
6881
6882void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6883 if (Decl->getType().hasAddressSpace())
6884 return;
6885 if (Decl->getType()->isDependentType())
6886 return;
6887 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6888 QualType Type = Var->getType();
6889 if (Type->isSamplerT() || Type->isVoidType())
6890 return;
6891 LangAS ImplAS = LangAS::opencl_private;
6892 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
6893 // __opencl_c_program_scope_global_variables feature, the address space
6894 // for a variable at program scope or a static or extern variable inside
6895 // a function are inferred to be __global.
6896 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
6897 Var->hasGlobalStorage())
6898 ImplAS = LangAS::opencl_global;
6899 // If the original type from a decayed type is an array type and that array
6900 // type has no address space yet, deduce it now.
6901 if (auto DT = dyn_cast<DecayedType>(Type)) {
6902 auto OrigTy = DT->getOriginalType();
6903 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6904 // Add the address space to the original array type and then propagate
6905 // that to the element type through `getAsArrayType`.
6906 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6907 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6908 // Re-generate the decayed type.
6909 Type = Context.getDecayedType(OrigTy);
6910 }
6911 }
6912 Type = Context.getAddrSpaceQualType(Type, ImplAS);
6913 // Apply any qualifiers (including address space) from the array type to
6914 // the element type. This implements C99 6.7.3p8: "If the specification of
6915 // an array type includes any type qualifiers, the element type is so
6916 // qualified, not the array type."
6917 if (Type->isArrayType())
6918 Type = QualType(Context.getAsArrayType(Type), 0);
6919 Decl->setType(Type);
6920 }
6921}
6922
6923static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6924 // Ensure that an auto decl is deduced otherwise the checks below might cache
6925 // the wrong linkage.
6926 assert(S.ParsingInitForAutoVars.count(&ND) == 0)(static_cast <bool> (S.ParsingInitForAutoVars.count(&
ND) == 0) ? void (0) : __assert_fail ("S.ParsingInitForAutoVars.count(&ND) == 0"
, "clang/lib/Sema/SemaDecl.cpp", 6926, __extension__ __PRETTY_FUNCTION__
))
;
6927
6928 // 'weak' only applies to declarations with external linkage.
6929 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6930 if (!ND.isExternallyVisible()) {
6931 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6932 ND.dropAttr<WeakAttr>();
6933 }
6934 }
6935 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6936 if (ND.isExternallyVisible()) {
6937 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6938 ND.dropAttr<WeakRefAttr>();
6939 ND.dropAttr<AliasAttr>();
6940 }
6941 }
6942
6943 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6944 if (VD->hasInit()) {
6945 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6946 assert(VD->isThisDeclarationADefinition() &&(static_cast <bool> (VD->isThisDeclarationADefinition
() && !VD->isExternallyVisible() && "Broken AliasAttr handled late!"
) ? void (0) : __assert_fail ("VD->isThisDeclarationADefinition() && !VD->isExternallyVisible() && \"Broken AliasAttr handled late!\""
, "clang/lib/Sema/SemaDecl.cpp", 6947, __extension__ __PRETTY_FUNCTION__
))
6947 !VD->isExternallyVisible() && "Broken AliasAttr handled late!")(static_cast <bool> (VD->isThisDeclarationADefinition
() && !VD->isExternallyVisible() && "Broken AliasAttr handled late!"
) ? void (0) : __assert_fail ("VD->isThisDeclarationADefinition() && !VD->isExternallyVisible() && \"Broken AliasAttr handled late!\""
, "clang/lib/Sema/SemaDecl.cpp", 6947, __extension__ __PRETTY_FUNCTION__
))
;
6948 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6949 VD->dropAttr<AliasAttr>();
6950 }
6951 }
6952 }
6953
6954 // 'selectany' only applies to externally visible variable declarations.
6955 // It does not apply to functions.
6956 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6957 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6958 S.Diag(Attr->getLocation(),
6959 diag::err_attribute_selectany_non_extern_data);
6960 ND.dropAttr<SelectAnyAttr>();
6961 }
6962 }
6963
6964 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6965 auto *VD = dyn_cast<VarDecl>(&ND);
6966 bool IsAnonymousNS = false;
6967 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6968 if (VD) {
6969 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6970 while (NS && !IsAnonymousNS) {
6971 IsAnonymousNS = NS->isAnonymousNamespace();
6972 NS = dyn_cast<NamespaceDecl>(NS->getParent());
6973 }
6974 }
6975 // dll attributes require external linkage. Static locals may have external
6976 // linkage but still cannot be explicitly imported or exported.
6977 // In Microsoft mode, a variable defined in anonymous namespace must have
6978 // external linkage in order to be exported.
6979 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6980 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6981 (!AnonNSInMicrosoftMode &&
6982 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6983 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6984 << &ND << Attr;
6985 ND.setInvalidDecl();
6986 }
6987 }
6988
6989 // Check the attributes on the function type, if any.
6990 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6991 // Don't declare this variable in the second operand of the for-statement;
6992 // GCC miscompiles that by ending its lifetime before evaluating the
6993 // third operand. See gcc.gnu.org/PR86769.
6994 AttributedTypeLoc ATL;
6995 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6996 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6997 TL = ATL.getModifiedLoc()) {
6998 // The [[lifetimebound]] attribute can be applied to the implicit object
6999 // parameter of a non-static member function (other than a ctor or dtor)
7000 // by applying it to the function type.
7001 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
7002 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
7003 if (!MD || MD->isStatic()) {
7004 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
7005 << !MD << A->getRange();
7006 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
7007 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
7008 << isa<CXXDestructorDecl>(MD) << A->getRange();
7009 }
7010 }
7011 }
7012 }
7013}
7014
7015static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
7016 NamedDecl *NewDecl,
7017 bool IsSpecialization,
7018 bool IsDefinition) {
7019 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
7020 return;
7021
7022 bool IsTemplate = false;
7023 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
7024 OldDecl = OldTD->getTemplatedDecl();
7025 IsTemplate = true;
7026 if (!IsSpecialization)
7027 IsDefinition = false;
7028 }
7029 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
7030 NewDecl = NewTD->getTemplatedDecl();
7031 IsTemplate = true;
7032 }
7033
7034 if (!OldDecl || !NewDecl)
7035 return;
7036
7037 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
7038 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
7039 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
7040 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
7041
7042 // dllimport and dllexport are inheritable attributes so we have to exclude
7043 // inherited attribute instances.
7044 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
7045 (NewExportAttr && !NewExportAttr->isInherited());
7046
7047 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
7048 // the only exception being explicit specializations.
7049 // Implicitly generated declarations are also excluded for now because there
7050 // is no other way to switch these to use dllimport or dllexport.
7051 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
7052
7053 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
7054 // Allow with a warning for free functions and global variables.
7055 bool JustWarn = false;
7056 if (!OldDecl->isCXXClassMember()) {
7057 auto *VD = dyn_cast<VarDecl>(OldDecl);
7058 if (VD && !VD->getDescribedVarTemplate())
7059 JustWarn = true;
7060 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
7061 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
7062 JustWarn = true;
7063 }
7064
7065 // We cannot change a declaration that's been used because IR has already
7066 // been emitted. Dllimported functions will still work though (modulo
7067 // address equality) as they can use the thunk.
7068 if (OldDecl->isUsed())
7069 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
7070 JustWarn = false;
7071
7072 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7073 : diag::err_attribute_dll_redeclaration;
7074 S.Diag(NewDecl->getLocation(), DiagID)
7075 << NewDecl
7076 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7077 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7078 if (!JustWarn) {
7079 NewDecl->setInvalidDecl();
7080 return;
7081 }
7082 }
7083
7084 // A redeclaration is not allowed to drop a dllimport attribute, the only
7085 // exceptions being inline function definitions (except for function
7086 // templates), local extern declarations, qualified friend declarations or
7087 // special MSVC extension: in the last case, the declaration is treated as if
7088 // it were marked dllexport.
7089 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7090 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7091 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
7092 // Ignore static data because out-of-line definitions are diagnosed
7093 // separately.
7094 IsStaticDataMember = VD->isStaticDataMember();
7095 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7096 VarDecl::DeclarationOnly;
7097 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
7098 IsInline = FD->isInlined();
7099 IsQualifiedFriend = FD->getQualifier() &&
7100 FD->getFriendObjectKind() == Decl::FOK_Declared;
7101 }
7102
7103 if (OldImportAttr && !HasNewAttr &&
7104 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7105 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7106 if (IsMicrosoftABI && IsDefinition) {
7107 if (IsSpecialization) {
7108 S.Diag(
7109 NewDecl->getLocation(),
7110 diag::err_attribute_dllimport_function_specialization_definition);
7111 S.Diag(OldImportAttr->getLocation(), diag::note_attribute);
7112 NewDecl->dropAttr<DLLImportAttr>();
7113 } else {
7114 S.Diag(NewDecl->getLocation(),
7115 diag::warn_redeclaration_without_import_attribute)
7116 << NewDecl;
7117 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7118 NewDecl->dropAttr<DLLImportAttr>();
7119 NewDecl->addAttr(DLLExportAttr::CreateImplicit(
7120 S.Context, NewImportAttr->getRange()));
7121 }
7122 } else if (IsMicrosoftABI && IsSpecialization) {
7123 assert(!IsDefinition)(static_cast <bool> (!IsDefinition) ? void (0) : __assert_fail
("!IsDefinition", "clang/lib/Sema/SemaDecl.cpp", 7123, __extension__
__PRETTY_FUNCTION__))
;
7124 // MSVC allows this. Keep the inherited attribute.
7125 } else {
7126 S.Diag(NewDecl->getLocation(),
7127 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7128 << NewDecl << OldImportAttr;
7129 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7130 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
7131 OldDecl->dropAttr<DLLImportAttr>();
7132 NewDecl->dropAttr<DLLImportAttr>();
7133 }
7134 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7135 // In MinGW, seeing a function declared inline drops the dllimport
7136 // attribute.
7137 OldDecl->dropAttr<DLLImportAttr>();
7138 NewDecl->dropAttr<DLLImportAttr>();
7139 S.Diag(NewDecl->getLocation(),
7140 diag::warn_dllimport_dropped_from_inline_function)
7141 << NewDecl << OldImportAttr;
7142 }
7143
7144 // A specialization of a class template member function is processed here
7145 // since it's a redeclaration. If the parent class is dllexport, the
7146 // specialization inherits that attribute. This doesn't happen automatically
7147 // since the parent class isn't instantiated until later.
7148 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
7149 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7150 !NewImportAttr && !NewExportAttr) {
7151 if (const DLLExportAttr *ParentExportAttr =
7152 MD->getParent()->getAttr<DLLExportAttr>()) {
7153 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
7154 NewAttr->setInherited(true);
7155 NewDecl->addAttr(NewAttr);
7156 }
7157 }
7158 }
7159}
7160
7161/// Given that we are within the definition of the given function,
7162/// will that definition behave like C99's 'inline', where the
7163/// definition is discarded except for optimization purposes?
7164static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
7165 // Try to avoid calling GetGVALinkageForFunction.
7166
7167 // All cases of this require the 'inline' keyword.
7168 if (!FD->isInlined()) return false;
7169
7170 // This is only possible in C++ with the gnu_inline attribute.
7171 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7172 return false;
7173
7174 // Okay, go ahead and call the relatively-more-expensive function.
7175 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
7176}
7177
7178/// Determine whether a variable is extern "C" prior to attaching
7179/// an initializer. We can't just call isExternC() here, because that
7180/// will also compute and cache whether the declaration is externally
7181/// visible, which might change when we attach the initializer.
7182///
7183/// This can only be used if the declaration is known to not be a
7184/// redeclaration of an internal linkage declaration.
7185///
7186/// For instance:
7187///
7188/// auto x = []{};
7189///
7190/// Attaching the initializer here makes this declaration not externally
7191/// visible, because its type has internal linkage.
7192///
7193/// FIXME: This is a hack.
7194template<typename T>
7195static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7196 if (S.getLangOpts().CPlusPlus) {
7197 // In C++, the overloadable attribute negates the effects of extern "C".
7198 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7199 return false;
7200
7201 // So do CUDA's host/device attributes.
7202 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7203 D->template hasAttr<CUDAHostAttr>()))
7204 return false;
7205 }
7206 return D->isExternC();
7207}
7208
7209static bool shouldConsiderLinkage(const VarDecl *VD) {
7210 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7211 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
7212 isa<OMPDeclareMapperDecl>(DC))
7213 return VD->hasExternalStorage();
7214 if (DC->isFileContext())
7215 return true;
7216 if (DC->isRecord())
7217 return false;
7218 if (DC->getDeclKind() == Decl::HLSLBuffer)
7219 return false;
7220
7221 if (isa<RequiresExprBodyDecl>(DC))
7222 return false;
7223 llvm_unreachable("Unexpected context")::llvm::llvm_unreachable_internal("Unexpected context", "clang/lib/Sema/SemaDecl.cpp"
, 7223)
;
7224}
7225
7226static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7227 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7228 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7229 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
7230 return true;
7231 if (DC->isRecord())
7232 return false;
7233 llvm_unreachable("Unexpected context")::llvm::llvm_unreachable_internal("Unexpected context", "clang/lib/Sema/SemaDecl.cpp"
, 7233)
;
7234}
7235
7236static bool hasParsedAttr(Scope *S, const Declarator &PD,
7237 ParsedAttr::Kind Kind) {
7238 // Check decl attributes on the DeclSpec.
7239 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
7240 return true;
7241
7242 // Walk the declarator structure, checking decl attributes that were in a type
7243 // position to the decl itself.
7244 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7245 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
7246 return true;
7247 }
7248
7249 // Finally, check attributes on the decl itself.
7250 return PD.getAttributes().hasAttribute(Kind) ||
7251 PD.getDeclarationAttributes().hasAttribute(Kind);
7252}
7253
7254/// Adjust the \c DeclContext for a function or variable that might be a
7255/// function-local external declaration.
7256bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
7257 if (!DC->isFunctionOrMethod())
7258 return false;
7259
7260 // If this is a local extern function or variable declared within a function
7261 // template, don't add it into the enclosing namespace scope until it is
7262 // instantiated; it might have a dependent type right now.
7263 if (DC->isDependentContext())
7264 return true;
7265
7266 // C++11 [basic.link]p7:
7267 // When a block scope declaration of an entity with linkage is not found to
7268 // refer to some other declaration, then that entity is a member of the
7269 // innermost enclosing namespace.
7270 //
7271 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7272 // semantically-enclosing namespace, not a lexically-enclosing one.
7273 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
7274 DC = DC->getParent();
7275 return true;
7276}
7277
7278/// Returns true if given declaration has external C language linkage.
7279static bool isDeclExternC(const Decl *D) {
7280 if (const auto *FD = dyn_cast<FunctionDecl>(D))
7281 return FD->isExternC();
7282 if (const auto *VD = dyn_cast<VarDecl>(D))
7283 return VD->isExternC();
7284
7285 llvm_unreachable("Unknown type of decl!")::llvm::llvm_unreachable_internal("Unknown type of decl!", "clang/lib/Sema/SemaDecl.cpp"
, 7285)
;
7286}
7287
7288/// Returns true if there hasn't been any invalid type diagnosed.
7289static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7290 DeclContext *DC = NewVD->getDeclContext();
7291 QualType R = NewVD->getType();
7292
7293 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7294 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7295 // argument.
7296 if (R->isImageType() || R->isPipeType()) {
7297 Se.Diag(NewVD->getLocation(),
7298 diag::err_opencl_type_can_only_be_used_as_function_parameter)
7299 << R;
7300 NewVD->setInvalidDecl();
7301 return false;
7302 }
7303
7304 // OpenCL v1.2 s6.9.r:
7305 // The event type cannot be used to declare a program scope variable.
7306 // OpenCL v2.0 s6.9.q:
7307 // The clk_event_t and reserve_id_t types cannot be declared in program
7308 // scope.
7309 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7310 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7311 Se.Diag(NewVD->getLocation(),
7312 diag::err_invalid_type_for_program_scope_var)
7313 << R;
7314 NewVD->setInvalidDecl();
7315 return false;
7316 }
7317 }
7318
7319 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7320 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7321 Se.getLangOpts())) {
7322 QualType NR = R.getCanonicalType();
7323 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7324 NR->isReferenceType()) {
7325 if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
7326 NR->isFunctionReferenceType()) {
7327 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7328 << NR->isReferenceType();
7329 NewVD->setInvalidDecl();
7330 return false;
7331 }
7332 NR = NR->getPointeeType();
7333 }
7334 }
7335
7336 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7337 Se.getLangOpts())) {
7338 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7339 // half array type (unless the cl_khr_fp16 extension is enabled).
7340 if (Se.Context.getBaseElementType(R)->isHalfType()) {
7341 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7342 NewVD->setInvalidDecl();
7343 return false;
7344 }
7345 }
7346
7347 // OpenCL v1.2 s6.9.r:
7348 // The event type cannot be used with the __local, __constant and __global
7349 // address space qualifiers.
7350 if (R->isEventT()) {
7351 if (R.getAddressSpace() != LangAS::opencl_private) {
7352 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7353 NewVD->setInvalidDecl();
7354 return false;
7355 }
7356 }
7357
7358 if (R->isSamplerT()) {
7359 // OpenCL v1.2 s6.9.b p4:
7360 // The sampler type cannot be used with the __local and __global address
7361 // space qualifiers.
7362 if (R.getAddressSpace() == LangAS::opencl_local ||
7363 R.getAddressSpace() == LangAS::opencl_global) {
7364 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7365 NewVD->setInvalidDecl();
7366 }
7367
7368 // OpenCL v1.2 s6.12.14.1:
7369 // A global sampler must be declared with either the constant address
7370 // space qualifier or with the const qualifier.
7371 if (DC->isTranslationUnit() &&
7372 !(R.getAddressSpace() == LangAS::opencl_constant ||
7373 R.isConstQualified())) {
7374 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7375 NewVD->setInvalidDecl();
7376 }
7377 if (NewVD->isInvalidDecl())
7378 return false;
7379 }
7380
7381 return true;
7382}
7383
7384template <typename AttrTy>
7385static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7386 const TypedefNameDecl *TND = TT->getDecl();
7387 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7388 AttrTy *Clone = Attribute->clone(S.Context);
7389 Clone->setInherited(true);
7390 D->addAttr(Clone);
7391 }
7392}
7393
7394// This function emits warning and a corresponding note based on the
7395// ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7396// declarations of an annotated type must be const qualified.
7397void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD) {
7398 QualType VarType = VD->getType().getCanonicalType();
7399
7400 // Ignore local declarations (for now) and those with const qualification.
7401 // TODO: Local variables should not be allowed if their type declaration has
7402 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7403 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7404 return;
7405
7406 if (VarType->isArrayType()) {
7407 // Retrieve element type for array declarations.
7408 VarType = S.getASTContext().getBaseElementType(VarType);
7409 }
7410
7411 const RecordDecl *RD = VarType->getAsRecordDecl();
7412
7413 // Check if the record declaration is present and if it has any attributes.
7414 if (RD == nullptr)
7415 return;
7416
7417 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7418 S.Diag(VD->getLocation(), diag::warn_var_decl_not_read_only) << RD;
7419 S.Diag(ConstDecl->getLocation(), diag::note_enforce_read_only_placement);
7420 return;
7421 }
7422}
7423
7424NamedDecl *Sema::ActOnVariableDeclarator(
7425 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7426 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7427 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7428 QualType R = TInfo->getType();
7429 DeclarationName Name = GetNameForDeclarator(D).getName();
7430
7431 IdentifierInfo *II = Name.getAsIdentifierInfo();
7432
7433 if (D.isDecompositionDeclarator()) {
7434 // Take the name of the first declarator as our name for diagnostic
7435 // purposes.
7436 auto &Decomp = D.getDecompositionDeclarator();
7437 if (!Decomp.bindings().empty()) {
7438 II = Decomp.bindings()[0].Name;
7439 Name = II;
7440 }
7441 } else if (!II) {
7442 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7443 return nullptr;
7444 }
7445
7446
7447 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7448 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
7449
7450 // dllimport globals without explicit storage class are treated as extern. We
7451 // have to change the storage class this early to get the right DeclContext.
7452 if (SC == SC_None && !DC->isRecord() &&
7453 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7454 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7455 SC = SC_Extern;
7456
7457 DeclContext *OriginalDC = DC;
7458 bool IsLocalExternDecl = SC == SC_Extern &&
7459 adjustContextForLocalExternDecl(DC);
7460
7461 if (SCSpec == DeclSpec::SCS_mutable) {
7462 // mutable can only appear on non-static class members, so it's always
7463 // an error here
7464 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7465 D.setInvalidType();
7466 SC = SC_None;
7467 }
7468
7469 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7470 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7471 D.getDeclSpec().getStorageClassSpecLoc())) {
7472 // In C++11, the 'register' storage class specifier is deprecated.
7473 // Suppress the warning in system macros, it's used in macros in some
7474 // popular C system headers, such as in glibc's htonl() macro.
7475 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7476 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7477 : diag::warn_deprecated_register)
7478 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7479 }
7480
7481 DiagnoseFunctionSpecifiers(D.getDeclSpec());
7482
7483 if (!DC->isRecord() && S->getFnParent() == nullptr) {
7484 // C99 6.9p2: The storage-class specifiers auto and register shall not
7485 // appear in the declaration specifiers in an external declaration.
7486 // Global Register+Asm is a GNU extension we support.
7487 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7488 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7489 D.setInvalidType();
7490 }
7491 }
7492
7493 // If this variable has a VLA type and an initializer, try to
7494 // fold to a constant-sized type. This is otherwise invalid.
7495 if (D.hasInitializer() && R->isVariableArrayType())
7496 tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
7497 /*DiagID=*/0);
7498
7499 bool IsMemberSpecialization = false;
7500 bool IsVariableTemplateSpecialization = false;
7501 bool IsPartialSpecialization = false;
7502 bool IsVariableTemplate = false;
7503 VarDecl *NewVD = nullptr;
7504 VarTemplateDecl *NewTemplate = nullptr;
7505 TemplateParameterList *TemplateParams = nullptr;
7506 if (!getLangOpts().CPlusPlus) {
7507 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
7508 II, R, TInfo, SC);
7509
7510 if (R->getContainedDeducedType())
7511 ParsingInitForAutoVars.insert(NewVD);
7512
7513 if (D.isInvalidType())
7514 NewVD->setInvalidDecl();
7515
7516 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7517 NewVD->hasLocalStorage())
7518 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7519 NTCUC_AutoVar, NTCUK_Destruct);
7520 } else {
7521 bool Invalid = false;
7522
7523 if (DC->isRecord() && !CurContext->isRecord()) {
7524 // This is an out-of-line definition of a static data member.
7525 switch (SC) {
7526 case SC_None:
7527 break;
7528 case SC_Static:
7529 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7530 diag::err_static_out_of_line)
7531 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7532 break;
7533 case SC_Auto:
7534 case SC_Register:
7535 case SC_Extern:
7536 // [dcl.stc] p2: The auto or register specifiers shall be applied only
7537 // to names of variables declared in a block or to function parameters.
7538 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7539 // of class members
7540
7541 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7542 diag::err_storage_class_for_static_member)
7543 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7544 break;
7545 case SC_PrivateExtern:
7546 llvm_unreachable("C storage class in c++!")::llvm::llvm_unreachable_internal("C storage class in c++!", "clang/lib/Sema/SemaDecl.cpp"
, 7546)
;
7547 }
7548 }
7549
7550 if (SC == SC_Static && CurContext->isRecord()) {
7551 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7552 // Walk up the enclosing DeclContexts to check for any that are
7553 // incompatible with static data members.
7554 const DeclContext *FunctionOrMethod = nullptr;
7555 const CXXRecordDecl *AnonStruct = nullptr;
7556 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7557 if (Ctxt->isFunctionOrMethod()) {
7558 FunctionOrMethod = Ctxt;
7559 break;
7560 }
7561 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7562 if (ParentDecl && !ParentDecl->getDeclName()) {
7563 AnonStruct = ParentDecl;
7564 break;
7565 }
7566 }
7567 if (FunctionOrMethod) {
7568 // C++ [class.static.data]p5: A local class shall not have static data
7569 // members.
7570 Diag(D.getIdentifierLoc(),
7571 diag::err_static_data_member_not_allowed_in_local_class)
7572 << Name << RD->getDeclName() << RD->getTagKind();
7573 } else if (AnonStruct) {
7574 // C++ [class.static.data]p4: Unnamed classes and classes contained
7575 // directly or indirectly within unnamed classes shall not contain
7576 // static data members.
7577 Diag(D.getIdentifierLoc(),
7578 diag::err_static_data_member_not_allowed_in_anon_struct)
7579 << Name << AnonStruct->getTagKind();
7580 Invalid = true;
7581 } else if (RD->isUnion()) {
7582 // C++98 [class.union]p1: If a union contains a static data member,
7583 // the program is ill-formed. C++11 drops this restriction.
7584 Diag(D.getIdentifierLoc(),
7585 getLangOpts().CPlusPlus11
7586 ? diag::warn_cxx98_compat_static_data_member_in_union
7587 : diag::ext_static_data_member_in_union) << Name;
7588 }
7589 }
7590 }
7591
7592 // Match up the template parameter lists with the scope specifier, then
7593 // determine whether we have a template or a template specialization.
7594 bool InvalidScope = false;
7595 TemplateParams = MatchTemplateParametersToScopeSpecifier(
7596 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7597 D.getCXXScopeSpec(),
7598 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7599 ? D.getName().TemplateId
7600 : nullptr,
7601 TemplateParamLists,
7602 /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
7603 Invalid |= InvalidScope;
7604
7605 if (TemplateParams) {
7606 if (!TemplateParams->size() &&
7607 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7608 // There is an extraneous 'template<>' for this variable. Complain
7609 // about it, but allow the declaration of the variable.
7610 Diag(TemplateParams->getTemplateLoc(),
7611 diag::err_template_variable_noparams)
7612 << II
7613 << SourceRange(TemplateParams->getTemplateLoc(),
7614 TemplateParams->getRAngleLoc());
7615 TemplateParams = nullptr;
7616 } else {
7617 // Check that we can declare a template here.
7618 if (CheckTemplateDeclScope(S, TemplateParams))
7619 return nullptr;
7620
7621 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7622 // This is an explicit specialization or a partial specialization.
7623 IsVariableTemplateSpecialization = true;
7624 IsPartialSpecialization = TemplateParams->size() > 0;
7625 } else { // if (TemplateParams->size() > 0)
7626 // This is a template declaration.
7627 IsVariableTemplate = true;
7628
7629 // Only C++1y supports variable templates (N3651).
7630 Diag(D.getIdentifierLoc(),
7631 getLangOpts().CPlusPlus14
7632 ? diag::warn_cxx11_compat_variable_template
7633 : diag::ext_variable_template);
7634 }
7635 }
7636 } else {
7637 // Check that we can declare a member specialization here.
7638 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7639 CheckTemplateDeclScope(S, TemplateParamLists.back()))
7640 return nullptr;
7641 assert((Invalid ||(static_cast <bool> ((Invalid || D.getName().getKind() !=
UnqualifiedIdKind::IK_TemplateId) && "should have a 'template<>' for this decl"
) ? void (0) : __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && \"should have a 'template<>' for this decl\""
, "clang/lib/Sema/SemaDecl.cpp", 7643, __extension__ __PRETTY_FUNCTION__
))
7642 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&(static_cast <bool> ((Invalid || D.getName().getKind() !=
UnqualifiedIdKind::IK_TemplateId) && "should have a 'template<>' for this decl"
) ? void (0) : __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && \"should have a 'template<>' for this decl\""
, "clang/lib/Sema/SemaDecl.cpp", 7643, __extension__ __PRETTY_FUNCTION__
))
7643 "should have a 'template<>' for this decl")(static_cast <bool> ((Invalid || D.getName().getKind() !=
UnqualifiedIdKind::IK_TemplateId) && "should have a 'template<>' for this decl"
) ? void (0) : __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && \"should have a 'template<>' for this decl\""
, "clang/lib/Sema/SemaDecl.cpp", 7643, __extension__ __PRETTY_FUNCTION__
))
;
7644 }
7645
7646 if (IsVariableTemplateSpecialization) {
7647 SourceLocation TemplateKWLoc =
7648 TemplateParamLists.size() > 0
7649 ? TemplateParamLists[0]->getTemplateLoc()
7650 : SourceLocation();
7651 DeclResult Res = ActOnVarTemplateSpecialization(
7652 S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7653 IsPartialSpecialization);
7654 if (Res.isInvalid())
7655 return nullptr;
7656 NewVD = cast<VarDecl>(Res.get());
7657 AddToScope = false;
7658 } else if (D.isDecompositionDeclarator()) {
7659 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7660 D.getIdentifierLoc(), R, TInfo, SC,
7661 Bindings);
7662 } else
7663 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7664 D.getIdentifierLoc(), II, R, TInfo, SC);
7665
7666 // If this is supposed to be a variable template, create it as such.
7667 if (IsVariableTemplate) {
7668 NewTemplate =
7669 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7670 TemplateParams, NewVD);
7671 NewVD->setDescribedVarTemplate(NewTemplate);
7672 }
7673
7674 // If this decl has an auto type in need of deduction, make a note of the
7675 // Decl so we can diagnose uses of it in its own initializer.
7676 if (R->getContainedDeducedType())
7677 ParsingInitForAutoVars.insert(NewVD);
7678
7679 if (D.isInvalidType() || Invalid) {
7680 NewVD->setInvalidDecl();
7681 if (NewTemplate)
7682 NewTemplate->setInvalidDecl();
7683 }
7684
7685 SetNestedNameSpecifier(*this, NewVD, D);
7686
7687 // If we have any template parameter lists that don't directly belong to
7688 // the variable (matching the scope specifier), store them.
7689 // An explicit variable template specialization does not own any template
7690 // parameter lists.
7691 bool IsExplicitSpecialization =
7692 IsVariableTemplateSpecialization && !IsPartialSpecialization;
7693 unsigned VDTemplateParamLists =
7694 (TemplateParams && !IsExplicitSpecialization) ? 1 : 0;
7695 if (TemplateParamLists.size() > VDTemplateParamLists)
7696 NewVD->setTemplateParameterListsInfo(
7697 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7698 }
7699
7700 if (D.getDeclSpec().isInlineSpecified()) {
7701 if (!getLangOpts().CPlusPlus) {
7702 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7703 << 0;
7704 } else if (CurContext->isFunctionOrMethod()) {
7705 // 'inline' is not allowed on block scope variable declaration.
7706 Diag(D.getDeclSpec().getInlineSpecLoc(),
7707 diag::err_inline_declaration_block_scope) << Name
7708 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7709 } else {
7710 Diag(D.getDeclSpec().getInlineSpecLoc(),
7711 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7712 : diag::ext_inline_variable);
7713 NewVD->setInlineSpecified();
7714 }
7715 }
7716
7717 // Set the lexical context. If the declarator has a C++ scope specifier, the
7718 // lexical context will be different from the semantic context.
7719 NewVD->setLexicalDeclContext(CurContext);
7720 if (NewTemplate)
7721 NewTemplate->setLexicalDeclContext(CurContext);
7722
7723 if (IsLocalExternDecl) {
7724 if (D.isDecompositionDeclarator())
7725 for (auto *B : Bindings)
7726 B->setLocalExternDecl();
7727 else
7728 NewVD->setLocalExternDecl();
7729 }
7730
7731 bool EmitTLSUnsupportedError = false;
7732 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7733 // C++11 [dcl.stc]p4:
7734 // When thread_local is applied to a variable of block scope the
7735 // storage-class-specifier static is implied if it does not appear
7736 // explicitly.
7737 // Core issue: 'static' is not implied if the variable is declared
7738 // 'extern'.
7739 if (NewVD->hasLocalStorage() &&
7740 (SCSpec != DeclSpec::SCS_unspecified ||
7741 TSCS != DeclSpec::TSCS_thread_local ||
7742 !DC->isFunctionOrMethod()))
7743 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7744 diag::err_thread_non_global)
7745 << DeclSpec::getSpecifierName(TSCS);
7746 else if (!Context.getTargetInfo().isTLSSupported()) {
7747 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7748 getLangOpts().SYCLIsDevice) {
7749 // Postpone error emission until we've collected attributes required to
7750 // figure out whether it's a host or device variable and whether the
7751 // error should be ignored.
7752 EmitTLSUnsupportedError = true;
7753 // We still need to mark the variable as TLS so it shows up in AST with
7754 // proper storage class for other tools to use even if we're not going
7755 // to emit any code for it.
7756 NewVD->setTSCSpec(TSCS);
7757 } else
7758 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7759 diag::err_thread_unsupported);
7760 } else
7761 NewVD->setTSCSpec(TSCS);
7762 }
7763
7764 switch (D.getDeclSpec().getConstexprSpecifier()) {
7765 case ConstexprSpecKind::Unspecified:
7766 break;
7767
7768 case ConstexprSpecKind::Consteval:
7769 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7770 diag::err_constexpr_wrong_decl_kind)
7771 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7772 [[fallthrough]];
7773
7774 case ConstexprSpecKind::Constexpr:
7775 NewVD->setConstexpr(true);
7776 // C++1z [dcl.spec.constexpr]p1:
7777 // A static data member declared with the constexpr specifier is
7778 // implicitly an inline variable.
7779 if (NewVD->isStaticDataMember() &&
7780 (getLangOpts().CPlusPlus17 ||
7781 Context.getTargetInfo().getCXXABI().isMicrosoft()))
7782 NewVD->setImplicitlyInline();
7783 break;
7784
7785 case ConstexprSpecKind::Constinit:
7786 if (!NewVD->hasGlobalStorage())
7787 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7788 diag::err_constinit_local_variable);
7789 else
7790 NewVD->addAttr(
7791 ConstInitAttr::Create(Context, D.getDeclSpec().getConstexprSpecLoc(),
7792 ConstInitAttr::Keyword_constinit));
7793 break;
7794 }
7795
7796 // C99 6.7.4p3
7797 // An inline definition of a function with external linkage shall
7798 // not contain a definition of a modifiable object with static or
7799 // thread storage duration...
7800 // We only apply this when the function is required to be defined
7801 // elsewhere, i.e. when the function is not 'extern inline'. Note
7802 // that a local variable with thread storage duration still has to
7803 // be marked 'static'. Also note that it's possible to get these
7804 // semantics in C++ using __attribute__((gnu_inline)).
7805 if (SC == SC_Static && S->getFnParent() != nullptr &&
7806 !NewVD->getType().isConstQualified()) {
7807 FunctionDecl *CurFD = getCurFunctionDecl();
7808 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7809 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7810 diag::warn_static_local_in_extern_inline);
7811 MaybeSuggestAddingStaticToDecl(CurFD);
7812 }
7813 }
7814
7815 if (D.getDeclSpec().isModulePrivateSpecified()) {
7816 if (IsVariableTemplateSpecialization)
7817 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7818 << (IsPartialSpecialization ? 1 : 0)
7819 << FixItHint::CreateRemoval(
7820 D.getDeclSpec().getModulePrivateSpecLoc());
7821 else if (IsMemberSpecialization)
7822 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7823 << 2
7824 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7825 else if (NewVD->hasLocalStorage())
7826 Diag(NewVD->getLocation(), diag::err_module_private_local)
7827 << 0 << NewVD
7828 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7829 << FixItHint::CreateRemoval(
7830 D.getDeclSpec().getModulePrivateSpecLoc());
7831 else {
7832 NewVD->setModulePrivate();
7833 if (NewTemplate)
7834 NewTemplate->setModulePrivate();
7835 for (auto *B : Bindings)
7836 B->setModulePrivate();
7837 }
7838 }
7839
7840 if (getLangOpts().OpenCL) {
7841 deduceOpenCLAddressSpace(NewVD);
7842
7843 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
7844 if (TSC != TSCS_unspecified) {
7845 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7846 diag::err_opencl_unknown_type_specifier)
7847 << getLangOpts().getOpenCLVersionString()
7848 << DeclSpec::getSpecifierName(TSC) << 1;
7849 NewVD->setInvalidDecl();
7850 }
7851 }
7852
7853 // Handle attributes prior to checking for duplicates in MergeVarDecl
7854 ProcessDeclAttributes(S, NewVD, D);
7855
7856 // FIXME: This is probably the wrong location to be doing this and we should
7857 // probably be doing this for more attributes (especially for function
7858 // pointer attributes such as format, warn_unused_result, etc.). Ideally
7859 // the code to copy attributes would be generated by TableGen.
7860 if (R->isFunctionPointerType())
7861 if (const auto *TT = R->getAs<TypedefType>())
7862 copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7863
7864 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7865 getLangOpts().SYCLIsDevice) {
7866 if (EmitTLSUnsupportedError &&
7867 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7868 (getLangOpts().OpenMPIsDevice &&
7869 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7870 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7871 diag::err_thread_unsupported);
7872
7873 if (EmitTLSUnsupportedError &&
7874 (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
7875 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7876 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7877 // storage [duration]."
7878 if (SC == SC_None && S->getFnParent() != nullptr &&
7879 (NewVD->hasAttr<CUDASharedAttr>() ||
7880 NewVD->hasAttr<CUDAConstantAttr>())) {
7881 NewVD->setStorageClass(SC_Static);
7882 }
7883 }
7884
7885 // Ensure that dllimport globals without explicit storage class are treated as
7886 // extern. The storage class is set above using parsed attributes. Now we can
7887 // check the VarDecl itself.
7888 assert(!NewVD->hasAttr<DLLImportAttr>() ||(static_cast <bool> (!NewVD->hasAttr<DLLImportAttr
>() || NewVD->getAttr<DLLImportAttr>()->isInherited
() || NewVD->isStaticDataMember() || NewVD->getStorageClass
() != SC_None) ? void (0) : __assert_fail ("!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None"
, "clang/lib/Sema/SemaDecl.cpp", 7890, __extension__ __PRETTY_FUNCTION__
))
7889 NewVD->getAttr<DLLImportAttr>()->isInherited() ||(static_cast <bool> (!NewVD->hasAttr<DLLImportAttr
>() || NewVD->getAttr<DLLImportAttr>()->isInherited
() || NewVD->isStaticDataMember() || NewVD->getStorageClass
() != SC_None) ? void (0) : __assert_fail ("!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None"
, "clang/lib/Sema/SemaDecl.cpp", 7890, __extension__ __PRETTY_FUNCTION__
))
7890 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None)(static_cast <bool> (!NewVD->hasAttr<DLLImportAttr
>() || NewVD->getAttr<DLLImportAttr>()->isInherited
() || NewVD->isStaticDataMember() || NewVD->getStorageClass
() != SC_None) ? void (0) : __assert_fail ("!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None"
, "clang/lib/Sema/SemaDecl.cpp", 7890, __extension__ __PRETTY_FUNCTION__
))
;
7891
7892 // In auto-retain/release, infer strong retension for variables of
7893 // retainable type.
7894 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7895 NewVD->setInvalidDecl();
7896
7897 // Handle GNU asm-label extension (encoded as an attribute).
7898 if (Expr *E = (Expr*)D.getAsmLabel()) {
7899 // The parser guarantees this is a string.
7900 StringLiteral *SE = cast<StringLiteral>(E);
7901 StringRef Label = SE->getString();
7902 if (S->getFnParent() != nullptr) {
7903 switch (SC) {
7904 case SC_None:
7905 case SC_Auto:
7906 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7907 break;
7908 case SC_Register:
7909 // Local Named register
7910 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7911 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7912 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7913 break;
7914 case SC_Static:
7915 case SC_Extern:
7916 case SC_PrivateExtern:
7917 break;
7918 }
7919 } else if (SC == SC_Register) {
7920 // Global Named register
7921 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7922 const auto &TI = Context.getTargetInfo();
7923 bool HasSizeMismatch;
7924
7925 if (!TI.isValidGCCRegisterName(Label))
7926 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7927 else if (!TI.validateGlobalRegisterVariable(Label,
7928 Context.getTypeSize(R),
7929 HasSizeMismatch))
7930 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7931 else if (HasSizeMismatch)
7932 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7933 }
7934
7935 if (!R->isIntegralType(Context) && !R->isPointerType()) {
7936 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7937 NewVD->setInvalidDecl(true);
7938 }
7939 }
7940
7941 NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7942 /*IsLiteralLabel=*/true,
7943 SE->getStrTokenLoc(0)));
7944 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7945 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7946 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7947 if (I != ExtnameUndeclaredIdentifiers.end()) {
7948 if (isDeclExternC(NewVD)) {
7949 NewVD->addAttr(I->second);
7950 ExtnameUndeclaredIdentifiers.erase(I);
7951 } else
7952 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7953 << /*Variable*/1 << NewVD;
7954 }
7955 }
7956
7957 // Find the shadowed declaration before filtering for scope.
7958 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7959 ? getShadowedDeclaration(NewVD, Previous)
7960 : nullptr;
7961
7962 // Don't consider existing declarations that are in a different
7963 // scope and are out-of-semantic-context declarations (if the new
7964 // declaration has linkage).
7965 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7966 D.getCXXScopeSpec().isNotEmpty() ||
7967 IsMemberSpecialization ||
7968 IsVariableTemplateSpecialization);
7969
7970 // Check whether the previous declaration is in the same block scope. This
7971 // affects whether we merge types with it, per C++11 [dcl.array]p3.
7972 if (getLangOpts().CPlusPlus &&
7973 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7974 NewVD->setPreviousDeclInSameBlockScope(
7975 Previous.isSingleResult() && !Previous.isShadowed() &&
7976 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7977
7978 if (!getLangOpts().CPlusPlus) {
7979 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7980 } else {
7981 // If this is an explicit specialization of a static data member, check it.
7982 if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7983 CheckMemberSpecialization(NewVD, Previous))
7984 NewVD->setInvalidDecl();
7985
7986 // Merge the decl with the existing one if appropriate.
7987 if (!Previous.empty()) {
7988 if (Previous.isSingleResult() &&
7989 isa<FieldDecl>(Previous.getFoundDecl()) &&
7990 D.getCXXScopeSpec().isSet()) {
7991 // The user tried to define a non-static data member
7992 // out-of-line (C++ [dcl.meaning]p1).
7993 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7994 << D.getCXXScopeSpec().getRange();
7995 Previous.clear();
7996 NewVD->setInvalidDecl();
7997 }
7998 } else if (D.getCXXScopeSpec().isSet()) {
7999 // No previous declaration in the qualifying scope.
8000 Diag(D.getIdentifierLoc(), diag::err_no_member)
8001 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
8002 << D.getCXXScopeSpec().getRange();
8003 NewVD->setInvalidDecl();
8004 }
8005
8006 if (!IsVariableTemplateSpecialization)
8007 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8008
8009 if (NewTemplate) {
8010 VarTemplateDecl *PrevVarTemplate =
8011 NewVD->getPreviousDecl()
8012 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
8013 : nullptr;
8014
8015 // Check the template parameter list of this declaration, possibly
8016 // merging in the template parameter list from the previous variable
8017 // template declaration.
8018 if (CheckTemplateParameterList(
8019 TemplateParams,
8020 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8021 : nullptr,
8022 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8023 DC->isDependentContext())
8024 ? TPC_ClassTemplateMember
8025 : TPC_VarTemplate))
8026 NewVD->setInvalidDecl();
8027
8028 // If we are providing an explicit specialization of a static variable
8029 // template, make a note of that.
8030 if (PrevVarTemplate &&
8031 PrevVarTemplate->getInstantiatedFromMemberTemplate())
8032 PrevVarTemplate->setMemberSpecialization();
8033 }
8034 }
8035
8036 // Diagnose shadowed variables iff this isn't a redeclaration.
8037 if (ShadowedDecl && !D.isRedeclaration())
8038 CheckShadow(NewVD, ShadowedDecl, Previous);
8039
8040 ProcessPragmaWeak(S, NewVD);
8041
8042 // If this is the first declaration of an extern C variable, update
8043 // the map of such variables.
8044 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8045 isIncompleteDeclExternC(*this, NewVD))
8046 RegisterLocallyScopedExternCDecl(NewVD, S);
8047
8048 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8049 MangleNumberingContext *MCtx;
8050 Decl *ManglingContextDecl;
8051 std::tie(MCtx, ManglingContextDecl) =
8052 getCurrentMangleNumberContext(NewVD->getDeclContext());
8053 if (MCtx) {
8054 Context.setManglingNumber(
8055 NewVD, MCtx->getManglingNumber(
8056 NewVD, getMSManglingNumber(getLangOpts(), S)));
8057 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
8058 }
8059 }
8060
8061 // Special handling of variable named 'main'.
8062 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
8063 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
8064 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
8065
8066 // C++ [basic.start.main]p3
8067 // A program that declares a variable main at global scope is ill-formed.
8068 if (getLangOpts().CPlusPlus)
8069 Diag(D.getBeginLoc(), diag::err_main_global_variable);
8070
8071 // In C, and external-linkage variable named main results in undefined
8072 // behavior.
8073 else if (NewVD->hasExternalFormalLinkage())
8074 Diag(D.getBeginLoc(), diag::warn_main_redefined);
8075 }
8076
8077 if (D.isRedeclaration() && !Previous.empty()) {
8078 NamedDecl *Prev = Previous.getRepresentativeDecl();
8079 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
8080 D.isFunctionDefinition());
8081 }
8082
8083 if (NewTemplate) {
8084 if (NewVD->isInvalidDecl())
8085 NewTemplate->setInvalidDecl();
8086 ActOnDocumentableDecl(NewTemplate);
8087 return NewTemplate;
8088 }
8089
8090 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8091 CompleteMemberSpecialization(NewVD, Previous);
8092
8093 emitReadOnlyPlacementAttrWarning(*this, NewVD);
8094
8095 return NewVD;
8096}
8097
8098/// Enum describing the %select options in diag::warn_decl_shadow.
8099enum ShadowedDeclKind {
8100 SDK_Local,
8101 SDK_Global,
8102 SDK_StaticMember,
8103 SDK_Field,
8104 SDK_Typedef,
8105 SDK_Using,
8106 SDK_StructuredBinding
8107};
8108
8109/// Determine what kind of declaration we're shadowing.
8110static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
8111 const DeclContext *OldDC) {
8112 if (isa<TypeAliasDecl>(ShadowedDecl))
8113 return SDK_Using;
8114 else if (isa<TypedefDecl>(ShadowedDecl))
8115 return SDK_Typedef;
8116 else if (isa<BindingDecl>(ShadowedDecl))
8117 return SDK_StructuredBinding;
8118 else if (isa<RecordDecl>(OldDC))
8119 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8120
8121 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8122}
8123
8124/// Return the location of the capture if the given lambda captures the given
8125/// variable \p VD, or an invalid source location otherwise.
8126static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
8127 const VarDecl *VD) {
8128 for (const Capture &Capture : LSI->Captures) {
8129 if (Capture.isVariableCapture() && Capture.getVariable() == VD)
8130 return Capture.getLocation();
8131 }
8132 return SourceLocation();
8133}
8134
8135static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
8136 const LookupResult &R) {
8137 // Only diagnose if we're shadowing an unambiguous field or variable.
8138 if (R.getResultKind() != LookupResult::Found)
8139 return false;
8140
8141 // Return false if warning is ignored.
8142 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
8143}
8144
8145/// Return the declaration shadowed by the given variable \p D, or null
8146/// if it doesn't shadow any declaration or shadowing warnings are disabled.
8147NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
8148 const LookupResult &R) {
8149 if (!shouldWarnIfShadowedDecl(Diags, R))
8150 return nullptr;
8151
8152 // Don't diagnose declarations at file scope.
8153 if (D->hasGlobalStorage())
8154 return nullptr;
8155
8156 NamedDecl *ShadowedDecl = R.getFoundDecl();
8157 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8158 : nullptr;
8159}
8160
8161/// Return the declaration shadowed by the given typedef \p D, or null
8162/// if it doesn't shadow any declaration or shadowing warnings are disabled.
8163NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
8164 const LookupResult &R) {
8165 // Don't warn if typedef declaration is part of a class
8166 if (D->getDeclContext()->isRecord())
8167 return nullptr;
8168
8169 if (!shouldWarnIfShadowedDecl(Diags, R))
8170 return nullptr;
8171
8172 NamedDecl *ShadowedDecl = R.getFoundDecl();
8173 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
8174}
8175
8176/// Return the declaration shadowed by the given variable \p D, or null
8177/// if it doesn't shadow any declaration or shadowing warnings are disabled.
8178NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
8179 const LookupResult &R) {
8180 if (!shouldWarnIfShadowedDecl(Diags, R))
8181 return nullptr;
8182
8183 NamedDecl *ShadowedDecl = R.getFoundDecl();
8184 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8185 : nullptr;
8186}
8187
8188/// Diagnose variable or built-in function shadowing. Implements
8189/// -Wshadow.
8190///
8191/// This method is called whenever a VarDecl is added to a "useful"
8192/// scope.
8193///
8194/// \param ShadowedDecl the declaration that is shadowed by the given variable
8195/// \param R the lookup of the name
8196///
8197void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
8198 const LookupResult &R) {
8199 DeclContext *NewDC = D->getDeclContext();
8200
8201 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
8202 // Fields are not shadowed by variables in C++ static methods.
8203 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
8204 if (MD->isStatic())
8205 return;
8206
8207 // Fields shadowed by constructor parameters are a special case. Usually
8208 // the constructor initializes the field with the parameter.
8209 if (isa<CXXConstructorDecl>(NewDC))
8210 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
8211 // Remember that this was shadowed so we can either warn about its
8212 // modification or its existence depending on warning settings.
8213 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
8214 return;
8215 }
8216 }
8217
8218 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
8219 if (shadowedVar->isExternC()) {
8220 // For shadowing external vars, make sure that we point to the global
8221 // declaration, not a locally scoped extern declaration.
8222 for (auto *I : shadowedVar->redecls())
8223 if (I->isFileVarDecl()) {
8224 ShadowedDecl = I;
8225 break;
8226 }
8227 }
8228
8229 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8230
8231 unsigned WarningDiag = diag::warn_decl_shadow;
8232 SourceLocation CaptureLoc;
8233 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
8234 isa<CXXMethodDecl>(NewDC)) {
8235 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
8236 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
8237 if (RD->getLambdaCaptureDefault() == LCD_None) {
8238 // Try to avoid warnings for lambdas with an explicit capture list.
8239 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
8240 // Warn only when the lambda captures the shadowed decl explicitly.
8241 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
8242 if (CaptureLoc.isInvalid())
8243 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8244 } else {
8245 // Remember that this was shadowed so we can avoid the warning if the
8246 // shadowed decl isn't captured and the warning settings allow it.
8247 cast<LambdaScopeInfo>(getCurFunction())
8248 ->ShadowingDecls.push_back(
8249 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
8250 return;
8251 }
8252 }
8253
8254 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
8255 // A variable can't shadow a local variable in an enclosing scope, if
8256 // they are separated by a non-capturing declaration context.
8257 for (DeclContext *ParentDC = NewDC;
8258 ParentDC && !ParentDC->Equals(OldDC);
8259 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
8260 // Only block literals, captured statements, and lambda expressions
8261 // can capture; other scopes don't.
8262 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
8263 !isLambdaCallOperator(ParentDC)) {
8264 return;
8265 }
8266 }
8267 }
8268 }
8269 }
8270
8271 // Only warn about certain kinds of shadowing for class members.
8272 if (NewDC && NewDC->isRecord()) {
8273 // In particular, don't warn about shadowing non-class members.
8274 if (!OldDC->isRecord())
8275 return;
8276
8277 // TODO: should we warn about static data members shadowing
8278 // static data members from base classes?
8279
8280 // TODO: don't diagnose for inaccessible shadowed members.
8281 // This is hard to do perfectly because we might friend the
8282 // shadowing context, but that's just a false negative.
8283 }
8284
8285
8286 DeclarationName Name = R.getLookupName();
8287
8288 // Emit warning and note.
8289 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8290 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8291 if (!CaptureLoc.isInvalid())
8292 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8293 << Name << /*explicitly*/ 1;
8294 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8295}
8296
8297/// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
8298/// when these variables are captured by the lambda.
8299void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
8300 for (const auto &Shadow : LSI->ShadowingDecls) {
8301 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
8302 // Try to avoid the warning when the shadowed decl isn't captured.
8303 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
8304 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8305 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
8306 ? diag::warn_decl_shadow_uncaptured_local
8307 : diag::warn_decl_shadow)
8308 << Shadow.VD->getDeclName()
8309 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8310 if (!CaptureLoc.isInvalid())
8311 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8312 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8313 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8314 }
8315}
8316
8317/// Check -Wshadow without the advantage of a previous lookup.
8318void Sema::CheckShadow(Scope *S, VarDecl *D) {
8319 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8320 return;
8321
8322 LookupResult R(*this, D->getDeclName(), D->getLocation(),
8323 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
8324 LookupName(R, S);
8325 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8326 CheckShadow(D, ShadowedDecl, R);
8327}
8328
8329/// Check if 'E', which is an expression that is about to be modified, refers
8330/// to a constructor parameter that shadows a field.
8331void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
8332 // Quickly ignore expressions that can't be shadowing ctor parameters.
8333 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8334 return;
8335 E = E->IgnoreParenImpCasts();
8336 auto *DRE = dyn_cast<DeclRefExpr>(E);
8337 if (!DRE)
8338 return;
8339 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8340 auto I = ShadowingDecls.find(D);
8341 if (I == ShadowingDecls.end())
8342 return;
8343 const NamedDecl *ShadowedDecl = I->second;
8344 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8345 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8346 Diag(D->getLocation(), diag::note_var_declared_here) << D;
8347 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8348
8349 // Avoid issuing multiple warnings about the same decl.
8350 ShadowingDecls.erase(I);
8351}
8352
8353/// Check for conflict between this global or extern "C" declaration and
8354/// previous global or extern "C" declarations. This is only used in C++.
8355template<typename T>
8356static bool checkGlobalOrExternCConflict(
8357 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8358 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"")(static_cast <bool> (S.getLangOpts().CPlusPlus &&
"only C++ has extern \"C\"") ? void (0) : __assert_fail ("S.getLangOpts().CPlusPlus && \"only C++ has extern \\\"C\\\"\""
, "clang/lib/Sema/SemaDecl.cpp", 8358, __extension__ __PRETTY_FUNCTION__
))
;
8359 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8360
8361 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8362 // The common case: this global doesn't conflict with any extern "C"
8363 // declaration.
8364 return false;
8365 }
8366
8367 if (Prev) {
8368 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8369 // Both the old and new declarations have C language linkage. This is a
8370 // redeclaration.
8371 Previous.clear();
8372 Previous.addDecl(Prev);
8373 return true;
8374 }
8375
8376 // This is a global, non-extern "C" declaration, and there is a previous
8377 // non-global extern "C" declaration. Diagnose if this is a variable
8378 // declaration.
8379 if (!isa<VarDecl>(ND))
8380 return false;
8381 } else {
8382 // The declaration is extern "C". Check for any declaration in the
8383 // translation unit which might conflict.
8384 if (IsGlobal) {
8385 // We have already performed the lookup into the translation unit.
8386 IsGlobal = false;
8387 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8388 I != E; ++I) {
8389 if (isa<VarDecl>(*I)) {
8390 Prev = *I;
8391 break;
8392 }
8393 }
8394 } else {
8395 DeclContext::lookup_result R =
8396 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8397 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8398 I != E; ++I) {
8399 if (isa<VarDecl>(*I)) {
8400 Prev = *I;
8401 break;
8402 }
8403 // FIXME: If we have any other entity with this name in global scope,
8404 // the declaration is ill-formed, but that is a defect: it breaks the
8405 // 'stat' hack, for instance. Only variables can have mangled name
8406 // clashes with extern "C" declarations, so only they deserve a
8407 // diagnostic.
8408 }
8409 }
8410
8411 if (!Prev)
8412 return false;
8413 }
8414
8415 // Use the first declaration's location to ensure we point at something which
8416 // is lexically inside an extern "C" linkage-spec.
8417 assert(Prev && "should have found a previous declaration to diagnose")(static_cast <bool> (Prev && "should have found a previous declaration to diagnose"
) ? void (0) : __assert_fail ("Prev && \"should have found a previous declaration to diagnose\""
, "clang/lib/Sema/SemaDecl.cpp", 8417, __extension__ __PRETTY_FUNCTION__
))
;
8418 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8419 Prev = FD->getFirstDecl();
8420 else
8421 Prev = cast<VarDecl>(Prev)->getFirstDecl();
8422
8423 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8424 << IsGlobal << ND;
8425 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8426 << IsGlobal;
8427 return false;
8428}
8429
8430/// Apply special rules for handling extern "C" declarations. Returns \c true
8431/// if we have found that this is a redeclaration of some prior entity.
8432///
8433/// Per C++ [dcl.link]p6:
8434/// Two declarations [for a function or variable] with C language linkage
8435/// with the same name that appear in different scopes refer to the same
8436/// [entity]. An entity with C language linkage shall not be declared with
8437/// the same name as an entity in global scope.
8438template<typename T>
8439static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
8440 LookupResult &Previous) {
8441 if (!S.getLangOpts().CPlusPlus) {
8442 // In C, when declaring a global variable, look for a corresponding 'extern'
8443 // variable declared in function scope. We don't need this in C++, because
8444 // we find local extern decls in the surrounding file-scope DeclContext.
8445 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8446 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8447 Previous.clear();
8448 Previous.addDecl(Prev);
8449 return true;
8450 }
8451 }
8452 return false;
8453 }
8454
8455 // A declaration in the translation unit can conflict with an extern "C"
8456 // declaration.
8457 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8458 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8459
8460 // An extern "C" declaration can conflict with a declaration in the
8461 // translation unit or can be a redeclaration of an extern "C" declaration
8462 // in another scope.
8463 if (isIncompleteDeclExternC(S,ND))
8464 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8465
8466 // Neither global nor extern "C": nothing to do.
8467 return false;
8468}
8469
8470void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
8471 // If the decl is already known invalid, don't check it.
8472 if (NewVD->isInvalidDecl())
8473 return;
8474
8475 QualType T = NewVD->getType();
8476
8477 // Defer checking an 'auto' type until its initializer is attached.
8478 if (T->isUndeducedType())
8479 return;
8480
8481 if (NewVD->hasAttrs())
8482 CheckAlignasUnderalignment(NewVD);
8483
8484 if (T->isObjCObjectType()) {
8485 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8486 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8487 T = Context.getObjCObjectPointerType(T);
8488 NewVD->setType(T);
8489 }
8490
8491 // Emit an error if an address space was applied to decl with local storage.
8492 // This includes arrays of objects with address space qualifiers, but not
8493 // automatic variables that point to other address spaces.
8494 // ISO/IEC TR 18037 S5.1.2
8495 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8496 T.getAddressSpace() != LangAS::Default) {
8497 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8498 NewVD->setInvalidDecl();
8499 return;
8500 }
8501
8502 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8503 // scope.
8504 if (getLangOpts().OpenCLVersion == 120 &&
8505 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8506 getLangOpts()) &&
8507 NewVD->isStaticLocal()) {
8508 Diag(NewVD->getLocation(), diag::err_static_function_scope);
8509 NewVD->setInvalidDecl();
8510 return;
8511 }
8512
8513 if (getLangOpts().OpenCL) {
8514 if (!diagnoseOpenCLTypes(*this, NewVD))
8515 return;
8516
8517 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8518 if (NewVD->hasAttr<BlocksAttr>()) {
8519 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8520 return;
8521 }
8522
8523 if (T->isBlockPointerType()) {
8524 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8525 // can't use 'extern' storage class.
8526 if (!T.isConstQualified()) {
8527 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8528 << 0 /*const*/;
8529 NewVD->setInvalidDecl();
8530 return;
8531 }
8532 if (NewVD->hasExternalStorage()) {
8533 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8534 NewVD->setInvalidDecl();
8535 return;
8536 }
8537 }
8538
8539 // FIXME: Adding local AS in C++ for OpenCL might make sense.
8540 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8541 NewVD->hasExternalStorage()) {
8542 if (!T->isSamplerT() && !T->isDependentType() &&
8543 !(T.getAddressSpace() == LangAS::opencl_constant ||
8544 (T.getAddressSpace() == LangAS::opencl_global &&
8545 getOpenCLOptions().areProgramScopeVariablesSupported(
8546 getLangOpts())))) {
8547 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8548 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8549 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8550 << Scope << "global or constant";
8551 else
8552 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8553 << Scope << "constant";
8554 NewVD->setInvalidDecl();
8555 return;
8556 }
8557 } else {
8558 if (T.getAddressSpace() == LangAS::opencl_global) {
8559 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8560 << 1 /*is any function*/ << "global";
8561 NewVD->setInvalidDecl();
8562 return;
8563 }
8564 if (T.getAddressSpace() == LangAS::opencl_constant ||
8565 T.getAddressSpace() == LangAS::opencl_local) {
8566 FunctionDecl *FD = getCurFunctionDecl();
8567 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8568 // in functions.
8569 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8570 if (T.getAddressSpace() == LangAS::opencl_constant)
8571 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8572 << 0 /*non-kernel only*/ << "constant";
8573 else
8574 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8575 << 0 /*non-kernel only*/ << "local";
8576 NewVD->setInvalidDecl();
8577 return;
8578 }
8579 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8580 // in the outermost scope of a kernel function.
8581 if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8582 if (!getCurScope()->isFunctionScope()) {
8583 if (T.getAddressSpace() == LangAS::opencl_constant)
8584 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8585 << "constant";
8586 else
8587 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8588 << "local";
8589 NewVD->setInvalidDecl();
8590 return;
8591 }
8592 }
8593 } else if (T.getAddressSpace() != LangAS::opencl_private &&
8594 // If we are parsing a template we didn't deduce an addr
8595 // space yet.
8596 T.getAddressSpace() != LangAS::Default) {
8597 // Do not allow other address spaces on automatic variable.
8598 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8599 NewVD->setInvalidDecl();
8600 return;
8601 }
8602 }
8603 }
8604
8605 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8606 && !NewVD->hasAttr<BlocksAttr>()) {
8607 if (getLangOpts().getGC() != LangOptions::NonGC)
8608 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8609 else {
8610 assert(!getLangOpts().ObjCAutoRefCount)(static_cast <bool> (!getLangOpts().ObjCAutoRefCount) ?
void (0) : __assert_fail ("!getLangOpts().ObjCAutoRefCount",
"clang/lib/Sema/SemaDecl.cpp", 8610, __extension__ __PRETTY_FUNCTION__
))
;
8611 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8612 }
8613 }
8614
8615 bool isVM = T->isVariablyModifiedType();
8616 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8617 NewVD->hasAttr<BlocksAttr>())
8618 setFunctionHasBranchProtectedScope();
8619
8620 if ((isVM && NewVD->hasLinkage()) ||
8621 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8622 bool SizeIsNegative;
8623 llvm::APSInt Oversized;
8624 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
8625 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8626 QualType FixedT;
8627 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
8628 FixedT = FixedTInfo->getType();
8629 else if (FixedTInfo) {
8630 // Type and type-as-written are canonically different. We need to fix up
8631 // both types separately.
8632 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8633 Oversized);
8634 }
8635 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8636 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8637 // FIXME: This won't give the correct result for
8638 // int a[10][n];
8639 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8640
8641 if (NewVD->isFileVarDecl())
8642 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8643 << SizeRange;
8644 else if (NewVD->isStaticLocal())
8645 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8646 << SizeRange;
8647 else
8648 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8649 << SizeRange;
8650 NewVD->setInvalidDecl();
8651 return;
8652 }
8653
8654 if (!FixedTInfo) {
8655 if (NewVD->isFileVarDecl())
8656 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8657 else
8658 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8659 NewVD->setInvalidDecl();
8660 return;
8661 }
8662
8663 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8664 NewVD->setType(FixedT);
8665 NewVD->setTypeSourceInfo(FixedTInfo);
8666 }
8667
8668 if (T->isVoidType()) {
8669 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8670 // of objects and functions.
8671 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8672 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8673 << T;
8674 NewVD->setInvalidDecl();
8675 return;
8676 }
8677 }
8678
8679 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8680 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8681 NewVD->setInvalidDecl();
8682 return;
8683 }
8684
8685 if (!NewVD->hasLocalStorage() && T->isSizelessType() &&
8686 !T->isWebAssemblyReferenceType()) {
8687 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8688 NewVD->setInvalidDecl();
8689 return;
8690 }
8691
8692 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8693 Diag(NewVD->getLocation(), diag::err_block_on_vm);
8694 NewVD->setInvalidDecl();
8695 return;
8696 }
8697
8698 if (NewVD->isConstexpr() && !T->isDependentType() &&
8699 RequireLiteralType(NewVD->getLocation(), T,
8700 diag::err_constexpr_var_non_literal)) {
8701 NewVD->setInvalidDecl();
8702 return;
8703 }
8704
8705 // PPC MMA non-pointer types are not allowed as non-local variable types.
8706 if (Context.getTargetInfo().getTriple().isPPC64() &&
8707 !NewVD->isLocalVarDecl() &&
8708 CheckPPCMMAType(T, NewVD->getLocation())) {
8709 NewVD->setInvalidDecl();
8710 return;
8711 }
8712
8713 // Check that SVE types are only used in functions with SVE available.
8714 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
8715 const FunctionDecl *FD = cast<FunctionDecl>(CurContext);
8716 llvm::StringMap<bool> CallerFeatureMap;
8717 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
8718 if (!Builtin::evaluateRequiredTargetFeatures(
8719 "sve", CallerFeatureMap)) {
8720 Diag(NewVD->getLocation(), diag::err_sve_vector_in_non_sve_target) << T;
8721 NewVD->setInvalidDecl();
8722 return;
8723 }
8724 }
8725}
8726
8727/// Perform semantic checking on a newly-created variable
8728/// declaration.
8729///
8730/// This routine performs all of the type-checking required for a
8731/// variable declaration once it has been built. It is used both to
8732/// check variables after they have been parsed and their declarators
8733/// have been translated into a declaration, and to check variables
8734/// that have been instantiated from a template.
8735///
8736/// Sets NewVD->isInvalidDecl() if an error was encountered.
8737///
8738/// Returns true if the variable declaration is a redeclaration.
8739bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8740 CheckVariableDeclarationType(NewVD);
8741
8742 // If the decl is already known invalid, don't check it.
8743 if (NewVD->isInvalidDecl())
8744 return false;
8745
8746 // If we did not find anything by this name, look for a non-visible
8747 // extern "C" declaration with the same name.
8748 if (Previous.empty() &&
8749 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8750 Previous.setShadowed();
8751
8752 if (!Previous.empty()) {
8753 MergeVarDecl(NewVD, Previous);
8754 return true;
8755 }
8756 return false;
8757}
8758
8759/// AddOverriddenMethods - See if a method overrides any in the base classes,
8760/// and if so, check that it's a valid override and remember it.
8761bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8762 llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
8763
8764 // Look for methods in base classes that this method might override.
8765 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8766 /*DetectVirtual=*/false);
8767 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8768 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8769 DeclarationName Name = MD->getDeclName();
8770
8771 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8772 // We really want to find the base class destructor here.
8773 QualType T = Context.getTypeDeclType(BaseRecord);
8774 CanQualType CT = Context.getCanonicalType(T);
8775 Name = Context.DeclarationNames.getCXXDestructorName(CT);
8776 }
8777
8778 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8779 CXXMethodDecl *BaseMD =
8780 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8781 if (!BaseMD || !BaseMD->isVirtual() ||
8782 IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8783 /*ConsiderCudaAttrs=*/true,
8784 // C++2a [class.virtual]p2 does not consider requires
8785 // clauses when overriding.
8786 /*ConsiderRequiresClauses=*/false))
8787 continue;
8788
8789 if (Overridden.insert(BaseMD).second) {
8790 MD->addOverriddenMethod(BaseMD);
8791 CheckOverridingFunctionReturnType(MD, BaseMD);
8792 CheckOverridingFunctionAttributes(MD, BaseMD);
8793 CheckOverridingFunctionExceptionSpec(MD, BaseMD);
8794 CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
8795 }
8796
8797 // A method can only override one function from each base class. We
8798 // don't track indirectly overridden methods from bases of bases.
8799 return true;
8800 }
8801
8802 return false;
8803 };
8804
8805 DC->lookupInBases(VisitBase, Paths);
8806 return !Overridden.empty();
8807}
8808
8809namespace {
8810 // Struct for holding all of the extra arguments needed by
8811 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8812 struct ActOnFDArgs {
8813 Scope *S;
8814 Declarator &D;
8815 MultiTemplateParamsArg TemplateParamLists;
8816 bool AddToScope;
8817 };
8818} // end anonymous namespace
8819
8820namespace {
8821
8822// Callback to only accept typo corrections that have a non-zero edit distance.
8823// Also only accept corrections that have the same parent decl.
8824class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8825 public:
8826 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8827 CXXRecordDecl *Parent)
8828 : Context(Context), OriginalFD(TypoFD),
8829 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8830
8831 bool ValidateCandidate(const TypoCorrection &candidate) override {
8832 if (candidate.getEditDistance() == 0)
8833 return false;
8834
8835 SmallVector<unsigned, 1> MismatchedParams;
8836 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8837 CDeclEnd = candidate.end();
8838 CDecl != CDeclEnd; ++CDecl) {
8839 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8840
8841 if (FD && !FD->hasBody() &&
8842 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8843 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8844 CXXRecordDecl *Parent = MD->getParent();
8845 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8846 return true;
8847 } else if (!ExpectedParent) {
8848 return true;
8849 }
8850 }
8851 }
8852
8853 return false;
8854 }
8855
8856 std::unique_ptr<CorrectionCandidateCallback> clone() override {
8857 return std::make_unique<DifferentNameValidatorCCC>(*this);
8858 }
8859
8860 private:
8861 ASTContext &Context;
8862 FunctionDecl *OriginalFD;
8863 CXXRecordDecl *ExpectedParent;
8864};
8865
8866} // end anonymous namespace
8867
8868void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8869 TypoCorrectedFunctionDefinitions.insert(F);
8870}
8871
8872/// Generate diagnostics for an invalid function redeclaration.
8873///
8874/// This routine handles generating the diagnostic messages for an invalid
8875/// function redeclaration, including finding possible similar declarations
8876/// or performing typo correction if there are no previous declarations with
8877/// the same name.
8878///
8879/// Returns a NamedDecl iff typo correction was performed and substituting in
8880/// the new declaration name does not cause new errors.
8881static NamedDecl *DiagnoseInvalidRedeclaration(
8882 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8883 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8884 DeclarationName Name = NewFD->getDeclName();
8885 DeclContext *NewDC = NewFD->getDeclContext();
8886 SmallVector<unsigned, 1> MismatchedParams;
8887 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8888 TypoCorrection Correction;
8889 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8890 unsigned DiagMsg =
8891 IsLocalFriend ? diag::err_no_matching_local_friend :
8892 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8893 diag::err_member_decl_does_not_match;
8894 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8895 IsLocalFriend ? Sema::LookupLocalFriendName
8896 : Sema::LookupOrdinaryName,
8897 Sema::ForVisibleRedeclaration);
8898
8899 NewFD->setInvalidDecl();
8900 if (IsLocalFriend)
8901 SemaRef.LookupName(Prev, S);
8902 else
8903 SemaRef.LookupQualifiedName(Prev, NewDC);
8904 assert(!Prev.isAmbiguous() &&(static_cast <bool> (!Prev.isAmbiguous() && "Cannot have an ambiguity in previous-declaration lookup"
) ? void (0) : __assert_fail ("!Prev.isAmbiguous() && \"Cannot have an ambiguity in previous-declaration lookup\""
, "clang/lib/Sema/SemaDecl.cpp", 8905, __extension__ __PRETTY_FUNCTION__
))
8905 "Cannot have an ambiguity in previous-declaration lookup")(static_cast <bool> (!Prev.isAmbiguous() && "Cannot have an ambiguity in previous-declaration lookup"
) ? void (0) : __assert_fail ("!Prev.isAmbiguous() && \"Cannot have an ambiguity in previous-declaration lookup\""
, "clang/lib/Sema/SemaDecl.cpp", 8905, __extension__ __PRETTY_FUNCTION__
))
;
8906 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8907 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8908 MD ? MD->getParent() : nullptr);
8909 if (!Prev.empty()) {
8910 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8911 Func != FuncEnd; ++Func) {
8912 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8913 if (FD &&
8914 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8915 // Add 1 to the index so that 0 can mean the mismatch didn't
8916 // involve a parameter
8917 unsigned ParamNum =
8918 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8919 NearMatches.push_back(std::make_pair(FD, ParamNum));
8920 }
8921 }
8922 // If the qualified name lookup yielded nothing, try typo correction
8923 } else if ((Correction = SemaRef.CorrectTypo(
8924 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8925 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8926 IsLocalFriend ? nullptr : NewDC))) {
8927 // Set up everything for the call to ActOnFunctionDeclarator
8928 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8929 ExtraArgs.D.getIdentifierLoc());
8930 Previous.clear();
8931 Previous.setLookupName(Correction.getCorrection());
8932 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8933 CDeclEnd = Correction.end();
8934 CDecl != CDeclEnd; ++CDecl) {
8935 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8936 if (FD && !FD->hasBody() &&
8937 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8938 Previous.addDecl(FD);
8939 }
8940 }
8941 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8942
8943 NamedDecl *Result;
8944 // Retry building the function declaration with the new previous
8945 // declarations, and with errors suppressed.
8946 {
8947 // Trap errors.
8948 Sema::SFINAETrap Trap(SemaRef);
8949
8950 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8951 // pieces need to verify the typo-corrected C++ declaration and hopefully
8952 // eliminate the need for the parameter pack ExtraArgs.
8953 Result = SemaRef.ActOnFunctionDeclarator(
8954 ExtraArgs.S, ExtraArgs.D,
8955 Correction.getCorrectionDecl()->getDeclContext(),
8956 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8957 ExtraArgs.AddToScope);
8958
8959 if (Trap.hasErrorOccurred())
8960 Result = nullptr;
8961 }
8962
8963 if (Result) {
8964 // Determine which correction we picked.
8965 Decl *Canonical = Result->getCanonicalDecl();
8966 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8967 I != E; ++I)
8968 if ((*I)->getCanonicalDecl() == Canonical)
8969 Correction.setCorrectionDecl(*I);
8970
8971 // Let Sema know about the correction.
8972 SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8973 SemaRef.diagnoseTypo(
8974 Correction,
8975 SemaRef.PDiag(IsLocalFriend
8976 ? diag::err_no_matching_local_friend_suggest
8977 : diag::err_member_decl_does_not_match_suggest)
8978 << Name << NewDC << IsDefinition);
8979 return Result;
8980 }
8981
8982 // Pretend the typo correction never occurred
8983 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8984 ExtraArgs.D.getIdentifierLoc());
8985 ExtraArgs.D.setRedeclaration(wasRedeclaration);
8986 Previous.clear();
8987 Previous.setLookupName(Name);
8988 }
8989
8990 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8991 << Name << NewDC << IsDefinition << NewFD->getLocation();
8992
8993 bool NewFDisConst = false;
8994 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8995 NewFDisConst = NewMD->isConst();
8996
8997 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8998 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8999 NearMatch != NearMatchEnd; ++NearMatch) {
9000 FunctionDecl *FD = NearMatch->first;
9001 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
9002 bool FDisConst = MD && MD->isConst();
9003 bool IsMember = MD || !IsLocalFriend;
9004
9005 // FIXME: These notes are poorly worded for the local friend case.
9006 if (unsigned Idx = NearMatch->second) {
9007 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
9008 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
9009 if (Loc.isInvalid()) Loc = FD->getLocation();
9010 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
9011 : diag::note_local_decl_close_param_match)
9012 << Idx << FDParam->getType()
9013 << NewFD->getParamDecl(Idx - 1)->getType();
9014 } else if (FDisConst != NewFDisConst) {
9015 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
9016 << NewFDisConst << FD->getSourceRange().getEnd()
9017 << (NewFDisConst
9018 ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo()
9019 .getConstQualifierLoc())
9020 : FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo()
9021 .getRParenLoc()
9022 .getLocWithOffset(1),
9023 " const"));
9024 } else
9025 SemaRef.Diag(FD->getLocation(),
9026 IsMember ? diag::note_member_def_close_match
9027 : diag::note_local_decl_close_match);
9028 }
9029 return nullptr;
9030}
9031
9032static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
9033 switch (D.getDeclSpec().getStorageClassSpec()) {
9034 default: llvm_unreachable("Unknown storage class!")::llvm::llvm_unreachable_internal("Unknown storage class!", "clang/lib/Sema/SemaDecl.cpp"
, 9034)
;
9035 case DeclSpec::SCS_auto:
9036 case DeclSpec::SCS_register:
9037 case DeclSpec::SCS_mutable:
9038 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9039 diag::err_typecheck_sclass_func);
9040 D.getMutableDeclSpec().ClearStorageClassSpecs();
9041 D.setInvalidType();
9042 break;
9043 case DeclSpec::SCS_unspecified: break;
9044 case DeclSpec::SCS_extern:
9045 if (D.getDeclSpec().isExternInLinkageSpec())
9046 return SC_None;
9047 return SC_Extern;
9048 case DeclSpec::SCS_static: {
9049 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
9050 // C99 6.7.1p5:
9051 // The declaration of an identifier for a function that has
9052 // block scope shall have no explicit storage-class specifier
9053 // other than extern
9054 // See also (C++ [dcl.stc]p4).
9055 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9056 diag::err_static_block_func);
9057 break;
9058 } else
9059 return SC_Static;
9060 }
9061 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
9062 }
9063
9064 // No explicit storage class has already been returned
9065 return SC_None;
9066}
9067
9068static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
9069 DeclContext *DC, QualType &R,
9070 TypeSourceInfo *TInfo,
9071 StorageClass SC,
9072 bool &IsVirtualOkay) {
9073 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9074 DeclarationName Name = NameInfo.getName();
9075
9076 FunctionDecl *NewFD = nullptr;
9077 bool isInline = D.getDeclSpec().isInlineSpecified();
9078
9079 if (!SemaRef.getLangOpts().CPlusPlus) {
9080 // Determine whether the function was written with a prototype. This is
9081 // true when:
9082 // - there is a prototype in the declarator, or
9083 // - the type R of the function is some kind of typedef or other non-
9084 // attributed reference to a type name (which eventually refers to a
9085 // function type). Note, we can't always look at the adjusted type to
9086 // check this case because attributes may cause a non-function
9087 // declarator to still have a function type. e.g.,
9088 // typedef void func(int a);
9089 // __attribute__((noreturn)) func other_func; // This has a prototype
9090 bool HasPrototype =
9091 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
9092 (D.getDeclSpec().isTypeRep() &&
9093 D.getDeclSpec().getRepAsType().get()->isFunctionProtoType()) ||
9094 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
9095 assert((static_cast <bool> ((HasPrototype || !SemaRef.getLangOpts
().requiresStrictPrototypes()) && "Strict prototypes are required"
) ? void (0) : __assert_fail ("(HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) && \"Strict prototypes are required\""
, "clang/lib/Sema/SemaDecl.cpp", 9097, __extension__ __PRETTY_FUNCTION__
))
9096 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&(static_cast <bool> ((HasPrototype || !SemaRef.getLangOpts
().requiresStrictPrototypes()) && "Strict prototypes are required"
) ? void (0) : __assert_fail ("(HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) && \"Strict prototypes are required\""
, "clang/lib/Sema/SemaDecl.cpp", 9097, __extension__ __PRETTY_FUNCTION__
))
9097 "Strict prototypes are required")(static_cast <bool> ((HasPrototype || !SemaRef.getLangOpts
().requiresStrictPrototypes()) && "Strict prototypes are required"
) ? void (0) : __assert_fail ("(HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) && \"Strict prototypes are required\""
, "clang/lib/Sema/SemaDecl.cpp", 9097, __extension__ __PRETTY_FUNCTION__
))
;
9098
9099 NewFD = FunctionDecl::Create(
9100 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9101 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
9102 ConstexprSpecKind::Unspecified,
9103 /*TrailingRequiresClause=*/nullptr);
9104 if (D.isInvalidType())
9105 NewFD->setInvalidDecl();
9106
9107 return NewFD;
9108 }
9109
9110 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
9111
9112 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9113 if (ConstexprKind == ConstexprSpecKind::Constinit) {
9114 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9115 diag::err_constexpr_wrong_decl_kind)
9116 << static_cast<int>(ConstexprKind);
9117 ConstexprKind = ConstexprSpecKind::Unspecified;
9118 D.getMutableDeclSpec().ClearConstexprSpec();
9119 }
9120 Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
9121
9122 // Check that the return type is not an abstract class type.
9123 // For record types, this is done by the AbstractClassUsageDiagnoser once
9124 // the class has been completely parsed.
9125 if (!DC->isRecord() &&
9126 SemaRef.RequireNonAbstractType(
9127 D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
9128 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
9129 D.setInvalidType();
9130
9131 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
9132 // This is a C++ constructor declaration.
9133 assert(DC->isRecord() &&(static_cast <bool> (DC->isRecord() && "Constructors can only be declared in a member context"
) ? void (0) : __assert_fail ("DC->isRecord() && \"Constructors can only be declared in a member context\""
, "clang/lib/Sema/SemaDecl.cpp", 9134, __extension__ __PRETTY_FUNCTION__
))
9134 "Constructors can only be declared in a member context")(static_cast <bool> (DC->isRecord() && "Constructors can only be declared in a member context"
) ? void (0) : __assert_fail ("DC->isRecord() && \"Constructors can only be declared in a member context\""
, "clang/lib/Sema/SemaDecl.cpp", 9134, __extension__ __PRETTY_FUNCTION__
))
;
9135
9136 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9137 return CXXConstructorDecl::Create(
9138 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9139 TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(),
9140 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9141 InheritedConstructor(), TrailingRequiresClause);
9142
9143 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9144 // This is a C++ destructor declaration.
9145 if (DC->isRecord()) {
9146 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9147 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
9148 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
9149 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
9150 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9151 /*isImplicitlyDeclared=*/false, ConstexprKind,
9152 TrailingRequiresClause);
9153 // User defined destructors start as not selected if the class definition is still
9154 // not done.
9155 if (Record->isBeingDefined())
9156 NewDD->setIneligibleOrNotSelected(true);
9157
9158 // If the destructor needs an implicit exception specification, set it
9159 // now. FIXME: It'd be nice to be able to create the right type to start
9160 // with, but the type needs to reference the destructor declaration.
9161 if (SemaRef.getLangOpts().CPlusPlus11)
9162 SemaRef.AdjustDestructorExceptionSpec(NewDD);
9163
9164 IsVirtualOkay = true;
9165 return NewDD;
9166
9167 } else {
9168 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
9169 D.setInvalidType();
9170
9171 // Create a FunctionDecl to satisfy the function definition parsing
9172 // code path.
9173 return FunctionDecl::Create(
9174 SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
9175 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9176 /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
9177 }
9178
9179 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
9180 if (!DC->isRecord()) {
9181 SemaRef.Diag(D.getIdentifierLoc(),
9182 diag::err_conv_function_not_member);
9183 return nullptr;
9184 }
9185
9186 SemaRef.CheckConversionDeclarator(D, R, SC);
9187 if (D.isInvalidType())
9188 return nullptr;
9189
9190 IsVirtualOkay = true;
9191 return CXXConversionDecl::Create(
9192 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9193 TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9194 ExplicitSpecifier, ConstexprKind, SourceLocation(),
9195 TrailingRequiresClause);
9196
9197 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
9198 if (TrailingRequiresClause)
9199 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
9200 diag::err_trailing_requires_clause_on_deduction_guide)
9201 << TrailingRequiresClause->getSourceRange();
9202 SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
9203
9204 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
9205 ExplicitSpecifier, NameInfo, R, TInfo,
9206 D.getEndLoc());
9207 } else if (DC->isRecord()) {
9208 // If the name of the function is the same as the name of the record,
9209 // then this must be an invalid constructor that has a return type.
9210 // (The parser checks for a return type and makes the declarator a
9211 // constructor if it has no return type).
9212 if (Name.getAsIdentifierInfo() &&
9213 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
9214 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
9215 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
9216 << SourceRange(D.getIdentifierLoc());
9217 return nullptr;
9218 }
9219
9220 // This is a C++ method declaration.
9221 CXXMethodDecl *Ret = CXXMethodDecl::Create(
9222 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9223 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9224 ConstexprKind, SourceLocation(), TrailingRequiresClause);
9225 IsVirtualOkay = !Ret->isStatic();
9226 return Ret;
9227 } else {
9228 bool isFriend =
9229 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9230 if (!isFriend && SemaRef.CurContext->isRecord())
9231 return nullptr;
9232
9233 // Determine whether the function was written with a
9234 // prototype. This true when:
9235 // - we're in C++ (where every function has a prototype),
9236 return FunctionDecl::Create(
9237 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9238 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9239 true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9240 }
9241}
9242
9243enum OpenCLParamType {
9244 ValidKernelParam,
9245 PtrPtrKernelParam,
9246 PtrKernelParam,
9247 InvalidAddrSpacePtrKernelParam,
9248 InvalidKernelParam,
9249 RecordKernelParam
9250};
9251
9252static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
9253 // Size dependent types are just typedefs to normal integer types
9254 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9255 // integers other than by their names.
9256 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9257
9258 // Remove typedefs one by one until we reach a typedef
9259 // for a size dependent type.
9260 QualType DesugaredTy = Ty;
9261 do {
9262 ArrayRef<StringRef> Names(SizeTypeNames);
9263 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
9264 if (Names.end() != Match)
9265 return true;
9266
9267 Ty = DesugaredTy;
9268 DesugaredTy = Ty.getSingleStepDesugaredType(C);
9269 } while (DesugaredTy != Ty);
9270
9271 return false;
9272}
9273
9274static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
9275 if (PT->isDependentType())
9276 return InvalidKernelParam;
9277
9278 if (PT->isPointerType() || PT->isReferenceType()) {
9279 QualType PointeeType = PT->getPointeeType();
9280 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9281 PointeeType.getAddressSpace() == LangAS::opencl_private ||
9282 PointeeType.getAddressSpace() == LangAS::Default)
9283 return InvalidAddrSpacePtrKernelParam;
9284
9285 if (PointeeType->isPointerType()) {
9286 // This is a pointer to pointer parameter.
9287 // Recursively check inner type.
9288 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
9289 if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9290 ParamKind == InvalidKernelParam)
9291 return ParamKind;
9292
9293 // OpenCL v3.0 s6.11.a:
9294 // A restriction to pass pointers to pointers only applies to OpenCL C
9295 // v1.2 or below.
9296 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9297 return ValidKernelParam;
9298
9299 return PtrPtrKernelParam;
9300 }
9301
9302 // C++ for OpenCL v1.0 s2.4:
9303 // Moreover the types used in parameters of the kernel functions must be:
9304 // Standard layout types for pointer parameters. The same applies to
9305 // reference if an implementation supports them in kernel parameters.
9306 if (S.getLangOpts().OpenCLCPlusPlus &&
9307 !S.getOpenCLOptions().isAvailableOption(
9308 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts())) {
9309 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9310 bool IsStandardLayoutType = true;
9311 if (CXXRec) {
9312 // If template type is not ODR-used its definition is only available
9313 // in the template definition not its instantiation.
9314 // FIXME: This logic doesn't work for types that depend on template
9315 // parameter (PR58590).
9316 if (!CXXRec->hasDefinition())
9317 CXXRec = CXXRec->getTemplateInstantiationPattern();
9318 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9319 IsStandardLayoutType = false;
9320 }
9321 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9322 !IsStandardLayoutType)
9323 return InvalidKernelParam;
9324 }
9325
9326 // OpenCL v1.2 s6.9.p:
9327 // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9328 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9329 return ValidKernelParam;
9330
9331 return PtrKernelParam;
9332 }
9333
9334 // OpenCL v1.2 s6.9.k:
9335 // Arguments to kernel functions in a program cannot be declared with the
9336 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9337 // uintptr_t or a struct and/or union that contain fields declared to be one
9338 // of these built-in scalar types.
9339 if (isOpenCLSizeDependentType(S.getASTContext(), PT))
9340 return InvalidKernelParam;
9341
9342 if (PT->isImageType())
9343 return PtrKernelParam;
9344
9345 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9346 return InvalidKernelParam;
9347
9348 // OpenCL extension spec v1.2 s9.5:
9349 // This extension adds support for half scalar and vector types as built-in
9350 // types that can be used for arithmetic operations, conversions etc.
9351 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
9352 PT->isHalfType())
9353 return InvalidKernelParam;
9354
9355 // Look into an array argument to check if it has a forbidden type.
9356 if (PT->isArrayType()) {
9357 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9358 // Call ourself to check an underlying type of an array. Since the
9359 // getPointeeOrArrayElementType returns an innermost type which is not an
9360 // array, this recursive call only happens once.
9361 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
9362 }
9363
9364 // C++ for OpenCL v1.0 s2.4:
9365 // Moreover the types used in parameters of the kernel functions must be:
9366 // Trivial and standard-layout types C++17 [basic.types] (plain old data
9367 // types) for parameters passed by value;
9368 if (S.getLangOpts().OpenCLCPlusPlus &&
9369 !S.getOpenCLOptions().isAvailableOption(
9370 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9371 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
9372 return InvalidKernelParam;
9373
9374 if (PT->isRecordType())
9375 return RecordKernelParam;
9376
9377 return ValidKernelParam;
9378}
9379
9380static void checkIsValidOpenCLKernelParameter(
9381 Sema &S,
9382 Declarator &D,
9383 ParmVarDecl *Param,
9384 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9385 QualType PT = Param->getType();
9386
9387 // Cache the valid types we encounter to avoid rechecking structs that are
9388 // used again
9389 if (ValidTypes.count(PT.getTypePtr()))
9390 return;
9391
9392 switch (getOpenCLKernelParameterType(S, PT)) {
9393 case PtrPtrKernelParam:
9394 // OpenCL v3.0 s6.11.a:
9395 // A kernel function argument cannot be declared as a pointer to a pointer
9396 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9397 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9398 D.setInvalidType();
9399 return;
9400
9401 case InvalidAddrSpacePtrKernelParam:
9402 // OpenCL v1.0 s6.5:
9403 // __kernel function arguments declared to be a pointer of a type can point
9404 // to one of the following address spaces only : __global, __local or
9405 // __constant.
9406 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9407 D.setInvalidType();
9408 return;
9409
9410 // OpenCL v1.2 s6.9.k:
9411 // Arguments to kernel functions in a program cannot be declared with the
9412 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9413 // uintptr_t or a struct and/or union that contain fields declared to be
9414 // one of these built-in scalar types.
9415
9416 case InvalidKernelParam:
9417 // OpenCL v1.2 s6.8 n:
9418 // A kernel function argument cannot be declared
9419 // of event_t type.
9420 // Do not diagnose half type since it is diagnosed as invalid argument
9421 // type for any function elsewhere.
9422 if (!PT->isHalfType()) {
9423 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9424
9425 // Explain what typedefs are involved.
9426 const TypedefType *Typedef = nullptr;
9427 while ((Typedef = PT->getAs<TypedefType>())) {
9428 SourceLocation Loc = Typedef->getDecl()->getLocation();
9429 // SourceLocation may be invalid for a built-in type.
9430 if (Loc.isValid())
9431 S.Diag(Loc, diag::note_entity_declared_at) << PT;
9432 PT = Typedef->desugar();
9433 }
9434 }
9435
9436 D.setInvalidType();
9437 return;
9438
9439 case PtrKernelParam:
9440 case ValidKernelParam:
9441 ValidTypes.insert(PT.getTypePtr());
9442 return;
9443
9444 case RecordKernelParam:
9445 break;
9446 }
9447
9448 // Track nested structs we will inspect
9449 SmallVector<const Decl *, 4> VisitStack;
9450
9451 // Track where we are in the nested structs. Items will migrate from
9452 // VisitStack to HistoryStack as we do the DFS for bad field.
9453 SmallVector<const FieldDecl *, 4> HistoryStack;
9454 HistoryStack.push_back(nullptr);
9455
9456 // At this point we already handled everything except of a RecordType or
9457 // an ArrayType of a RecordType.
9458 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.")(static_cast <bool> ((PT->isArrayType() || PT->isRecordType
()) && "Unexpected type.") ? void (0) : __assert_fail
("(PT->isArrayType() || PT->isRecordType()) && \"Unexpected type.\""
, "clang/lib/Sema/SemaDecl.cpp", 9458, __extension__ __PRETTY_FUNCTION__
))
;
9459 const RecordType *RecTy =
9460 PT->getPointeeOrArrayElementType()->getAs<RecordType>();
9461 const RecordDecl *OrigRecDecl = RecTy->getDecl();
9462
9463 VisitStack.push_back(RecTy->getDecl());
9464 assert(VisitStack.back() && "First decl null?")(static_cast <bool> (VisitStack.back() && "First decl null?"
) ? void (0) : __assert_fail ("VisitStack.back() && \"First decl null?\""
, "clang/lib/Sema/SemaDecl.cpp", 9464, __extension__ __PRETTY_FUNCTION__
))
;
9465
9466 do {
9467 const Decl *Next = VisitStack.pop_back_val();
9468 if (!Next) {
9469 assert(!HistoryStack.empty())(static_cast <bool> (!HistoryStack.empty()) ? void (0) :
__assert_fail ("!HistoryStack.empty()", "clang/lib/Sema/SemaDecl.cpp"
, 9469, __extension__ __PRETTY_FUNCTION__))
;
9470 // Found a marker, we have gone up a level
9471 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9472 ValidTypes.insert(Hist->getType().getTypePtr());
9473
9474 continue;
9475 }
9476
9477 // Adds everything except the original parameter declaration (which is not a
9478 // field itself) to the history stack.
9479 const RecordDecl *RD;
9480 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9481 HistoryStack.push_back(Field);
9482
9483 QualType FieldTy = Field->getType();
9484 // Other field types (known to be valid or invalid) are handled while we
9485 // walk around RecordDecl::fields().
9486 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&(static_cast <bool> ((FieldTy->isArrayType() || FieldTy
->isRecordType()) && "Unexpected type.") ? void (0
) : __assert_fail ("(FieldTy->isArrayType() || FieldTy->isRecordType()) && \"Unexpected type.\""
, "clang/lib/Sema/SemaDecl.cpp", 9487, __extension__ __PRETTY_FUNCTION__
))
9487 "Unexpected type.")(static_cast <bool> ((FieldTy->isArrayType() || FieldTy
->isRecordType()) && "Unexpected type.") ? void (0
) : __assert_fail ("(FieldTy->isArrayType() || FieldTy->isRecordType()) && \"Unexpected type.\""
, "clang/lib/Sema/SemaDecl.cpp", 9487, __extension__ __PRETTY_FUNCTION__
))
;
9488 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9489
9490 RD = FieldRecTy->castAs<RecordType>()->getDecl();
9491 } else {
9492 RD = cast<RecordDecl>(Next);
9493 }
9494
9495 // Add a null marker so we know when we've gone back up a level
9496 VisitStack.push_back(nullptr);
9497
9498 for (const auto *FD : RD->fields()) {
9499 QualType QT = FD->getType();
9500
9501 if (ValidTypes.count(QT.getTypePtr()))
9502 continue;
9503
9504 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
9505 if (ParamType == ValidKernelParam)
9506 continue;
9507
9508 if (ParamType == RecordKernelParam) {
9509 VisitStack.push_back(FD);
9510 continue;
9511 }
9512
9513 // OpenCL v1.2 s6.9.p:
9514 // Arguments to kernel functions that are declared to be a struct or union
9515 // do not allow OpenCL objects to be passed as elements of the struct or
9516 // union. This restriction was lifted in OpenCL v2.0 with the introduction
9517 // of SVM.
9518 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9519 ParamType == InvalidAddrSpacePtrKernelParam) {
9520 S.Diag(Param->getLocation(),
9521 diag::err_record_with_pointers_kernel_param)
9522 << PT->isUnionType()
9523 << PT;
9524 } else {
9525 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9526 }
9527
9528 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
9529 << OrigRecDecl->getDeclName();
9530
9531 // We have an error, now let's go back up through history and show where
9532 // the offending field came from
9533 for (ArrayRef<const FieldDecl *>::const_iterator
9534 I = HistoryStack.begin() + 1,
9535 E = HistoryStack.end();
9536 I != E; ++I) {
9537 const FieldDecl *OuterField = *I;
9538 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9539 << OuterField->getType();
9540 }
9541
9542 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9543 << QT->isPointerType()
9544 << QT;
9545 D.setInvalidType();
9546 return;
9547 }
9548 } while (!VisitStack.empty());
9549}
9550
9551/// Find the DeclContext in which a tag is implicitly declared if we see an
9552/// elaborated type specifier in the specified context, and lookup finds
9553/// nothing.
9554static DeclContext *getTagInjectionContext(DeclContext *DC) {
9555 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9556 DC = DC->getParent();
9557 return DC;
9558}
9559
9560/// Find the Scope in which a tag is implicitly declared if we see an
9561/// elaborated type specifier in the specified context, and lookup finds
9562/// nothing.
9563static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9564 while (S->isClassScope() ||
9565 (LangOpts.CPlusPlus &&
9566 S->isFunctionPrototypeScope()) ||
9567 ((S->getFlags() & Scope::DeclScope) == 0) ||
9568 (S->getEntity() && S->getEntity()->isTransparentContext()))
9569 S = S->getParent();
9570 return S;
9571}
9572
9573/// Determine whether a declaration matches a known function in namespace std.
9574static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD,
9575 unsigned BuiltinID) {
9576 switch (BuiltinID) {
9577 case Builtin::BI__GetExceptionInfo:
9578 // No type checking whatsoever.
9579 return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
9580
9581 case Builtin::BIaddressof:
9582 case Builtin::BI__addressof:
9583 case Builtin::BIforward:
9584 case Builtin::BIforward_like:
9585 case Builtin::BImove:
9586 case Builtin::BImove_if_noexcept:
9587 case Builtin::BIas_const: {
9588 // Ensure that we don't treat the algorithm
9589 // OutputIt std::move(InputIt, InputIt, OutputIt)
9590 // as the builtin std::move.
9591 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9592 return FPT->getNumParams() == 1 && !FPT->isVariadic();
9593 }
9594
9595 default:
9596 return false;
9597 }
9598}
9599
9600NamedDecl*
9601Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
9602 TypeSourceInfo *TInfo, LookupResult &Previous,
9603 MultiTemplateParamsArg TemplateParamListsRef,
9604 bool &AddToScope) {
9605 QualType R = TInfo->getType();
9606
9607 assert(R->isFunctionType())(static_cast <bool> (R->isFunctionType()) ? void (0)
: __assert_fail ("R->isFunctionType()", "clang/lib/Sema/SemaDecl.cpp"
, 9607, __extension__ __PRETTY_FUNCTION__))
;
9608 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
9609 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9610
9611 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9612 llvm::append_range(TemplateParamLists, TemplateParamListsRef);
9613 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
9614 if (!TemplateParamLists.empty() &&
9615 Invented->getDepth() == TemplateParamLists.back()->getDepth())
9616 TemplateParamLists.back() = Invented;
9617 else
9618 TemplateParamLists.push_back(Invented);
9619 }
9620
9621 // TODO: consider using NameInfo for diagnostic.
9622 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9623 DeclarationName Name = NameInfo.getName();
9624 StorageClass SC = getFunctionStorageClass(*this, D);
9625
9626 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
9627 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
9628 diag::err_invalid_thread)
9629 << DeclSpec::getSpecifierName(TSCS);
9630
9631 if (D.isFirstDeclarationOfMember())
9632 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
9633 D.getIdentifierLoc());
9634
9635 bool isFriend = false;
9636 FunctionTemplateDecl *FunctionTemplate = nullptr;
9637 bool isMemberSpecialization = false;
9638 bool isFunctionTemplateSpecialization = false;
9639
9640 bool isDependentClassScopeExplicitSpecialization = false;
9641 bool HasExplicitTemplateArgs = false;
9642 TemplateArgumentListInfo TemplateArgs;
9643
9644 bool isVirtualOkay = false;
9645
9646 DeclContext *OriginalDC = DC;
9647 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9648
9649 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
9650 isVirtualOkay);
9651 if (!NewFD) return nullptr;
9652
9653 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
9654 NewFD->setTopLevelDeclInObjCContainer();
9655
9656 // Set the lexical context. If this is a function-scope declaration, or has a
9657 // C++ scope specifier, or is the object of a friend declaration, the lexical
9658 // context will be different from the semantic context.
9659 NewFD->setLexicalDeclContext(CurContext);
9660
9661 if (IsLocalExternDecl)
9662 NewFD->setLocalExternDecl();
9663
9664 if (getLangOpts().CPlusPlus) {
9665 // The rules for implicit inlines changed in C++20 for methods and friends
9666 // with an in-class definition (when such a definition is not attached to
9667 // the global module). User-specified 'inline' overrides this (set when
9668 // the function decl is created above).
9669 // FIXME: We need a better way to separate C++ standard and clang modules.
9670 bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
9671 !NewFD->getOwningModule() ||
9672 NewFD->getOwningModule()->isGlobalModule() ||
9673 NewFD->getOwningModule()->isHeaderLikeModule();
9674 bool isInline = D.getDeclSpec().isInlineSpecified();
9675 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9676 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9677 isFriend = D.getDeclSpec().isFriendSpecified();
9678 if (isFriend && !isInline && D.isFunctionDefinition()) {
9679 // Pre-C++20 [class.friend]p5
9680 // A function can be defined in a friend declaration of a
9681 // class . . . . Such a function is implicitly inline.
9682 // Post C++20 [class.friend]p7
9683 // Such a function is implicitly an inline function if it is attached
9684 // to the global module.
9685 NewFD->setImplicitlyInline(ImplicitInlineCXX20);
9686 }
9687
9688 // If this is a method defined in an __interface, and is not a constructor
9689 // or an overloaded operator, then set the pure flag (isVirtual will already
9690 // return true).
9691 if (const CXXRecordDecl *Parent =
9692 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9693 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9694 NewFD->setPure(true);
9695
9696 // C++ [class.union]p2
9697 // A union can have member functions, but not virtual functions.
9698 if (isVirtual && Parent->isUnion()) {
9699 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9700 NewFD->setInvalidDecl();
9701 }
9702 if ((Parent->isClass() || Parent->isStruct()) &&
9703 Parent->hasAttr<SYCLSpecialClassAttr>() &&
9704 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
9705 NewFD->getName() == "__init" && D.isFunctionDefinition()) {
9706 if (auto *Def = Parent->getDefinition())
9707 Def->setInitMethod(true);
9708 }
9709 }
9710
9711 SetNestedNameSpecifier(*this, NewFD, D);
9712 isMemberSpecialization = false;
9713 isFunctionTemplateSpecialization = false;
9714 if (D.isInvalidType())
9715 NewFD->setInvalidDecl();
9716
9717 // Match up the template parameter lists with the scope specifier, then
9718 // determine whether we have a template or a template specialization.
9719 bool Invalid = false;
9720 TemplateParameterList *TemplateParams =
9721 MatchTemplateParametersToScopeSpecifier(
9722 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
9723 D.getCXXScopeSpec(),
9724 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
9725 ? D.getName().TemplateId
9726 : nullptr,
9727 TemplateParamLists, isFriend, isMemberSpecialization,
9728 Invalid);
9729 if (TemplateParams) {
9730 // Check that we can declare a template here.
9731 if (CheckTemplateDeclScope(S, TemplateParams))
9732 NewFD->setInvalidDecl();
9733
9734 if (TemplateParams->size() > 0) {
9735 // This is a function template
9736
9737 // A destructor cannot be a template.
9738 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9739 Diag(NewFD->getLocation(), diag::err_destructor_template);
9740 NewFD->setInvalidDecl();
9741 }
9742
9743 // If we're adding a template to a dependent context, we may need to
9744 // rebuilding some of the types used within the template parameter list,
9745 // now that we know what the current instantiation is.
9746 if (DC->isDependentContext()) {
9747 ContextRAII SavedContext(*this, DC);
9748 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
9749 Invalid = true;
9750 }
9751
9752 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
9753 NewFD->getLocation(),
9754 Name, TemplateParams,
9755 NewFD);
9756 FunctionTemplate->setLexicalDeclContext(CurContext);
9757 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
9758
9759 // For source fidelity, store the other template param lists.
9760 if (TemplateParamLists.size() > 1) {
9761 NewFD->setTemplateParameterListsInfo(Context,
9762 ArrayRef<TemplateParameterList *>(TemplateParamLists)
9763 .drop_back(1));
9764 }
9765 } else {
9766 // This is a function template specialization.
9767 isFunctionTemplateSpecialization = true;
9768 // For source fidelity, store all the template param lists.
9769 if (TemplateParamLists.size() > 0)
9770 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9771
9772 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9773 if (isFriend) {
9774 // We want to remove the "template<>", found here.
9775 SourceRange RemoveRange = TemplateParams->getSourceRange();
9776
9777 // If we remove the template<> and the name is not a
9778 // template-id, we're actually silently creating a problem:
9779 // the friend declaration will refer to an untemplated decl,
9780 // and clearly the user wants a template specialization. So
9781 // we need to insert '<>' after the name.
9782 SourceLocation InsertLoc;
9783 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9784 InsertLoc = D.getName().getSourceRange().getEnd();
9785 InsertLoc = getLocForEndOfToken(InsertLoc);
9786 }
9787
9788 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9789 << Name << RemoveRange
9790 << FixItHint::CreateRemoval(RemoveRange)
9791 << FixItHint::CreateInsertion(InsertLoc, "<>");
9792 Invalid = true;
9793 }
9794 }
9795 } else {
9796 // Check that we can declare a template here.
9797 if (!TemplateParamLists.empty() && isMemberSpecialization &&
9798 CheckTemplateDeclScope(S, TemplateParamLists.back()))
9799 NewFD->setInvalidDecl();
9800
9801 // All template param lists were matched against the scope specifier:
9802 // this is NOT (an explicit specialization of) a template.
9803 if (TemplateParamLists.size() > 0)
9804 // For source fidelity, store all the template param lists.
9805 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9806 }
9807
9808 if (Invalid) {
9809 NewFD->setInvalidDecl();
9810 if (FunctionTemplate)
9811 FunctionTemplate->setInvalidDecl();
9812 }
9813
9814 // C++ [dcl.fct.spec]p5:
9815 // The virtual specifier shall only be used in declarations of
9816 // nonstatic class member functions that appear within a
9817 // member-specification of a class declaration; see 10.3.
9818 //
9819 if (isVirtual && !NewFD->isInvalidDecl()) {
9820 if (!isVirtualOkay) {
9821 Diag(D.getDeclSpec().getVirtualSpecLoc(),
9822 diag::err_virtual_non_function);
9823 } else if (!CurContext->isRecord()) {
9824 // 'virtual' was specified outside of the class.
9825 Diag(D.getDeclSpec().getVirtualSpecLoc(),
9826 diag::err_virtual_out_of_class)
9827 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9828 } else if (NewFD->getDescribedFunctionTemplate()) {
9829 // C++ [temp.mem]p3:
9830 // A member function template shall not be virtual.
9831 Diag(D.getDeclSpec().getVirtualSpecLoc(),
9832 diag::err_virtual_member_function_template)
9833 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9834 } else {
9835 // Okay: Add virtual to the method.
9836 NewFD->setVirtualAsWritten(true);
9837 }
9838
9839 if (getLangOpts().CPlusPlus14 &&
9840 NewFD->getReturnType()->isUndeducedType())
9841 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9842 }
9843
9844 if (getLangOpts().CPlusPlus14 &&
9845 (NewFD->isDependentContext() ||
9846 (isFriend && CurContext->isDependentContext())) &&
9847 NewFD->getReturnType()->isUndeducedType()) {
9848 // If the function template is referenced directly (for instance, as a
9849 // member of the current instantiation), pretend it has a dependent type.
9850 // This is not really justified by the standard, but is the only sane
9851 // thing to do.
9852 // FIXME: For a friend function, we have not marked the function as being
9853 // a friend yet, so 'isDependentContext' on the FD doesn't work.
9854 const FunctionProtoType *FPT =
9855 NewFD->getType()->castAs<FunctionProtoType>();
9856 QualType Result = SubstAutoTypeDependent(FPT->getReturnType());
9857 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9858 FPT->getExtProtoInfo()));
9859 }
9860
9861 // C++ [dcl.fct.spec]p3:
9862 // The inline specifier shall not appear on a block scope function
9863 // declaration.
9864 if (isInline && !NewFD->isInvalidDecl()) {
9865 if (CurContext->isFunctionOrMethod()) {
9866 // 'inline' is not allowed on block scope function declaration.
9867 Diag(D.getDeclSpec().getInlineSpecLoc(),
9868 diag::err_inline_declaration_block_scope) << Name
9869 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9870 }
9871 }
9872
9873 // C++ [dcl.fct.spec]p6:
9874 // The explicit specifier shall be used only in the declaration of a
9875 // constructor or conversion function within its class definition;
9876 // see 12.3.1 and 12.3.2.
9877 if (hasExplicit && !NewFD->isInvalidDecl() &&
9878 !isa<CXXDeductionGuideDecl>(NewFD)) {
9879 if (!CurContext->isRecord()) {
9880 // 'explicit' was specified outside of the class.
9881 Diag(D.getDeclSpec().getExplicitSpecLoc(),
9882 diag::err_explicit_out_of_class)
9883 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9884 } else if (!isa<CXXConstructorDecl>(NewFD) &&
9885 !isa<CXXConversionDecl>(NewFD)) {
9886 // 'explicit' was specified on a function that wasn't a constructor
9887 // or conversion function.
9888 Diag(D.getDeclSpec().getExplicitSpecLoc(),
9889 diag::err_explicit_non_ctor_or_conv_function)
9890 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9891 }
9892 }
9893
9894 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9895 if (ConstexprKind != ConstexprSpecKind::Unspecified) {
9896 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9897 // are implicitly inline.
9898 NewFD->setImplicitlyInline();
9899
9900 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9901 // be either constructors or to return a literal type. Therefore,
9902 // destructors cannot be declared constexpr.
9903 if (isa<CXXDestructorDecl>(NewFD) &&
9904 (!getLangOpts().CPlusPlus20 ||
9905 ConstexprKind == ConstexprSpecKind::Consteval)) {
9906 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9907 << static_cast<int>(ConstexprKind);
9908 NewFD->setConstexprKind(getLangOpts().CPlusPlus20
9909 ? ConstexprSpecKind::Unspecified
9910 : ConstexprSpecKind::Constexpr);
9911 }
9912 // C++20 [dcl.constexpr]p2: An allocation function, or a
9913 // deallocation function shall not be declared with the consteval
9914 // specifier.
9915 if (ConstexprKind == ConstexprSpecKind::Consteval &&
9916 (NewFD->getOverloadedOperator() == OO_New ||
9917 NewFD->getOverloadedOperator() == OO_Array_New ||
9918 NewFD->getOverloadedOperator() == OO_Delete ||
9919 NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9920 Diag(D.getDeclSpec().getConstexprSpecLoc(),
9921 diag::err_invalid_consteval_decl_kind)
9922 << NewFD;
9923 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
9924 }
9925 }
9926
9927 // If __module_private__ was specified, mark the function accordingly.
9928 if (D.getDeclSpec().isModulePrivateSpecified()) {
9929 if (isFunctionTemplateSpecialization) {
9930 SourceLocation ModulePrivateLoc
9931 = D.getDeclSpec().getModulePrivateSpecLoc();
9932 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9933 << 0
9934 << FixItHint::CreateRemoval(ModulePrivateLoc);
9935 } else {
9936 NewFD->setModulePrivate();
9937 if (FunctionTemplate)
9938 FunctionTemplate->setModulePrivate();
9939 }
9940 }
9941
9942 if (isFriend) {
9943 if (FunctionTemplate) {
9944 FunctionTemplate->setObjectOfFriendDecl();
9945 FunctionTemplate->setAccess(AS_public);
9946 }
9947 NewFD->setObjectOfFriendDecl();
9948 NewFD->setAccess(AS_public);
9949 }
9950
9951 // If a function is defined as defaulted or deleted, mark it as such now.
9952 // We'll do the relevant checks on defaulted / deleted functions later.
9953 switch (D.getFunctionDefinitionKind()) {
9954 case FunctionDefinitionKind::Declaration:
9955 case FunctionDefinitionKind::Definition:
9956 break;
9957
9958 case FunctionDefinitionKind::Defaulted:
9959 NewFD->setDefaulted();
9960 break;
9961
9962 case FunctionDefinitionKind::Deleted:
9963 NewFD->setDeletedAsWritten();
9964 break;
9965 }
9966
9967 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9968 D.isFunctionDefinition() && !isInline) {
9969 // Pre C++20 [class.mfct]p2:
9970 // A member function may be defined (8.4) in its class definition, in
9971 // which case it is an inline member function (7.1.2)
9972 // Post C++20 [class.mfct]p1:
9973 // If a member function is attached to the global module and is defined
9974 // in its class definition, it is inline.
9975 NewFD->setImplicitlyInline(ImplicitInlineCXX20);
9976 }
9977
9978 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9979 !CurContext->isRecord()) {
9980 // C++ [class.static]p1:
9981 // A data or function member of a class may be declared static
9982 // in a class definition, in which case it is a static member of
9983 // the class.
9984
9985 // Complain about the 'static' specifier if it's on an out-of-line
9986 // member function definition.
9987
9988 // MSVC permits the use of a 'static' storage specifier on an out-of-line
9989 // member function template declaration and class member template
9990 // declaration (MSVC versions before 2015), warn about this.
9991 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9992 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9993 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9994 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9995 ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9996 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9997 }
9998
9999 // C++11 [except.spec]p15:
10000 // A deallocation function with no exception-specification is treated
10001 // as if it were specified with noexcept(true).
10002 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10003 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
10004 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
10005 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
10006 NewFD->setType(Context.getFunctionType(
10007 FPT->getReturnType(), FPT->getParamTypes(),
10008 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
10009
10010 // C++20 [dcl.inline]/7
10011 // If an inline function or variable that is attached to a named module
10012 // is declared in a definition domain, it shall be defined in that
10013 // domain.
10014 // So, if the current declaration does not have a definition, we must
10015 // check at the end of the TU (or when the PMF starts) to see that we
10016 // have a definition at that point.
10017 if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
10018 NewFD->hasOwningModule() &&
10019 NewFD->getOwningModule()->isModulePurview()) {
10020 PendingInlineFuncDecls.insert(NewFD);
10021 }
10022 }
10023
10024 // Filter out previous declarations that don't match the scope.
10025 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
10026 D.getCXXScopeSpec().isNotEmpty() ||
10027 isMemberSpecialization ||
10028 isFunctionTemplateSpecialization);
10029
10030 // Handle GNU asm-label extension (encoded as an attribute).
10031 if (Expr *E = (Expr*) D.getAsmLabel()) {
10032 // The parser guarantees this is a string.
10033 StringLiteral *SE = cast<StringLiteral>(E);
10034 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
10035 /*IsLiteralLabel=*/true,
10036 SE->getStrTokenLoc(0)));
10037 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10038 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
10039 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
10040 if (I != ExtnameUndeclaredIdentifiers.end()) {
10041 if (isDeclExternC(NewFD)) {
10042 NewFD->addAttr(I->second);
10043 ExtnameUndeclaredIdentifiers.erase(I);
10044 } else
10045 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
10046 << /*Variable*/0 << NewFD;
10047 }
10048 }
10049
10050 // Copy the parameter declarations from the declarator D to the function
10051 // declaration NewFD, if they are available. First scavenge them into Params.
10052 SmallVector<ParmVarDecl*, 16> Params;
10053 unsigned FTIIdx;
10054 if (D.isFunctionDeclarator(FTIIdx)) {
10055 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
10056
10057 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10058 // function that takes no arguments, not a function that takes a
10059 // single void argument.
10060 // We let through "const void" here because Sema::GetTypeForDeclarator
10061 // already checks for that case.
10062 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10063 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10064 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
10065 assert(Param->getDeclContext() != NewFD && "Was set before ?")(static_cast <bool> (Param->getDeclContext() != NewFD
&& "Was set before ?") ? void (0) : __assert_fail ("Param->getDeclContext() != NewFD && \"Was set before ?\""
, "clang/lib/Sema/SemaDecl.cpp", 10065, __extension__ __PRETTY_FUNCTION__
))
;
10066 Param->setDeclContext(NewFD);
10067 Params.push_back(Param);
10068
10069 if (Param->isInvalidDecl())
10070 NewFD->setInvalidDecl();
10071 }
10072 }
10073
10074 if (!getLangOpts().CPlusPlus) {
10075 // In C, find all the tag declarations from the prototype and move them
10076 // into the function DeclContext. Remove them from the surrounding tag
10077 // injection context of the function, which is typically but not always
10078 // the TU.
10079 DeclContext *PrototypeTagContext =
10080 getTagInjectionContext(NewFD->getLexicalDeclContext());
10081 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10082 auto *TD = dyn_cast<TagDecl>(NonParmDecl);
10083
10084 // We don't want to reparent enumerators. Look at their parent enum
10085 // instead.
10086 if (!TD) {
10087 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
10088 TD = cast<EnumDecl>(ECD->getDeclContext());
10089 }
10090 if (!TD)
10091 continue;
10092 DeclContext *TagDC = TD->getLexicalDeclContext();
10093 if (!TagDC->containsDecl(TD))
10094 continue;
10095 TagDC->removeDecl(TD);
10096 TD->setDeclContext(NewFD);
10097 NewFD->addDecl(TD);
10098
10099 // Preserve the lexical DeclContext if it is not the surrounding tag
10100 // injection context of the FD. In this example, the semantic context of
10101 // E will be f and the lexical context will be S, while both the
10102 // semantic and lexical contexts of S will be f:
10103 // void f(struct S { enum E { a } f; } s);
10104 if (TagDC != PrototypeTagContext)
10105 TD->setLexicalDeclContext(TagDC);
10106 }
10107 }
10108 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10109 // When we're declaring a function with a typedef, typeof, etc as in the
10110 // following example, we'll need to synthesize (unnamed)
10111 // parameters for use in the declaration.
10112 //
10113 // @code
10114 // typedef void fn(int);
10115 // fn f;
10116 // @endcode
10117
10118 // Synthesize a parameter for each argument type.
10119 for (const auto &AI : FT->param_types()) {
10120 ParmVarDecl *Param =
10121 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
10122 Param->setScopeInfo(0, Params.size());
10123 Params.push_back(Param);
10124 }
10125 } else {
10126 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&(static_cast <bool> (R->isFunctionNoProtoType() &&
NewFD->getNumParams() == 0 && "Should not need args for typedef of non-prototype fn"
) ? void (0) : __assert_fail ("R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && \"Should not need args for typedef of non-prototype fn\""
, "clang/lib/Sema/SemaDecl.cpp", 10127, __extension__ __PRETTY_FUNCTION__
))
10127 "Should not need args for typedef of non-prototype fn")(static_cast <bool> (R->isFunctionNoProtoType() &&
NewFD->getNumParams() == 0 && "Should not need args for typedef of non-prototype fn"
) ? void (0) : __assert_fail ("R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && \"Should not need args for typedef of non-prototype fn\""
, "clang/lib/Sema/SemaDecl.cpp", 10127, __extension__ __PRETTY_FUNCTION__
))
;
10128 }
10129
10130 // Finally, we know we have the right number of parameters, install them.
10131 NewFD->setParams(Params);
10132
10133 if (D.getDeclSpec().isNoreturnSpecified())
10134 NewFD->addAttr(
10135 C11NoReturnAttr::Create(Context, D.getDeclSpec().getNoreturnSpecLoc()));
10136
10137 // Functions returning a variably modified type violate C99 6.7.5.2p2
10138 // because all functions have linkage.
10139 if (!NewFD->isInvalidDecl() &&
10140 NewFD->getReturnType()->isVariablyModifiedType()) {
10141 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
10142 NewFD->setInvalidDecl();
10143 }
10144
10145 // Apply an implicit SectionAttr if '#pragma clang section text' is active
10146 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
10147 !NewFD->hasAttr<SectionAttr>())
10148 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
10149 Context, PragmaClangTextSection.SectionName,
10150 PragmaClangTextSection.PragmaLocation));
10151
10152 // Apply an implicit SectionAttr if #pragma code_seg is active.
10153 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10154 !NewFD->hasAttr<SectionAttr>()) {
10155 NewFD->addAttr(SectionAttr::CreateImplicit(
10156 Context, CodeSegStack.CurrentValue->getString(),
10157 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate));
10158 if (UnifySection(CodeSegStack.CurrentValue->getString(),
10159 ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
10160 ASTContext::PSF_Read,
10161 NewFD))
10162 NewFD->dropAttr<SectionAttr>();
10163 }
10164
10165 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10166 // active.
10167 if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() &&
10168 !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10169 NewFD->addAttr(StrictGuardStackCheckAttr::CreateImplicit(
10170 Context, PragmaClangTextSection.PragmaLocation));
10171
10172 // Apply an implicit CodeSegAttr from class declspec or
10173 // apply an implicit SectionAttr from #pragma code_seg if active.
10174 if (!NewFD->hasAttr<CodeSegAttr>()) {
10175 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
10176 D.isFunctionDefinition())) {
10177 NewFD->addAttr(SAttr);
10178 }
10179 }
10180
10181 // Handle attributes.
10182 ProcessDeclAttributes(S, NewFD, D);
10183 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10184 if (NewTVA && !NewTVA->isDefaultVersion() &&
10185 !Context.getTargetInfo().hasFeature("fmv")) {
10186 // Don't add to scope fmv functions declarations if fmv disabled
10187 AddToScope = false;
10188 return NewFD;
10189 }
10190
10191 if (getLangOpts().OpenCL) {
10192 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10193 // type declaration will generate a compilation error.
10194 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10195 if (AddressSpace != LangAS::Default) {
10196 Diag(NewFD->getLocation(), diag::err_return_value_with_address_space);
10197 NewFD->setInvalidDecl();
10198 }
10199 }
10200
10201 if (getLangOpts().HLSL) {
10202 auto &TargetInfo = getASTContext().getTargetInfo();
10203 // Skip operator overload which not identifier.
10204 // Also make sure NewFD is in translation-unit scope.
10205 if (!NewFD->isInvalidDecl() && Name.isIdentifier() &&
10206 NewFD->getName() == TargetInfo.getTargetOpts().HLSLEntry &&
10207 S->getDepth() == 0) {
10208 CheckHLSLEntryPoint(NewFD);
10209 if (!NewFD->isInvalidDecl()) {
10210 auto Env = TargetInfo.getTriple().getEnvironment();
10211 HLSLShaderAttr::ShaderType ShaderType =
10212 static_cast<HLSLShaderAttr::ShaderType>(
10213 hlsl::getStageFromEnvironment(Env));
10214 // To share code with HLSLShaderAttr, add HLSLShaderAttr to entry
10215 // function.
10216 if (HLSLShaderAttr *NT = NewFD->getAttr<HLSLShaderAttr>()) {
10217 if (NT->getType() != ShaderType)
10218 Diag(NT->getLocation(), diag::err_hlsl_entry_shader_attr_mismatch)
10219 << NT;
10220 } else {
10221 NewFD->addAttr(HLSLShaderAttr::Create(Context, ShaderType,
10222 NewFD->getBeginLoc()));
10223 }
10224 }
10225 }
10226 // HLSL does not support specifying an address space on a function return
10227 // type.
10228 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10229 if (AddressSpace != LangAS::Default) {
10230 Diag(NewFD->getLocation(), diag::err_return_value_with_address_space);
10231 NewFD->setInvalidDecl();
10232 }
10233 }
10234
10235 if (!getLangOpts().CPlusPlus) {
10236 // Perform semantic checking on the function declaration.
10237 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10238 CheckMain(NewFD, D.getDeclSpec());
10239
10240 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10241 CheckMSVCRTEntryPoint(NewFD);
10242
10243 if (!NewFD->isInvalidDecl())
10244 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10245 isMemberSpecialization,
10246 D.isFunctionDefinition()));
10247 else if (!Previous.empty())
10248 // Recover gracefully from an invalid redeclaration.
10249 D.setRedeclaration(true);
10250 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||(static_cast <bool> ((NewFD->isInvalidDecl() || !D.isRedeclaration
() || Previous.getResultKind() != LookupResult::FoundOverloaded
) && "previous declaration set still overloaded") ? void
(0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\""
, "clang/lib/Sema/SemaDecl.cpp", 10252, __extension__ __PRETTY_FUNCTION__
))
10251 Previous.getResultKind() != LookupResult::FoundOverloaded) &&(static_cast <bool> ((NewFD->isInvalidDecl() || !D.isRedeclaration
() || Previous.getResultKind() != LookupResult::FoundOverloaded
) && "previous declaration set still overloaded") ? void
(0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\""
, "clang/lib/Sema/SemaDecl.cpp", 10252, __extension__ __PRETTY_FUNCTION__
))
10252 "previous declaration set still overloaded")(static_cast <bool> ((NewFD->isInvalidDecl() || !D.isRedeclaration
() || Previous.getResultKind() != LookupResult::FoundOverloaded
) && "previous declaration set still overloaded") ? void
(0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\""
, "clang/lib/Sema/SemaDecl.cpp", 10252, __extension__ __PRETTY_FUNCTION__
))
;
10253
10254 // Diagnose no-prototype function declarations with calling conventions that
10255 // don't support variadic calls. Only do this in C and do it after merging
10256 // possibly prototyped redeclarations.
10257 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10258 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
10259 CallingConv CC = FT->getExtInfo().getCC();
10260 if (!supportsVariadicCall(CC)) {
10261 // Windows system headers sometimes accidentally use stdcall without
10262 // (void) parameters, so we relax this to a warning.
10263 int DiagID =
10264 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10265 Diag(NewFD->getLocation(), DiagID)
10266 << FunctionType::getNameForCallConv(CC);
10267 }
10268 }
10269
10270 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
10271 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
10272 checkNonTrivialCUnion(NewFD->getReturnType(),
10273 NewFD->getReturnTypeSourceRange().getBegin(),
10274 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
10275 } else {
10276 // C++11 [replacement.functions]p3:
10277 // The program's definitions shall not be specified as inline.
10278 //
10279 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10280 //
10281 // Suppress the diagnostic if the function is __attribute__((used)), since
10282 // that forces an external definition to be emitted.
10283 if (D.getDeclSpec().isInlineSpecified() &&
10284 NewFD->isReplaceableGlobalAllocationFunction() &&
10285 !NewFD->hasAttr<UsedAttr>())
10286 Diag(D.getDeclSpec().getInlineSpecLoc(),
10287 diag::ext_operator_new_delete_declared_inline)
10288 << NewFD->getDeclName();
10289
10290 // If the declarator is a template-id, translate the parser's template
10291 // argument list into our AST format.
10292 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
10293 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
10294 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
10295 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
10296 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
10297 TemplateId->NumArgs);
10298 translateTemplateArguments(TemplateArgsPtr,
10299 TemplateArgs);
10300
10301 HasExplicitTemplateArgs = true;
10302
10303 if (NewFD->isInvalidDecl()) {
10304 HasExplicitTemplateArgs = false;
10305 } else if (FunctionTemplate) {
10306 // Function template with explicit template arguments.
10307 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
10308 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
10309
10310 HasExplicitTemplateArgs = false;
10311 } else {
10312 assert((isFunctionTemplateSpecialization ||(static_cast <bool> ((isFunctionTemplateSpecialization ||
D.getDeclSpec().isFriendSpecified()) && "should have a 'template<>' for this decl"
) ? void (0) : __assert_fail ("(isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && \"should have a 'template<>' for this decl\""
, "clang/lib/Sema/SemaDecl.cpp", 10314, __extension__ __PRETTY_FUNCTION__
))
10313 D.getDeclSpec().isFriendSpecified()) &&(static_cast <bool> ((isFunctionTemplateSpecialization ||
D.getDeclSpec().isFriendSpecified()) && "should have a 'template<>' for this decl"
) ? void (0) : __assert_fail ("(isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && \"should have a 'template<>' for this decl\""
, "clang/lib/Sema/SemaDecl.cpp", 10314, __extension__ __PRETTY_FUNCTION__
))
10314 "should have a 'template<>' for this decl")(static_cast <bool> ((isFunctionTemplateSpecialization ||
D.getDeclSpec().isFriendSpecified()) && "should have a 'template<>' for this decl"
) ? void (0) : __assert_fail ("(isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && \"should have a 'template<>' for this decl\""
, "clang/lib/Sema/SemaDecl.cpp", 10314, __extension__ __PRETTY_FUNCTION__
))
;
10315 // "friend void foo<>(int);" is an implicit specialization decl.
10316 isFunctionTemplateSpecialization = true;
10317 }
10318 } else if (isFriend && isFunctionTemplateSpecialization) {
10319 // This combination is only possible in a recovery case; the user
10320 // wrote something like:
10321 // template <> friend void foo(int);
10322 // which we're recovering from as if the user had written:
10323 // friend void foo<>(int);
10324 // Go ahead and fake up a template id.
10325 HasExplicitTemplateArgs = true;
10326 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
10327 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
10328 }
10329
10330 // We do not add HD attributes to specializations here because
10331 // they may have different constexpr-ness compared to their
10332 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
10333 // may end up with different effective targets. Instead, a
10334 // specialization inherits its target attributes from its template
10335 // in the CheckFunctionTemplateSpecialization() call below.
10336 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
10337 maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
10338
10339 // If it's a friend (and only if it's a friend), it's possible
10340 // that either the specialized function type or the specialized
10341 // template is dependent, and therefore matching will fail. In
10342 // this case, don't check the specialization yet.
10343 if (isFunctionTemplateSpecialization && isFriend &&
10344 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
10345 TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
10346 TemplateArgs.arguments()))) {
10347 assert(HasExplicitTemplateArgs &&(static_cast <bool> (HasExplicitTemplateArgs &&
"friend function specialization without template args") ? void
(0) : __assert_fail ("HasExplicitTemplateArgs && \"friend function specialization without template args\""
, "clang/lib/Sema/SemaDecl.cpp", 10348, __extension__ __PRETTY_FUNCTION__
))
10348 "friend function specialization without template args")(static_cast <bool> (HasExplicitTemplateArgs &&
"friend function specialization without template args") ? void
(0) : __assert_fail ("HasExplicitTemplateArgs && \"friend function specialization without template args\""
, "clang/lib/Sema/SemaDecl.cpp", 10348, __extension__ __PRETTY_FUNCTION__
))
;
10349 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
10350 Previous))
10351 NewFD->setInvalidDecl();
10352 } else if (isFunctionTemplateSpecialization) {
10353 if (CurContext->isDependentContext() && CurContext->isRecord()
10354 && !isFriend) {
10355 isDependentClassScopeExplicitSpecialization = true;
10356 } else if (!NewFD->isInvalidDecl() &&
10357 CheckFunctionTemplateSpecialization(
10358 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
10359 Previous))
10360 NewFD->setInvalidDecl();
10361
10362 // C++ [dcl.stc]p1:
10363 // A storage-class-specifier shall not be specified in an explicit
10364 // specialization (14.7.3)
10365 FunctionTemplateSpecializationInfo *Info =
10366 NewFD->getTemplateSpecializationInfo();
10367 if (Info && SC != SC_None) {
10368 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
10369 Diag(NewFD->getLocation(),
10370 diag::err_explicit_specialization_inconsistent_storage_class)
10371 << SC
10372 << FixItHint::CreateRemoval(
10373 D.getDeclSpec().getStorageClassSpecLoc());
10374
10375 else
10376 Diag(NewFD->getLocation(),
10377 diag::ext_explicit_specialization_storage_class)
10378 << FixItHint::CreateRemoval(
10379 D.getDeclSpec().getStorageClassSpecLoc());
10380 }
10381 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
10382 if (CheckMemberSpecialization(NewFD, Previous))
10383 NewFD->setInvalidDecl();
10384 }
10385
10386 // Perform semantic checking on the function declaration.
10387 if (!isDependentClassScopeExplicitSpecialization) {
10388 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10389 CheckMain(NewFD, D.getDeclSpec());
10390
10391 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10392 CheckMSVCRTEntryPoint(NewFD);
10393
10394 if (!NewFD->isInvalidDecl())
10395 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10396 isMemberSpecialization,
10397 D.isFunctionDefinition()));
10398 else if (!Previous.empty())
10399 // Recover gracefully from an invalid redeclaration.
10400 D.setRedeclaration(true);
10401 }
10402
10403 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||(static_cast <bool> ((NewFD->isInvalidDecl() || NewFD
->isMultiVersion() || !D.isRedeclaration() || Previous.getResultKind
() != LookupResult::FoundOverloaded) && "previous declaration set still overloaded"
) ? void (0) : __assert_fail ("(NewFD->isInvalidDecl() || NewFD->isMultiVersion() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\""
, "clang/lib/Sema/SemaDecl.cpp", 10406, __extension__ __PRETTY_FUNCTION__
))
10404 !D.isRedeclaration() ||(static_cast <bool> ((NewFD->isInvalidDecl() || NewFD
->isMultiVersion() || !D.isRedeclaration() || Previous.getResultKind
() != LookupResult::FoundOverloaded) && "previous declaration set still overloaded"
) ? void (0) : __assert_fail ("(NewFD->isInvalidDecl() || NewFD->isMultiVersion() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\""
, "clang/lib/Sema/SemaDecl.cpp", 10406, __extension__ __PRETTY_FUNCTION__
))
10405 Previous.getResultKind() != LookupResult::FoundOverloaded) &&(static_cast <bool> ((NewFD->isInvalidDecl() || NewFD
->isMultiVersion() || !D.isRedeclaration() || Previous.getResultKind
() != LookupResult::FoundOverloaded) && "previous declaration set still overloaded"
) ? void (0) : __assert_fail ("(NewFD->isInvalidDecl() || NewFD->isMultiVersion() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\""
, "clang/lib/Sema/SemaDecl.cpp", 10406, __extension__ __PRETTY_FUNCTION__
))
10406 "previous declaration set still overloaded")(static_cast <bool> ((NewFD->isInvalidDecl() || NewFD
->isMultiVersion() || !D.isRedeclaration() || Previous.getResultKind
() != LookupResult::FoundOverloaded) && "previous declaration set still overloaded"
) ? void (0) : __assert_fail ("(NewFD->isInvalidDecl() || NewFD->isMultiVersion() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\""
, "clang/lib/Sema/SemaDecl.cpp", 10406, __extension__ __PRETTY_FUNCTION__
))
;
10407
10408 NamedDecl *PrincipalDecl = (FunctionTemplate
10409 ? cast<NamedDecl>(FunctionTemplate)
10410 : NewFD);
10411
10412 if (isFriend && NewFD->getPreviousDecl()) {
10413 AccessSpecifier Access = AS_public;
10414 if (!NewFD->isInvalidDecl())
10415 Access = NewFD->getPreviousDecl()->getAccess();
10416
10417 NewFD->setAccess(Access);
10418 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10419 }
10420
10421 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10422 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
10423 PrincipalDecl->setNonMemberOperator();
10424
10425 // If we have a function template, check the template parameter
10426 // list. This will check and merge default template arguments.
10427 if (FunctionTemplate) {
10428 FunctionTemplateDecl *PrevTemplate =
10429 FunctionTemplate->getPreviousDecl();
10430 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
10431 PrevTemplate ? PrevTemplate->getTemplateParameters()
10432 : nullptr,
10433 D.getDeclSpec().isFriendSpecified()
10434 ? (D.isFunctionDefinition()
10435 ? TPC_FriendFunctionTemplateDefinition
10436 : TPC_FriendFunctionTemplate)
10437 : (D.getCXXScopeSpec().isSet() &&
10438 DC && DC->isRecord() &&
10439 DC->isDependentContext())
10440 ? TPC_ClassTemplateMember
10441 : TPC_FunctionTemplate);
10442 }
10443
10444 if (NewFD->isInvalidDecl()) {
10445 // Ignore all the rest of this.
10446 } else if (!D.isRedeclaration()) {
10447 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
10448 AddToScope };
10449 // Fake up an access specifier if it's supposed to be a class member.
10450 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10451 NewFD->setAccess(AS_public);
10452
10453 // Qualified decls generally require a previous declaration.
10454 if (D.getCXXScopeSpec().isSet()) {
10455 // ...with the major exception of templated-scope or
10456 // dependent-scope friend declarations.
10457
10458 // TODO: we currently also suppress this check in dependent
10459 // contexts because (1) the parameter depth will be off when
10460 // matching friend templates and (2) we might actually be
10461 // selecting a friend based on a dependent factor. But there
10462 // are situations where these conditions don't apply and we
10463 // can actually do this check immediately.
10464 //
10465 // Unless the scope is dependent, it's always an error if qualified
10466 // redeclaration lookup found nothing at all. Diagnose that now;
10467 // nothing will diagnose that error later.
10468 if (isFriend &&
10469 (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
10470 (!Previous.empty() && CurContext->isDependentContext()))) {
10471 // ignore these
10472 } else if (NewFD->isCPUDispatchMultiVersion() ||
10473 NewFD->isCPUSpecificMultiVersion()) {
10474 // ignore this, we allow the redeclaration behavior here to create new
10475 // versions of the function.
10476 } else {
10477 // The user tried to provide an out-of-line definition for a
10478 // function that is a member of a class or namespace, but there
10479 // was no such member function declared (C++ [class.mfct]p2,
10480 // C++ [namespace.memdef]p2). For example:
10481 //
10482 // class X {
10483 // void f() const;
10484 // };
10485 //
10486 // void X::f() { } // ill-formed
10487 //
10488 // Complain about this problem, and attempt to suggest close
10489 // matches (e.g., those that differ only in cv-qualifiers and
10490 // whether the parameter types are references).
10491
10492 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10493 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
10494 AddToScope = ExtraArgs.AddToScope;
10495 return Result;
10496 }
10497 }
10498
10499 // Unqualified local friend declarations are required to resolve
10500 // to something.
10501 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
10502 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10503 *this, Previous, NewFD, ExtraArgs, true, S)) {
10504 AddToScope = ExtraArgs.AddToScope;
10505 return Result;
10506 }
10507 }
10508 } else if (!D.isFunctionDefinition() &&
10509 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
10510 !isFriend && !isFunctionTemplateSpecialization &&
10511 !isMemberSpecialization) {
10512 // An out-of-line member function declaration must also be a
10513 // definition (C++ [class.mfct]p2).
10514 // Note that this is not the case for explicit specializations of
10515 // function templates or member functions of class templates, per
10516 // C++ [temp.expl.spec]p2. We also allow these declarations as an
10517 // extension for compatibility with old SWIG code which likes to
10518 // generate them.
10519 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
10520 << D.getCXXScopeSpec().getRange();
10521 }
10522 }
10523
10524 // If this is the first declaration of a library builtin function, add
10525 // attributes as appropriate.
10526 if (!D.isRedeclaration()) {
10527 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
10528 if (unsigned BuiltinID = II->getBuiltinID()) {
10529 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);
10530 if (!InStdNamespace &&
10531 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
10532 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
10533 // Validate the type matches unless this builtin is specified as
10534 // matching regardless of its declared type.
10535 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
10536 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10537 } else {
10538 ASTContext::GetBuiltinTypeError Error;
10539 LookupNecessaryTypesForBuiltin(S, BuiltinID);
10540 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
10541
10542 if (!Error && !BuiltinType.isNull() &&
10543 Context.hasSameFunctionTypeIgnoringExceptionSpec(
10544 NewFD->getType(), BuiltinType))
10545 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10546 }
10547 }
10548 } else if (InStdNamespace && NewFD->isInStdNamespace() &&
10549 isStdBuiltin(Context, NewFD, BuiltinID)) {
10550 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10551 }
10552 }
10553 }
10554 }
10555
10556 ProcessPragmaWeak(S, NewFD);
10557 checkAttributesAfterMerging(*this, *NewFD);
10558
10559 AddKnownFunctionAttributes(NewFD);
10560
10561 if (NewFD->hasAttr<OverloadableAttr>() &&
10562 !NewFD->getType()->getAs<FunctionProtoType>()) {
10563 Diag(NewFD->getLocation(),
10564 diag::err_attribute_overloadable_no_prototype)
10565 << NewFD;
10566 NewFD->dropAttr<OverloadableAttr>();
10567 }
10568
10569 // If there's a #pragma GCC visibility in scope, and this isn't a class
10570 // member, set the visibility of this function.
10571 if (!DC->isRecord() && NewFD->isExternallyVisible())
10572 AddPushedVisibilityAttribute(NewFD);
10573
10574 // If there's a #pragma clang arc_cf_code_audited in scope, consider
10575 // marking the function.
10576 AddCFAuditedAttribute(NewFD);
10577
10578 // If this is a function definition, check if we have to apply any
10579 // attributes (i.e. optnone and no_builtin) due to a pragma.
10580 if (D.isFunctionDefinition()) {
10581 AddRangeBasedOptnone(NewFD);
10582 AddImplicitMSFunctionNoBuiltinAttr(NewFD);
10583 AddSectionMSAllocText(NewFD);
10584 ModifyFnAttributesMSPragmaOptimize(NewFD);
10585 }
10586
10587 // If this is the first declaration of an extern C variable, update
10588 // the map of such variables.
10589 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
10590 isIncompleteDeclExternC(*this, NewFD))
10591 RegisterLocallyScopedExternCDecl(NewFD, S);
10592
10593 // Set this FunctionDecl's range up to the right paren.
10594 NewFD->setRangeEnd(D.getSourceRange().getEnd());
10595
10596 if (D.isRedeclaration() && !Previous.empty()) {
10597 NamedDecl *Prev = Previous.getRepresentativeDecl();
10598 checkDLLAttributeRedeclaration(*this, Prev, NewFD,
10599 isMemberSpecialization ||
10600 isFunctionTemplateSpecialization,
10601 D.isFunctionDefinition());
10602 }
10603
10604 if (getLangOpts().CUDA) {
10605 IdentifierInfo *II = NewFD->getIdentifier();
10606 if (II && II->isStr(getCudaConfigureFuncName()) &&
10607 !NewFD->isInvalidDecl() &&
10608 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
10609 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
10610 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
10611 << getCudaConfigureFuncName();
10612 Context.setcudaConfigureCallDecl(NewFD);
10613 }
10614
10615 // Variadic functions, other than a *declaration* of printf, are not allowed
10616 // in device-side CUDA code, unless someone passed
10617 // -fcuda-allow-variadic-functions.
10618 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
10619 (NewFD->hasAttr<CUDADeviceAttr>() ||
10620 NewFD->hasAttr<CUDAGlobalAttr>()) &&
10621 !(II && II->isStr("printf") && NewFD->isExternC() &&
10622 !D.isFunctionDefinition())) {
10623 Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
10624 }
10625 }
10626
10627 MarkUnusedFileScopedDecl(NewFD);
10628
10629
10630
10631 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
10632 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
10633 if (SC == SC_Static) {
10634 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
10635 D.setInvalidType();
10636 }
10637
10638 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
10639 if (!NewFD->getReturnType()->isVoidType()) {
10640 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
10641 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
10642 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
10643 : FixItHint());
10644 D.setInvalidType();
10645 }
10646
10647 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
10648 for (auto *Param : NewFD->parameters())
10649 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
10650
10651 if (getLangOpts().OpenCLCPlusPlus) {
10652 if (DC->isRecord()) {
10653 Diag(D.getIdentifierLoc(), diag::err_method_kernel);
10654 D.setInvalidType();
10655 }
10656 if (FunctionTemplate) {
10657 Diag(D.getIdentifierLoc(), diag::err_template_kernel);
10658 D.setInvalidType();
10659 }
10660 }
10661 }
10662
10663 if (getLangOpts().CPlusPlus) {
10664 // Precalculate whether this is a friend function template with a constraint
10665 // that depends on an enclosing template, per [temp.friend]p9.
10666 if (isFriend && FunctionTemplate &&
10667 FriendConstraintsDependOnEnclosingTemplate(NewFD))
10668 NewFD->setFriendConstraintRefersToEnclosingTemplate(true);
10669
10670 if (FunctionTemplate) {
10671 if (NewFD->isInvalidDecl())
10672 FunctionTemplate->setInvalidDecl();
10673 return FunctionTemplate;
10674 }
10675
10676 if (isMemberSpecialization && !NewFD->isInvalidDecl())
10677 CompleteMemberSpecialization(NewFD, Previous);
10678 }
10679
10680 for (const ParmVarDecl *Param : NewFD->parameters()) {
10681 QualType PT = Param->getType();
10682
10683 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10684 // types.
10685 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
10686 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10687 QualType ElemTy = PipeTy->getElementType();
10688 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
10689 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
10690 D.setInvalidType();
10691 }
10692 }
10693 }
10694 }
10695
10696 // Here we have an function template explicit specialization at class scope.
10697 // The actual specialization will be postponed to template instatiation
10698 // time via the ClassScopeFunctionSpecializationDecl node.
10699 if (isDependentClassScopeExplicitSpecialization) {
10700 ClassScopeFunctionSpecializationDecl *NewSpec =
10701 ClassScopeFunctionSpecializationDecl::Create(
10702 Context, CurContext, NewFD->getLocation(),
10703 cast<CXXMethodDecl>(NewFD),
10704 HasExplicitTemplateArgs, TemplateArgs);
10705 CurContext->addDecl(NewSpec);
10706 AddToScope = false;
10707 }
10708
10709 // Diagnose availability attributes. Availability cannot be used on functions
10710 // that are run during load/unload.
10711 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
10712 if (NewFD->hasAttr<ConstructorAttr>()) {
10713 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10714 << 1;
10715 NewFD->dropAttr<AvailabilityAttr>();
10716 }
10717 if (NewFD->hasAttr<DestructorAttr>()) {
10718 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10719 << 2;
10720 NewFD->dropAttr<AvailabilityAttr>();
10721 }
10722 }
10723
10724 // Diagnose no_builtin attribute on function declaration that are not a
10725 // definition.
10726 // FIXME: We should really be doing this in
10727 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10728 // the FunctionDecl and at this point of the code
10729 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10730 // because Sema::ActOnStartOfFunctionDef has not been called yet.
10731 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
10732 switch (D.getFunctionDefinitionKind()) {
10733 case FunctionDefinitionKind::Defaulted:
10734 case FunctionDefinitionKind::Deleted:
10735 Diag(NBA->getLocation(),
10736 diag::err_attribute_no_builtin_on_defaulted_deleted_function)
10737 << NBA->getSpelling();
10738 break;
10739 case FunctionDefinitionKind::Declaration:
10740 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10741 << NBA->getSpelling();
10742 break;
10743 case FunctionDefinitionKind::Definition:
10744 break;
10745 }
10746
10747 return NewFD;
10748}
10749
10750/// Return a CodeSegAttr from a containing class. The Microsoft docs say
10751/// when __declspec(code_seg) "is applied to a class, all member functions of
10752/// the class and nested classes -- this includes compiler-generated special
10753/// member functions -- are put in the specified segment."
10754/// The actual behavior is a little more complicated. The Microsoft compiler
10755/// won't check outer classes if there is an active value from #pragma code_seg.
10756/// The CodeSeg is always applied from the direct parent but only from outer
10757/// classes when the #pragma code_seg stack is empty. See:
10758/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10759/// available since MS has removed the page.
10760static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
10761 const auto *Method = dyn_cast<CXXMethodDecl>(FD);
10762 if (!Method)
10763 return nullptr;
10764 const CXXRecordDecl *Parent = Method->getParent();
10765 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10766 Attr *NewAttr = SAttr->clone(S.getASTContext());
10767 NewAttr->setImplicit(true);
10768 return NewAttr;
10769 }
10770
10771 // The Microsoft compiler won't check outer classes for the CodeSeg
10772 // when the #pragma code_seg stack is active.
10773 if (S.CodeSegStack.CurrentValue)
10774 return nullptr;
10775
10776 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
10777 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10778 Attr *NewAttr = SAttr->clone(S.getASTContext());
10779 NewAttr->setImplicit(true);
10780 return NewAttr;
10781 }
10782 }
10783 return nullptr;
10784}
10785
10786/// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
10787/// containing class. Otherwise it will return implicit SectionAttr if the
10788/// function is a definition and there is an active value on CodeSegStack
10789/// (from the current #pragma code-seg value).
10790///
10791/// \param FD Function being declared.
10792/// \param IsDefinition Whether it is a definition or just a declaration.
10793/// \returns A CodeSegAttr or SectionAttr to apply to the function or
10794/// nullptr if no attribute should be added.
10795Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
10796 bool IsDefinition) {
10797 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
10798 return A;
10799 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
10800 CodeSegStack.CurrentValue)
10801 return SectionAttr::CreateImplicit(
10802 getASTContext(), CodeSegStack.CurrentValue->getString(),
10803 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate);
10804 return nullptr;
10805}
10806
10807/// Determines if we can perform a correct type check for \p D as a
10808/// redeclaration of \p PrevDecl. If not, we can generally still perform a
10809/// best-effort check.
10810///
10811/// \param NewD The new declaration.
10812/// \param OldD The old declaration.
10813/// \param NewT The portion of the type of the new declaration to check.
10814/// \param OldT The portion of the type of the old declaration to check.
10815bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
10816 QualType NewT, QualType OldT) {
10817 if (!NewD->getLexicalDeclContext()->isDependentContext())
10818 return true;
10819
10820 // For dependently-typed local extern declarations and friends, we can't
10821 // perform a correct type check in general until instantiation:
10822 //
10823 // int f();
10824 // template<typename T> void g() { T f(); }
10825 //
10826 // (valid if g() is only instantiated with T = int).
10827 if (NewT->isDependentType() &&
10828 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
10829 return false;
10830
10831 // Similarly, if the previous declaration was a dependent local extern
10832 // declaration, we don't really know its type yet.
10833 if (OldT->isDependentType() && OldD->isLocalExternDecl())
10834 return false;
10835
10836 return true;
10837}
10838
10839/// Checks if the new declaration declared in dependent context must be
10840/// put in the same redeclaration chain as the specified declaration.
10841///
10842/// \param D Declaration that is checked.
10843/// \param PrevDecl Previous declaration found with proper lookup method for the
10844/// same declaration name.
10845/// \returns True if D must be added to the redeclaration chain which PrevDecl
10846/// belongs to.
10847///
10848bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
10849 if (!D->getLexicalDeclContext()->isDependentContext())
10850 return true;
10851
10852 // Don't chain dependent friend function definitions until instantiation, to
10853 // permit cases like
10854 //
10855 // void func();
10856 // template<typename T> class C1 { friend void func() {} };
10857 // template<typename T> class C2 { friend void func() {} };
10858 //
10859 // ... which is valid if only one of C1 and C2 is ever instantiated.
10860 //
10861 // FIXME: This need only apply to function definitions. For now, we proxy
10862 // this by checking for a file-scope function. We do not want this to apply
10863 // to friend declarations nominating member functions, because that gets in
10864 // the way of access checks.
10865 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
10866 return false;
10867
10868 auto *VD = dyn_cast<ValueDecl>(D);
10869 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
10870 return !VD || !PrevVD ||
10871 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
10872 PrevVD->getType());
10873}
10874
10875/// Check the target or target_version attribute of the function for
10876/// MultiVersion validity.
10877///
10878/// Returns true if there was an error, false otherwise.
10879static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
10880 const auto *TA = FD->getAttr<TargetAttr>();
10881 const auto *TVA = FD->getAttr<TargetVersionAttr>();
10882 assert((static_cast <bool> ((TA || TVA) && "MultiVersion candidate requires a target or target_version attribute"
) ? void (0) : __assert_fail ("(TA || TVA) && \"MultiVersion candidate requires a target or target_version attribute\""
, "clang/lib/Sema/SemaDecl.cpp", 10884, __extension__ __PRETTY_FUNCTION__
))
10883 (TA || TVA) &&(static_cast <bool> ((TA || TVA) && "MultiVersion candidate requires a target or target_version attribute"
) ? void (0) : __assert_fail ("(TA || TVA) && \"MultiVersion candidate requires a target or target_version attribute\""
, "clang/lib/Sema/SemaDecl.cpp", 10884, __extension__ __PRETTY_FUNCTION__
))
10884 "MultiVersion candidate requires a target or target_version attribute")(static_cast <bool> ((TA || TVA) && "MultiVersion candidate requires a target or target_version attribute"
) ? void (0) : __assert_fail ("(TA || TVA) && \"MultiVersion candidate requires a target or target_version attribute\""
, "clang/lib/Sema/SemaDecl.cpp", 10884, __extension__ __PRETTY_FUNCTION__
))
;
10885 const TargetInfo &TargetInfo = S.Context.getTargetInfo();
10886 enum ErrType { Feature = 0, Architecture = 1 };
10887
10888 if (TA) {
10889 ParsedTargetAttr ParseInfo =
10890 S.getASTContext().getTargetInfo().parseTargetAttr(TA->getFeaturesStr());
10891 if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(ParseInfo.CPU)) {
10892 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10893 << Architecture << ParseInfo.CPU;
10894 return true;
10895 }
10896 for (const auto &Feat : ParseInfo.Features) {
10897 auto BareFeat = StringRef{Feat}.substr(1);
10898 if (Feat[0] == '-') {
10899 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10900 << Feature << ("no-" + BareFeat).str();
10901 return true;
10902 }
10903
10904 if (!TargetInfo.validateCpuSupports(BareFeat) ||
10905 !TargetInfo.isValidFeatureName(BareFeat)) {
10906 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10907 << Feature << BareFeat;
10908 return true;
10909 }
10910 }
10911 }
10912
10913 if (TVA) {
10914 llvm::SmallVector<StringRef, 8> Feats;
10915 TVA->getFeatures(Feats);
10916 for (const auto &Feat : Feats) {
10917 if (!TargetInfo.validateCpuSupports(Feat)) {
10918 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10919 << Feature << Feat;
10920 return true;
10921 }
10922 }
10923 }
10924 return false;
10925}
10926
10927// Provide a white-list of attributes that are allowed to be combined with
10928// multiversion functions.
10929static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
10930 MultiVersionKind MVKind) {
10931 // Note: this list/diagnosis must match the list in
10932 // checkMultiversionAttributesAllSame.
10933 switch (Kind) {
10934 default:
10935 return false;
10936 case attr::Used:
10937 return MVKind == MultiVersionKind::Target;
10938 case attr::NonNull:
10939 case attr::NoThrow:
10940 return true;
10941 }
10942}
10943
10944static bool checkNonMultiVersionCompatAttributes(Sema &S,
10945 const FunctionDecl *FD,
10946 const FunctionDecl *CausedFD,
10947 MultiVersionKind MVKind) {
10948 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
10949 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
10950 << static_cast<unsigned>(MVKind) << A;
10951 if (CausedFD)
10952 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
10953 return true;
10954 };
10955
10956 for (const Attr *A : FD->attrs()) {
10957 switch (A->getKind()) {
10958 case attr::CPUDispatch:
10959 case attr::CPUSpecific:
10960 if (MVKind != MultiVersionKind::CPUDispatch &&
10961 MVKind != MultiVersionKind::CPUSpecific)
10962 return Diagnose(S, A);
10963 break;
10964 case attr::Target:
10965 if (MVKind != MultiVersionKind::Target)
10966 return Diagnose(S, A);
10967 break;
10968 case attr::TargetVersion:
10969 if (MVKind != MultiVersionKind::TargetVersion)
10970 return Diagnose(S, A);
10971 break;
10972 case attr::TargetClones:
10973 if (MVKind != MultiVersionKind::TargetClones)
10974 return Diagnose(S, A);
10975 break;
10976 default:
10977 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
10978 return Diagnose(S, A);
10979 break;
10980 }
10981 }
10982 return false;
10983}
10984
10985bool Sema::areMultiversionVariantFunctionsCompatible(
10986 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10987 const PartialDiagnostic &NoProtoDiagID,
10988 const PartialDiagnosticAt &NoteCausedDiagIDAt,
10989 const PartialDiagnosticAt &NoSupportDiagIDAt,
10990 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10991 bool ConstexprSupported, bool CLinkageMayDiffer) {
10992 enum DoesntSupport {
10993 FuncTemplates = 0,
10994 VirtFuncs = 1,
10995 DeducedReturn = 2,
10996 Constructors = 3,
10997 Destructors = 4,
10998 DeletedFuncs = 5,
10999 DefaultedFuncs = 6,
11000 ConstexprFuncs = 7,
11001 ConstevalFuncs = 8,
11002 Lambda = 9,
11003 };
11004 enum Different {
11005 CallingConv = 0,
11006 ReturnType = 1,
11007 ConstexprSpec = 2,
11008 InlineSpec = 3,
11009 Linkage = 4,
11010 LanguageLinkage = 5,
11011 };
11012
11013 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
11014 !OldFD->getType()->getAs<FunctionProtoType>()) {
11015 Diag(OldFD->getLocation(), NoProtoDiagID);
11016 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
11017 return true;
11018 }
11019
11020 if (NoProtoDiagID.getDiagID() != 0 &&
11021 !NewFD->getType()->getAs<FunctionProtoType>())
11022 return Diag(NewFD->getLocation(), NoProtoDiagID);
11023
11024 if (!TemplatesSupported &&
11025 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
11026 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11027 << FuncTemplates;
11028
11029 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
11030 if (NewCXXFD->isVirtual())
11031 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11032 << VirtFuncs;
11033
11034 if (isa<CXXConstructorDecl>(NewCXXFD))
11035 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11036 << Constructors;
11037
11038 if (isa<CXXDestructorDecl>(NewCXXFD))
11039 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11040 << Destructors;
11041 }
11042
11043 if (NewFD->isDeleted())
11044 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11045 << DeletedFuncs;
11046
11047 if (NewFD->isDefaulted())
11048 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11049 << DefaultedFuncs;
11050
11051 if (!ConstexprSupported && NewFD->isConstexpr())
11052 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11053 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11054
11055 QualType NewQType = Context.getCanonicalType(NewFD->getType());
11056 const auto *NewType = cast<FunctionType>(NewQType);
11057 QualType NewReturnType = NewType->getReturnType();
11058
11059 if (NewReturnType->isUndeducedType())
11060 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11061 << DeducedReturn;
11062
11063 // Ensure the return type is identical.
11064 if (OldFD) {
11065 QualType OldQType = Context.getCanonicalType(OldFD->getType());
11066 const auto *OldType = cast<FunctionType>(OldQType);
11067 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11068 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11069
11070 if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
11071 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
11072
11073 QualType OldReturnType = OldType->getReturnType();
11074
11075 if (OldReturnType != NewReturnType)
11076 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
11077
11078 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11079 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
11080
11081 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11082 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
11083
11084 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11085 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
11086
11087 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11088 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
11089
11090 if (CheckEquivalentExceptionSpec(
11091 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
11092 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
11093 return true;
11094 }
11095 return false;
11096}
11097
11098static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
11099 const FunctionDecl *NewFD,
11100 bool CausesMV,
11101 MultiVersionKind MVKind) {
11102 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
11103 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
11104 if (OldFD)
11105 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11106 return true;
11107 }
11108
11109 bool IsCPUSpecificCPUDispatchMVKind =
11110 MVKind == MultiVersionKind::CPUDispatch ||
11111 MVKind == MultiVersionKind::CPUSpecific;
11112
11113 if (CausesMV && OldFD &&
11114 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
11115 return true;
11116
11117 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
11118 return true;
11119
11120 // Only allow transition to MultiVersion if it hasn't been used.
11121 if (OldFD && CausesMV && OldFD->isUsed(false))
11122 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11123
11124 return S.areMultiversionVariantFunctionsCompatible(
11125 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
11126 PartialDiagnosticAt(NewFD->getLocation(),
11127 S.PDiag(diag::note_multiversioning_caused_here)),
11128 PartialDiagnosticAt(NewFD->getLocation(),
11129 S.PDiag(diag::err_multiversion_doesnt_support)
11130 << static_cast<unsigned>(MVKind)),
11131 PartialDiagnosticAt(NewFD->getLocation(),
11132 S.PDiag(diag::err_multiversion_diff)),
11133 /*TemplatesSupported=*/false,
11134 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11135 /*CLinkageMayDiffer=*/false);
11136}
11137
11138/// Check the validity of a multiversion function declaration that is the
11139/// first of its kind. Also sets the multiversion'ness' of the function itself.
11140///
11141/// This sets NewFD->isInvalidDecl() to true if there was an error.
11142///
11143/// Returns true if there was an error, false otherwise.
11144static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD) {
11145 MultiVersionKind MVKind = FD->getMultiVersionKind();
11146 assert(MVKind != MultiVersionKind::None &&(static_cast <bool> (MVKind != MultiVersionKind::None &&
"Function lacks multiversion attribute") ? void (0) : __assert_fail
("MVKind != MultiVersionKind::None && \"Function lacks multiversion attribute\""
, "clang/lib/Sema/SemaDecl.cpp", 11147, __extension__ __PRETTY_FUNCTION__
))
11147 "Function lacks multiversion attribute")(static_cast <bool> (MVKind != MultiVersionKind::None &&
"Function lacks multiversion attribute") ? void (0) : __assert_fail
("MVKind != MultiVersionKind::None && \"Function lacks multiversion attribute\""
, "clang/lib/Sema/SemaDecl.cpp", 11147, __extension__ __PRETTY_FUNCTION__
))
;
11148 const auto *TA = FD->getAttr<TargetAttr>();
11149 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11150 // Target and target_version only causes MV if it is default, otherwise this
11151 // is a normal function.
11152 if ((TA && !TA->isDefaultVersion()) || (TVA && !TVA->isDefaultVersion()))
11153 return false;
11154
11155 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11156 FD->setInvalidDecl();
11157 return true;
11158 }
11159
11160 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
11161 FD->setInvalidDecl();
11162 return true;
11163 }
11164
11165 FD->setIsMultiVersion();
11166 return false;
11167}
11168
11169static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
11170 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11171 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
11172 return true;
11173 }
11174
11175 return false;
11176}
11177
11178static bool CheckTargetCausesMultiVersioning(Sema &S, FunctionDecl *OldFD,
11179 FunctionDecl *NewFD,
11180 bool &Redeclaration,
11181 NamedDecl *&OldDecl,
11182 LookupResult &Previous) {
11183 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11184 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11185 const auto *OldTA = OldFD->getAttr<TargetAttr>();
11186 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11187 // If the old decl is NOT MultiVersioned yet, and we don't cause that
11188 // to change, this is a simple redeclaration.
11189 if ((NewTA && !NewTA->isDefaultVersion() &&
11190 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) ||
11191 (NewTVA && !NewTVA->isDefaultVersion() &&
11192 (!OldTVA || OldTVA->getName() == NewTVA->getName())))
11193 return false;
11194
11195 // Otherwise, this decl causes MultiVersioning.
11196 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
11197 NewTVA ? MultiVersionKind::TargetVersion
11198 : MultiVersionKind::Target)) {
11199 NewFD->setInvalidDecl();
11200 return true;
11201 }
11202
11203 if (CheckMultiVersionValue(S, NewFD)) {
11204 NewFD->setInvalidDecl();
11205 return true;
11206 }
11207
11208 // If this is 'default', permit the forward declaration.
11209 if (!OldFD->isMultiVersion() &&
11210 ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
11211 (NewTVA && NewTVA->isDefaultVersion() && !OldTVA))) {
11212 Redeclaration = true;
11213 OldDecl = OldFD;
11214 OldFD->setIsMultiVersion();
11215 NewFD->setIsMultiVersion();
11216 return false;
11217 }
11218
11219 if (CheckMultiVersionValue(S, OldFD)) {
11220 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11221 NewFD->setInvalidDecl();
11222 return true;
11223 }
11224
11225 if (NewTA) {
11226 ParsedTargetAttr OldParsed =
11227 S.getASTContext().getTargetInfo().parseTargetAttr(
11228 OldTA->getFeaturesStr());
11229 llvm::sort(OldParsed.Features);
11230 ParsedTargetAttr NewParsed =
11231 S.getASTContext().getTargetInfo().parseTargetAttr(
11232 NewTA->getFeaturesStr());
11233 // Sort order doesn't matter, it just needs to be consistent.
11234 llvm::sort(NewParsed.Features);
11235 if (OldParsed == NewParsed) {
11236 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11237 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11238 NewFD->setInvalidDecl();
11239 return true;
11240 }
11241 }
11242
11243 if (NewTVA) {
11244 llvm::SmallVector<StringRef, 8> Feats;
11245 OldTVA->getFeatures(Feats);
11246 llvm::sort(Feats);
11247 llvm::SmallVector<StringRef, 8> NewFeats;
11248 NewTVA->getFeatures(NewFeats);
11249 llvm::sort(NewFeats);
11250
11251 if (Feats == NewFeats) {
11252 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11253 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11254 NewFD->setInvalidDecl();
11255 return true;
11256 }
11257 }
11258
11259 for (const auto *FD : OldFD->redecls()) {
11260 const auto *CurTA = FD->getAttr<TargetAttr>();
11261 const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
11262 // We allow forward declarations before ANY multiversioning attributes, but
11263 // nothing after the fact.
11264 if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
11265 ((NewTA && (!CurTA || CurTA->isInherited())) ||
11266 (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
11267 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
11268 << (NewTA ? 0 : 2);
11269 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11270 NewFD->setInvalidDecl();
11271 return true;
11272 }
11273 }
11274
11275 OldFD->setIsMultiVersion();
11276 NewFD->setIsMultiVersion();
11277 Redeclaration = false;
11278 OldDecl = nullptr;
11279 Previous.clear();
11280 return false;
11281}
11282
11283static bool MultiVersionTypesCompatible(MultiVersionKind Old,
11284 MultiVersionKind New) {
11285 if (Old == New || Old == MultiVersionKind::None ||
11286 New == MultiVersionKind::None)
11287 return true;
11288
11289 return (Old == MultiVersionKind::CPUDispatch &&
11290 New == MultiVersionKind::CPUSpecific) ||
11291 (Old == MultiVersionKind::CPUSpecific &&
11292 New == MultiVersionKind::CPUDispatch);
11293}
11294
11295/// Check the validity of a new function declaration being added to an existing
11296/// multiversioned declaration collection.
11297static bool CheckMultiVersionAdditionalDecl(
11298 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
11299 MultiVersionKind NewMVKind, const CPUDispatchAttr *NewCPUDisp,
11300 const CPUSpecificAttr *NewCPUSpec, const TargetClonesAttr *NewClones,
11301 bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous) {
11302 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11303 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11304 MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
11305 // Disallow mixing of multiversioning types.
11306 if (!MultiVersionTypesCompatible(OldMVKind, NewMVKind)) {
11307 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
11308 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11309 NewFD->setInvalidDecl();
11310 return true;
11311 }
11312
11313 ParsedTargetAttr NewParsed;
11314 if (NewTA) {
11315 NewParsed = S.getASTContext().getTargetInfo().parseTargetAttr(
11316 NewTA->getFeaturesStr());
11317 llvm::sort(NewParsed.Features);
11318 }
11319 llvm::SmallVector<StringRef, 8> NewFeats;
11320 if (NewTVA) {
11321 NewTVA->getFeatures(NewFeats);
11322 llvm::sort(NewFeats);
11323 }
11324
11325 bool UseMemberUsingDeclRules =
11326 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
11327
11328 bool MayNeedOverloadableChecks =
11329 AllowOverloadingOfFunction(Previous, S.Context, NewFD);
11330
11331 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
11332 // of a previous member of the MultiVersion set.
11333 for (NamedDecl *ND : Previous) {
11334 FunctionDecl *CurFD = ND->getAsFunction();
11335 if (!CurFD || CurFD->isInvalidDecl())
11336 continue;
11337 if (MayNeedOverloadableChecks &&
11338 S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
11339 continue;
11340
11341 if (NewMVKind == MultiVersionKind::None &&
11342 OldMVKind == MultiVersionKind::TargetVersion) {
11343 NewFD->addAttr(TargetVersionAttr::CreateImplicit(
11344 S.Context, "default", NewFD->getSourceRange()));
11345 NewFD->setIsMultiVersion();
11346 NewMVKind = MultiVersionKind::TargetVersion;
11347 if (!NewTVA) {
11348 NewTVA = NewFD->getAttr<TargetVersionAttr>();
11349 NewTVA->getFeatures(NewFeats);
11350 llvm::sort(NewFeats);
11351 }
11352 }
11353
11354 switch (NewMVKind) {
11355 case MultiVersionKind::None:
11356 assert(OldMVKind == MultiVersionKind::TargetClones &&(static_cast <bool> (OldMVKind == MultiVersionKind::TargetClones
&& "Only target_clones can be omitted in subsequent declarations"
) ? void (0) : __assert_fail ("OldMVKind == MultiVersionKind::TargetClones && \"Only target_clones can be omitted in subsequent declarations\""
, "clang/lib/Sema/SemaDecl.cpp", 11357, __extension__ __PRETTY_FUNCTION__
))
11357 "Only target_clones can be omitted in subsequent declarations")(static_cast <bool> (OldMVKind == MultiVersionKind::TargetClones
&& "Only target_clones can be omitted in subsequent declarations"
) ? void (0) : __assert_fail ("OldMVKind == MultiVersionKind::TargetClones && \"Only target_clones can be omitted in subsequent declarations\""
, "clang/lib/Sema/SemaDecl.cpp", 11357, __extension__ __PRETTY_FUNCTION__
))
;
11358 break;
11359 case MultiVersionKind::Target: {
11360 const auto *CurTA = CurFD->getAttr<TargetAttr>();
11361 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
11362 NewFD->setIsMultiVersion();
11363 Redeclaration = true;
11364 OldDecl = ND;
11365 return false;
11366 }
11367
11368 ParsedTargetAttr CurParsed =
11369 S.getASTContext().getTargetInfo().parseTargetAttr(
11370 CurTA->getFeaturesStr());
11371 llvm::sort(CurParsed.Features);
11372 if (CurParsed == NewParsed) {
11373 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11374 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11375 NewFD->setInvalidDecl();
11376 return true;
11377 }
11378 break;
11379 }
11380 case MultiVersionKind::TargetVersion: {
11381 const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>();
11382 if (CurTVA->getName() == NewTVA->getName()) {
11383 NewFD->setIsMultiVersion();
11384 Redeclaration = true;
11385 OldDecl = ND;
11386 return false;
11387 }
11388 llvm::SmallVector<StringRef, 8> CurFeats;
11389 if (CurTVA) {
11390 CurTVA->getFeatures(CurFeats);
11391 llvm::sort(CurFeats);
11392 }
11393 if (CurFeats == NewFeats) {
11394 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11395 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11396 NewFD->setInvalidDecl();
11397 return true;
11398 }
11399 break;
11400 }
11401 case MultiVersionKind::TargetClones: {
11402 const auto *CurClones = CurFD->getAttr<TargetClonesAttr>();
11403 Redeclaration = true;
11404 OldDecl = CurFD;
11405 NewFD->setIsMultiVersion();
11406
11407 if (CurClones && NewClones &&
11408 (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
11409 !std::equal(CurClones->featuresStrs_begin(),
11410 CurClones->featuresStrs_end(),
11411 NewClones->featuresStrs_begin()))) {
11412 S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
11413 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11414 NewFD->setInvalidDecl();
11415 return true;
11416 }
11417
11418 return false;
11419 }
11420 case MultiVersionKind::CPUSpecific:
11421 case MultiVersionKind::CPUDispatch: {
11422 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
11423 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
11424 // Handle CPUDispatch/CPUSpecific versions.
11425 // Only 1 CPUDispatch function is allowed, this will make it go through
11426 // the redeclaration errors.
11427 if (NewMVKind == MultiVersionKind::CPUDispatch &&
11428 CurFD->hasAttr<CPUDispatchAttr>()) {
11429 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
11430 std::equal(
11431 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
11432 NewCPUDisp->cpus_begin(),
11433 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11434 return Cur->getName() == New->getName();
11435 })) {
11436 NewFD->setIsMultiVersion();
11437 Redeclaration = true;
11438 OldDecl = ND;
11439 return false;
11440 }
11441
11442 // If the declarations don't match, this is an error condition.
11443 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
11444 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11445 NewFD->setInvalidDecl();
11446 return true;
11447 }
11448 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
11449 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
11450 std::equal(
11451 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
11452 NewCPUSpec->cpus_begin(),
11453 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11454 return Cur->getName() == New->getName();
11455 })) {
11456 NewFD->setIsMultiVersion();
11457 Redeclaration = true;
11458 OldDecl = ND;
11459 return false;
11460 }
11461
11462 // Only 1 version of CPUSpecific is allowed for each CPU.
11463 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
11464 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
11465 if (CurII == NewII) {
11466 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
11467 << NewII;
11468 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11469 NewFD->setInvalidDecl();
11470 return true;
11471 }
11472 }
11473 }
11474 }
11475 break;
11476 }
11477 }
11478 }
11479
11480 // Else, this is simply a non-redecl case. Checking the 'value' is only
11481 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
11482 // handled in the attribute adding step.
11483 if ((NewMVKind == MultiVersionKind::TargetVersion ||
11484 NewMVKind == MultiVersionKind::Target) &&
11485 CheckMultiVersionValue(S, NewFD)) {
11486 NewFD->setInvalidDecl();
11487 return true;
11488 }
11489
11490 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
11491 !OldFD->isMultiVersion(), NewMVKind)) {
11492 NewFD->setInvalidDecl();
11493 return true;
11494 }
11495
11496 // Permit forward declarations in the case where these two are compatible.
11497 if (!OldFD->isMultiVersion()) {
11498 OldFD->setIsMultiVersion();
11499 NewFD->setIsMultiVersion();
11500 Redeclaration = true;
11501 OldDecl = OldFD;
11502 return false;
11503 }
11504
11505 NewFD->setIsMultiVersion();
11506 Redeclaration = false;
11507 OldDecl = nullptr;
11508 Previous.clear();
11509 return false;
11510}
11511
11512/// Check the validity of a mulitversion function declaration.
11513/// Also sets the multiversion'ness' of the function itself.
11514///
11515/// This sets NewFD->isInvalidDecl() to true if there was an error.
11516///
11517/// Returns true if there was an error, false otherwise.
11518static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
11519 bool &Redeclaration, NamedDecl *&OldDecl,
11520 LookupResult &Previous) {
11521 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11522 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11523 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
11524 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
11525 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
11526 MultiVersionKind MVKind = NewFD->getMultiVersionKind();
11527
11528 // Main isn't allowed to become a multiversion function, however it IS
11529 // permitted to have 'main' be marked with the 'target' optimization hint,
11530 // for 'target_version' only default is allowed.
11531 if (NewFD->isMain()) {
11532 if (MVKind != MultiVersionKind::None &&
11533 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
11534 !(MVKind == MultiVersionKind::TargetVersion &&
11535 NewTVA->isDefaultVersion())) {
11536 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
11537 NewFD->setInvalidDecl();
11538 return true;
11539 }
11540 return false;
11541 }
11542
11543 if (!OldDecl || !OldDecl->getAsFunction() ||
11544 OldDecl->getDeclContext()->getRedeclContext() !=
11545 NewFD->getDeclContext()->getRedeclContext()) {
11546 // If there's no previous declaration, AND this isn't attempting to cause
11547 // multiversioning, this isn't an error condition.
11548 if (MVKind == MultiVersionKind::None)
11549 return false;
11550 return CheckMultiVersionFirstFunction(S, NewFD);
11551 }
11552
11553 FunctionDecl *OldFD = OldDecl->getAsFunction();
11554
11555 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None) {
11556 // No target_version attributes mean default
11557 if (!NewTVA) {
11558 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11559 if (OldTVA) {
11560 NewFD->addAttr(TargetVersionAttr::CreateImplicit(
11561 S.Context, "default", NewFD->getSourceRange()));
11562 NewFD->setIsMultiVersion();
11563 OldFD->setIsMultiVersion();
11564 OldDecl = OldFD;
11565 Redeclaration = true;
11566 return true;
11567 }
11568 }
11569 return false;
11570 }
11571
11572 // Multiversioned redeclarations aren't allowed to omit the attribute, except
11573 // for target_clones and target_version.
11574 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
11575 OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones &&
11576 OldFD->getMultiVersionKind() != MultiVersionKind::TargetVersion) {
11577 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
11578 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
11579 NewFD->setInvalidDecl();
11580 return true;
11581 }
11582
11583 if (!OldFD->isMultiVersion()) {
11584 switch (MVKind) {
11585 case MultiVersionKind::Target:
11586 case MultiVersionKind::TargetVersion:
11587 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, Redeclaration,
11588 OldDecl, Previous);
11589 case MultiVersionKind::TargetClones:
11590 if (OldFD->isUsed(false)) {
11591 NewFD->setInvalidDecl();
11592 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11593 }
11594 OldFD->setIsMultiVersion();
11595 break;
11596
11597 case MultiVersionKind::CPUDispatch:
11598 case MultiVersionKind::CPUSpecific:
11599 case MultiVersionKind::None:
11600 break;
11601 }
11602 }
11603
11604 // At this point, we have a multiversion function decl (in OldFD) AND an
11605 // appropriate attribute in the current function decl. Resolve that these are
11606 // still compatible with previous declarations.
11607 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, MVKind, NewCPUDisp,
11608 NewCPUSpec, NewClones, Redeclaration,
11609 OldDecl, Previous);
11610}
11611
11612/// Perform semantic checking of a new function declaration.
11613///
11614/// Performs semantic analysis of the new function declaration
11615/// NewFD. This routine performs all semantic checking that does not
11616/// require the actual declarator involved in the declaration, and is
11617/// used both for the declaration of functions as they are parsed
11618/// (called via ActOnDeclarator) and for the declaration of functions
11619/// that have been instantiated via C++ template instantiation (called
11620/// via InstantiateDecl).
11621///
11622/// \param IsMemberSpecialization whether this new function declaration is
11623/// a member specialization (that replaces any definition provided by the
11624/// previous declaration).
11625///
11626/// This sets NewFD->isInvalidDecl() to true if there was an error.
11627///
11628/// \returns true if the function declaration is a redeclaration.
11629bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
11630 LookupResult &Previous,
11631 bool IsMemberSpecialization,
11632 bool DeclIsDefn) {
11633 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&(static_cast <bool> (!NewFD->getReturnType()->isVariablyModifiedType
() && "Variably modified return types are not handled here"
) ? void (0) : __assert_fail ("!NewFD->getReturnType()->isVariablyModifiedType() && \"Variably modified return types are not handled here\""
, "clang/lib/Sema/SemaDecl.cpp", 11634, __extension__ __PRETTY_FUNCTION__
))
11634 "Variably modified return types are not handled here")(static_cast <bool> (!NewFD->getReturnType()->isVariablyModifiedType
() && "Variably modified return types are not handled here"
) ? void (0) : __assert_fail ("!NewFD->getReturnType()->isVariablyModifiedType() && \"Variably modified return types are not handled here\""
, "clang/lib/Sema/SemaDecl.cpp", 11634, __extension__ __PRETTY_FUNCTION__
))
;
11635
11636 // Determine whether the type of this function should be merged with
11637 // a previous visible declaration. This never happens for functions in C++,
11638 // and always happens in C if the previous declaration was visible.
11639 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
11640 !Previous.isShadowed();
11641
11642 bool Redeclaration = false;
11643 NamedDecl *OldDecl = nullptr;
11644 bool MayNeedOverloadableChecks = false;
11645
11646 // Merge or overload the declaration with an existing declaration of
11647 // the same name, if appropriate.
11648 if (!Previous.empty()) {
11649 // Determine whether NewFD is an overload of PrevDecl or
11650 // a declaration that requires merging. If it's an overload,
11651 // there's no more work to do here; we'll just add the new
11652 // function to the scope.
11653 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
11654 NamedDecl *Candidate = Previous.getRepresentativeDecl();
11655 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
11656 Redeclaration = true;
11657 OldDecl = Candidate;
11658 }
11659 } else {
11660 MayNeedOverloadableChecks = true;
11661 switch (CheckOverload(S, NewFD, Previous, OldDecl,
11662 /*NewIsUsingDecl*/ false)) {
11663 case Ovl_Match:
11664 Redeclaration = true;
11665 break;
11666
11667 case Ovl_NonFunction:
11668 Redeclaration = true;
11669 break;
11670
11671 case Ovl_Overload:
11672 Redeclaration = false;
11673 break;
11674 }
11675 }
11676 }
11677
11678 // Check for a previous extern "C" declaration with this name.
11679 if (!Redeclaration &&
11680 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
11681 if (!Previous.empty()) {
11682 // This is an extern "C" declaration with the same name as a previous
11683 // declaration, and thus redeclares that entity...
11684 Redeclaration = true;
11685 OldDecl = Previous.getFoundDecl();
11686 MergeTypeWithPrevious = false;
11687
11688 // ... except in the presence of __attribute__((overloadable)).
11689 if (OldDecl->hasAttr<OverloadableAttr>() ||
11690 NewFD->hasAttr<OverloadableAttr>()) {
11691 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
11692 MayNeedOverloadableChecks = true;
11693 Redeclaration = false;
11694 OldDecl = nullptr;
11695 }
11696 }
11697 }
11698 }
11699
11700 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
11701 return Redeclaration;
11702
11703 // PPC MMA non-pointer types are not allowed as function return types.
11704 if (Context.getTargetInfo().getTriple().isPPC64() &&
11705 CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
11706 NewFD->setInvalidDecl();
11707 }
11708
11709 // C++11 [dcl.constexpr]p8:
11710 // A constexpr specifier for a non-static member function that is not
11711 // a constructor declares that member function to be const.
11712 //
11713 // This needs to be delayed until we know whether this is an out-of-line
11714 // definition of a static member function.
11715 //
11716 // This rule is not present in C++1y, so we produce a backwards
11717 // compatibility warning whenever it happens in C++11.
11718 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
11719 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
11720 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
11721 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
11722 CXXMethodDecl *OldMD = nullptr;
11723 if (OldDecl)
11724 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
11725 if (!OldMD || !OldMD->isStatic()) {
11726 const FunctionProtoType *FPT =
11727 MD->getType()->castAs<FunctionProtoType>();
11728 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11729 EPI.TypeQuals.addConst();
11730 MD->setType(Context.getFunctionType(FPT->getReturnType(),
11731 FPT->getParamTypes(), EPI));
11732
11733 // Warn that we did this, if we're not performing template instantiation.
11734 // In that case, we'll have warned already when the template was defined.
11735 if (!inTemplateInstantiation()) {
11736 SourceLocation AddConstLoc;
11737 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
11738 .IgnoreParens().getAs<FunctionTypeLoc>())
11739 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
11740
11741 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
11742 << FixItHint::CreateInsertion(AddConstLoc, " const");
11743 }
11744 }
11745 }
11746
11747 if (Redeclaration) {
11748 // NewFD and OldDecl represent declarations that need to be
11749 // merged.
11750 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
11751 DeclIsDefn)) {
11752 NewFD->setInvalidDecl();
11753 return Redeclaration;
11754 }
11755
11756 Previous.clear();
11757 Previous.addDecl(OldDecl);
11758
11759 if (FunctionTemplateDecl *OldTemplateDecl =
11760 dyn_cast<FunctionTemplateDecl>(OldDecl)) {
11761 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
11762 FunctionTemplateDecl *NewTemplateDecl
11763 = NewFD->getDescribedFunctionTemplate();
11764 assert(NewTemplateDecl && "Template/non-template mismatch")(static_cast <bool> (NewTemplateDecl && "Template/non-template mismatch"
) ? void (0) : __assert_fail ("NewTemplateDecl && \"Template/non-template mismatch\""
, "clang/lib/Sema/SemaDecl.cpp", 11764, __extension__ __PRETTY_FUNCTION__
))
;
11765
11766 // The call to MergeFunctionDecl above may have created some state in
11767 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
11768 // can add it as a redeclaration.
11769 NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
11770
11771 NewFD->setPreviousDeclaration(OldFD);
11772 if (NewFD->isCXXClassMember()) {
11773 NewFD->setAccess(OldTemplateDecl->getAccess());
11774 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
11775 }
11776
11777 // If this is an explicit specialization of a member that is a function
11778 // template, mark it as a member specialization.
11779 if (IsMemberSpecialization &&
11780 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
11781 NewTemplateDecl->setMemberSpecialization();
11782 assert(OldTemplateDecl->isMemberSpecialization())(static_cast <bool> (OldTemplateDecl->isMemberSpecialization
()) ? void (0) : __assert_fail ("OldTemplateDecl->isMemberSpecialization()"
, "clang/lib/Sema/SemaDecl.cpp", 11782, __extension__ __PRETTY_FUNCTION__
))
;
11783 // Explicit specializations of a member template do not inherit deleted
11784 // status from the parent member template that they are specializing.
11785 if (OldFD->isDeleted()) {
11786 // FIXME: This assert will not hold in the presence of modules.
11787 assert(OldFD->getCanonicalDecl() == OldFD)(static_cast <bool> (OldFD->getCanonicalDecl() == OldFD
) ? void (0) : __assert_fail ("OldFD->getCanonicalDecl() == OldFD"
, "clang/lib/Sema/SemaDecl.cpp", 11787, __extension__ __PRETTY_FUNCTION__
))
;
11788 // FIXME: We need an update record for this AST mutation.
11789 OldFD->setDeletedAsWritten(false);
11790 }
11791 }
11792
11793 } else {
11794 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
11795 auto *OldFD = cast<FunctionDecl>(OldDecl);
11796 // This needs to happen first so that 'inline' propagates.
11797 NewFD->setPreviousDeclaration(OldFD);
11798 if (NewFD->isCXXClassMember())
11799 NewFD->setAccess(OldFD->getAccess());
11800 }
11801 }
11802 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
11803 !NewFD->getAttr<OverloadableAttr>()) {
11804 assert((Previous.empty() ||(static_cast <bool> ((Previous.empty() || llvm::any_of(
Previous, [](const NamedDecl *ND) { return ND->hasAttr<
OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present"
) ? void (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\""
, "clang/lib/Sema/SemaDecl.cpp", 11809, __extension__ __PRETTY_FUNCTION__
))
11805 llvm::any_of(Previous,(static_cast <bool> ((Previous.empty() || llvm::any_of(
Previous, [](const NamedDecl *ND) { return ND->hasAttr<
OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present"
) ? void (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\""
, "clang/lib/Sema/SemaDecl.cpp", 11809, __extension__ __PRETTY_FUNCTION__
))
11806 [](const NamedDecl *ND) {(static_cast <bool> ((Previous.empty() || llvm::any_of(
Previous, [](const NamedDecl *ND) { return ND->hasAttr<
OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present"
) ? void (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\""
, "clang/lib/Sema/SemaDecl.cpp", 11809, __extension__ __PRETTY_FUNCTION__
))
11807 return ND->hasAttr<OverloadableAttr>();(static_cast <bool> ((Previous.empty() || llvm::any_of(
Previous, [](const NamedDecl *ND) { return ND->hasAttr<
OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present"
) ? void (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\""
, "clang/lib/Sema/SemaDecl.cpp", 11809, __extension__ __PRETTY_FUNCTION__
))
11808 })) &&(static_cast <bool> ((Previous.empty() || llvm::any_of(
Previous, [](const NamedDecl *ND) { return ND->hasAttr<
OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present"
) ? void (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\""
, "clang/lib/Sema/SemaDecl.cpp", 11809, __extension__ __PRETTY_FUNCTION__
))
11809 "Non-redecls shouldn't happen without overloadable present")(static_cast <bool> ((Previous.empty() || llvm::any_of(
Previous, [](const NamedDecl *ND) { return ND->hasAttr<
OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present"
) ? void (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\""
, "clang/lib/Sema/SemaDecl.cpp", 11809, __extension__ __PRETTY_FUNCTION__
))
;
11810
11811 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
11812 const auto *FD = dyn_cast<FunctionDecl>(ND);
11813 return FD && !FD->hasAttr<OverloadableAttr>();
11814 });
11815
11816 if (OtherUnmarkedIter != Previous.end()) {
11817 Diag(NewFD->getLocation(),
11818 diag::err_attribute_overloadable_multiple_unmarked_overloads);
11819 Diag((*OtherUnmarkedIter)->getLocation(),
11820 diag::note_attribute_overloadable_prev_overload)
11821 << false;
11822
11823 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
11824 }
11825 }
11826
11827 if (LangOpts.OpenMP)
11828 ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
11829
11830 // Semantic checking for this function declaration (in isolation).
11831
11832 if (getLangOpts().CPlusPlus) {
11833 // C++-specific checks.
11834 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
11835 CheckConstructor(Constructor);
11836 } else if (CXXDestructorDecl *Destructor =
11837 dyn_cast<CXXDestructorDecl>(NewFD)) {
11838 // We check here for invalid destructor names.
11839 // If we have a friend destructor declaration that is dependent, we can't
11840 // diagnose right away because cases like this are still valid:
11841 // template <class T> struct A { friend T::X::~Y(); };
11842 // struct B { struct Y { ~Y(); }; using X = Y; };
11843 // template struct A<B>;
11844 if (NewFD->getFriendObjectKind() == Decl::FriendObjectKind::FOK_None ||
11845 !Destructor->getThisType()->isDependentType()) {
11846 CXXRecordDecl *Record = Destructor->getParent();
11847 QualType ClassType = Context.getTypeDeclType(Record);
11848
11849 DeclarationName Name = Context.DeclarationNames.getCXXDestructorName(
11850 Context.getCanonicalType(ClassType));
11851 if (NewFD->getDeclName() != Name) {
11852 Diag(NewFD->getLocation(), diag::err_destructor_name);
11853 NewFD->setInvalidDecl();
11854 return Redeclaration;
11855 }
11856 }
11857 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
11858 if (auto *TD = Guide->getDescribedFunctionTemplate())
11859 CheckDeductionGuideTemplate(TD);
11860
11861 // A deduction guide is not on the list of entities that can be
11862 // explicitly specialized.
11863 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
11864 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
11865 << /*explicit specialization*/ 1;
11866 }
11867
11868 // Find any virtual functions that this function overrides.
11869 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
11870 if (!Method->isFunctionTemplateSpecialization() &&
11871 !Method->getDescribedFunctionTemplate() &&
11872 Method->isCanonicalDecl()) {
11873 AddOverriddenMethods(Method->getParent(), Method);
11874 }
11875 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
11876 // C++2a [class.virtual]p6
11877 // A virtual method shall not have a requires-clause.
11878 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
11879 diag::err_constrained_virtual_method);
11880
11881 if (Method->isStatic())
11882 checkThisInStaticMemberFunctionType(Method);
11883 }
11884
11885 // C++20: dcl.decl.general p4:
11886 // The optional requires-clause ([temp.pre]) in an init-declarator or
11887 // member-declarator shall be present only if the declarator declares a
11888 // templated function ([dcl.fct]).
11889 if (Expr *TRC = NewFD->getTrailingRequiresClause()) {
11890 // [temp.pre]/8:
11891 // An entity is templated if it is
11892 // - a template,
11893 // - an entity defined ([basic.def]) or created ([class.temporary]) in a
11894 // templated entity,
11895 // - a member of a templated entity,
11896 // - an enumerator for an enumeration that is a templated entity, or
11897 // - the closure type of a lambda-expression ([expr.prim.lambda.closure])
11898 // appearing in the declaration of a templated entity. [Note 6: A local
11899 // class, a local or block variable, or a friend function defined in a
11900 // templated entity is a templated entity. — end note]
11901 //
11902 // A templated function is a function template or a function that is
11903 // templated. A templated class is a class template or a class that is
11904 // templated. A templated variable is a variable template or a variable
11905 // that is templated.
11906
11907 if (!NewFD->getDescribedFunctionTemplate() && // -a template
11908 // defined... in a templated entity
11909 !(DeclIsDefn && NewFD->isTemplated()) &&
11910 // a member of a templated entity
11911 !(isa<CXXMethodDecl>(NewFD) && NewFD->isTemplated()) &&
11912 // Don't complain about instantiations, they've already had these
11913 // rules + others enforced.
11914 !NewFD->isTemplateInstantiation()) {
11915 Diag(TRC->getBeginLoc(), diag::err_constrained_non_templated_function);
11916 }
11917 }
11918
11919 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
11920 ActOnConversionDeclarator(Conversion);
11921
11922 // Extra checking for C++ overloaded operators (C++ [over.oper]).
11923 if (NewFD->isOverloadedOperator() &&
11924 CheckOverloadedOperatorDeclaration(NewFD)) {
11925 NewFD->setInvalidDecl();
11926 return Redeclaration;
11927 }
11928
11929 // Extra checking for C++0x literal operators (C++0x [over.literal]).
11930 if (NewFD->getLiteralIdentifier() &&
11931 CheckLiteralOperatorDeclaration(NewFD)) {
11932 NewFD->setInvalidDecl();
11933 return Redeclaration;
11934 }
11935
11936 // In C++, check default arguments now that we have merged decls. Unless
11937 // the lexical context is the class, because in this case this is done
11938 // during delayed parsing anyway.
11939 if (!CurContext->isRecord())
11940 CheckCXXDefaultArguments(NewFD);
11941
11942 // If this function is declared as being extern "C", then check to see if
11943 // the function returns a UDT (class, struct, or union type) that is not C
11944 // compatible, and if it does, warn the user.
11945 // But, issue any diagnostic on the first declaration only.
11946 if (Previous.empty() && NewFD->isExternC()) {
11947 QualType R = NewFD->getReturnType();
11948 if (R->isIncompleteType() && !R->isVoidType())
11949 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
11950 << NewFD << R;
11951 else if (!R.isPODType(Context) && !R->isVoidType() &&
11952 !R->isObjCObjectPointerType())
11953 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
11954 }
11955
11956 // C++1z [dcl.fct]p6:
11957 // [...] whether the function has a non-throwing exception-specification
11958 // [is] part of the function type
11959 //
11960 // This results in an ABI break between C++14 and C++17 for functions whose
11961 // declared type includes an exception-specification in a parameter or
11962 // return type. (Exception specifications on the function itself are OK in
11963 // most cases, and exception specifications are not permitted in most other
11964 // contexts where they could make it into a mangling.)
11965 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
11966 auto HasNoexcept = [&](QualType T) -> bool {
11967 // Strip off declarator chunks that could be between us and a function
11968 // type. We don't need to look far, exception specifications are very
11969 // restricted prior to C++17.
11970 if (auto *RT = T->getAs<ReferenceType>())
11971 T = RT->getPointeeType();
11972 else if (T->isAnyPointerType())
11973 T = T->getPointeeType();
11974 else if (auto *MPT = T->getAs<MemberPointerType>())
11975 T = MPT->getPointeeType();
11976 if (auto *FPT = T->getAs<FunctionProtoType>())
11977 if (FPT->isNothrow())
11978 return true;
11979 return false;
11980 };
11981
11982 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
11983 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
11984 for (QualType T : FPT->param_types())
11985 AnyNoexcept |= HasNoexcept(T);
11986 if (AnyNoexcept)
11987 Diag(NewFD->getLocation(),
11988 diag::warn_cxx17_compat_exception_spec_in_signature)
11989 << NewFD;
11990 }
11991
11992 if (!Redeclaration && LangOpts.CUDA)
11993 checkCUDATargetOverload(NewFD, Previous);
11994 }
11995 return Redeclaration;
11996}
11997
11998void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
11999 // C++11 [basic.start.main]p3:
12000 // A program that [...] declares main to be inline, static or
12001 // constexpr is ill-formed.
12002 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
12003 // appear in a declaration of main.
12004 // static main is not an error under C99, but we should warn about it.
12005 // We accept _Noreturn main as an extension.
12006 if (FD->getStorageClass() == SC_Static)
12007 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
12008 ? diag::err_static_main : diag::warn_static_main)
12009 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
12010 if (FD->isInlineSpecified())
12011 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
12012 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
12013 if (DS.isNoreturnSpecified()) {
12014 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12015 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
12016 Diag(NoreturnLoc, diag::ext_noreturn_main);
12017 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
12018 << FixItHint::CreateRemoval(NoreturnRange);
12019 }
12020 if (FD->isConstexpr()) {
12021 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
12022 << FD->isConsteval()
12023 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
12024 FD->setConstexprKind(ConstexprSpecKind::Unspecified);
12025 }
12026
12027 if (getLangOpts().OpenCL) {
12028 Diag(FD->getLocation(), diag::err_opencl_no_main)
12029 << FD->hasAttr<OpenCLKernelAttr>();
12030 FD->setInvalidDecl();
12031 return;
12032 }
12033
12034 // Functions named main in hlsl are default entries, but don't have specific
12035 // signatures they are required to conform to.
12036 if (getLangOpts().HLSL)
12037 return;
12038
12039 QualType T = FD->getType();
12040 assert(T->isFunctionType() && "function decl is not of function type")(static_cast <bool> (T->isFunctionType() && "function decl is not of function type"
) ? void (0) : __assert_fail ("T->isFunctionType() && \"function decl is not of function type\""
, "clang/lib/Sema/SemaDecl.cpp", 12040, __extension__ __PRETTY_FUNCTION__
))
;
12041 const FunctionType* FT = T->castAs<FunctionType>();
12042
12043 // Set default calling convention for main()
12044 if (FT->getCallConv() != CC_C) {
12045 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
12046 FD->setType(QualType(FT, 0));
12047 T = Context.getCanonicalType(FD->getType());
12048 }
12049
12050 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
12051 // In C with GNU extensions we allow main() to have non-integer return
12052 // type, but we should warn about the extension, and we disable the
12053 // implicit-return-zero rule.
12054
12055 // GCC in C mode accepts qualified 'int'.
12056 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
12057 FD->setHasImplicitReturnZero(true);
12058 else {
12059 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
12060 SourceRange RTRange = FD->getReturnTypeSourceRange();
12061 if (RTRange.isValid())
12062 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
12063 << FixItHint::CreateReplacement(RTRange, "int");
12064 }
12065 } else {
12066 // In C and C++, main magically returns 0 if you fall off the end;
12067 // set the flag which tells us that.
12068 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12069
12070 // All the standards say that main() should return 'int'.
12071 if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
12072 FD->setHasImplicitReturnZero(true);
12073 else {
12074 // Otherwise, this is just a flat-out error.
12075 SourceRange RTRange = FD->getReturnTypeSourceRange();
12076 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
12077 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
12078 : FixItHint());
12079 FD->setInvalidDecl(true);
12080 }
12081 }
12082
12083 // Treat protoless main() as nullary.
12084 if (isa<FunctionNoProtoType>(FT)) return;
12085
12086 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
12087 unsigned nparams = FTP->getNumParams();
12088 assert(FD->getNumParams() == nparams)(static_cast <bool> (FD->getNumParams() == nparams) ?
void (0) : __assert_fail ("FD->getNumParams() == nparams"
, "clang/lib/Sema/SemaDecl.cpp", 12088, __extension__ __PRETTY_FUNCTION__
))
;
12089
12090 bool HasExtraParameters = (nparams > 3);
12091
12092 if (FTP->isVariadic()) {
12093 Diag(FD->getLocation(), diag::ext_variadic_main);
12094 // FIXME: if we had information about the location of the ellipsis, we
12095 // could add a FixIt hint to remove it as a parameter.
12096 }
12097
12098 // Darwin passes an undocumented fourth argument of type char**. If
12099 // other platforms start sprouting these, the logic below will start
12100 // getting shifty.
12101 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12102 HasExtraParameters = false;
12103
12104 if (HasExtraParameters) {
12105 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
12106 FD->setInvalidDecl(true);
12107 nparams = 3;
12108 }
12109
12110 // FIXME: a lot of the following diagnostics would be improved
12111 // if we had some location information about types.
12112
12113 QualType CharPP =
12114 Context.getPointerType(Context.getPointerType(Context.CharTy));
12115 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12116
12117 for (unsigned i = 0; i < nparams; ++i) {
12118 QualType AT = FTP->getParamType(i);
12119
12120 bool mismatch = true;
12121
12122 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
12123 mismatch = false;
12124 else if (Expected[i] == CharPP) {
12125 // As an extension, the following forms are okay:
12126 // char const **
12127 // char const * const *
12128 // char * const *
12129
12130 QualifierCollector qs;
12131 const PointerType* PT;
12132 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
12133 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
12134 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
12135 Context.CharTy)) {
12136 qs.removeConst();
12137 mismatch = !qs.empty();
12138 }
12139 }
12140
12141 if (mismatch) {
12142 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
12143 // TODO: suggest replacing given type with expected type
12144 FD->setInvalidDecl(true);
12145 }
12146 }
12147
12148 if (nparams == 1 && !FD->isInvalidDecl()) {
12149 Diag(FD->getLocation(), diag::warn_main_one_arg);
12150 }
12151
12152 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12153 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12154 FD->setInvalidDecl();
12155 }
12156}
12157
12158static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
12159
12160 // Default calling convention for main and wmain is __cdecl
12161 if (FD->getName() == "main" || FD->getName() == "wmain")
12162 return false;
12163
12164 // Default calling convention for MinGW is __cdecl
12165 const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
12166 if (T.isWindowsGNUEnvironment())
12167 return false;
12168
12169 // Default calling convention for WinMain, wWinMain and DllMain
12170 // is __stdcall on 32 bit Windows
12171 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
12172 return true;
12173
12174 return false;
12175}
12176
12177void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
12178 QualType T = FD->getType();
12179 assert(T->isFunctionType() && "function decl is not of function type")(static_cast <bool> (T->isFunctionType() && "function decl is not of function type"
) ? void (0) : __assert_fail ("T->isFunctionType() && \"function decl is not of function type\""
, "clang/lib/Sema/SemaDecl.cpp", 12179, __extension__ __PRETTY_FUNCTION__
))
;
12180 const FunctionType *FT = T->castAs<FunctionType>();
12181
12182 // Set an implicit return of 'zero' if the function can return some integral,
12183 // enumeration, pointer or nullptr type.
12184 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
12185 FT->getReturnType()->isAnyPointerType() ||
12186 FT->getReturnType()->isNullPtrType())
12187 // DllMain is exempt because a return value of zero means it failed.
12188 if (FD->getName() != "DllMain")
12189 FD->setHasImplicitReturnZero(true);
12190
12191 // Explicity specified calling conventions are applied to MSVC entry points
12192 if (!hasExplicitCallingConv(T)) {
12193 if (isDefaultStdCall(FD, *this)) {
12194 if (FT->getCallConv() != CC_X86StdCall) {
12195 FT = Context.adjustFunctionType(
12196 FT, FT->getExtInfo().withCallingConv(CC_X86StdCall));
12197 FD->setType(QualType(FT, 0));
12198 }
12199 } else if (FT->getCallConv() != CC_C) {
12200 FT = Context.adjustFunctionType(FT,
12201 FT->getExtInfo().withCallingConv(CC_C));
12202 FD->setType(QualType(FT, 0));
12203 }
12204 }
12205
12206 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12207 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12208 FD->setInvalidDecl();
12209 }
12210}
12211
12212void Sema::CheckHLSLEntryPoint(FunctionDecl *FD) {
12213 auto &TargetInfo = getASTContext().getTargetInfo();
12214 auto const Triple = TargetInfo.getTriple();
12215 switch (Triple.getEnvironment()) {
12216 default:
12217 // FIXME: check all shader profiles.
12218 break;
12219 case llvm::Triple::EnvironmentType::Compute:
12220 if (!FD->hasAttr<HLSLNumThreadsAttr>()) {
12221 Diag(FD->getLocation(), diag::err_hlsl_missing_numthreads)
12222 << Triple.getEnvironmentName();
12223 FD->setInvalidDecl();
12224 }
12225 break;
12226 }
12227
12228 for (const auto *Param : FD->parameters()) {
12229 if (!Param->hasAttr<HLSLAnnotationAttr>()) {
12230 // FIXME: Handle struct parameters where annotations are on struct fields.
12231 // See: https://github.com/llvm/llvm-project/issues/57875
12232 Diag(FD->getLocation(), diag::err_hlsl_missing_semantic_annotation);
12233 Diag(Param->getLocation(), diag::note_previous_decl) << Param;
12234 FD->setInvalidDecl();
12235 }
12236 }
12237 // FIXME: Verify return type semantic annotation.
12238}
12239
12240bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
12241 // FIXME: Need strict checking. In C89, we need to check for
12242 // any assignment, increment, decrement, function-calls, or
12243 // commas outside of a sizeof. In C99, it's the same list,
12244 // except that the aforementioned are allowed in unevaluated
12245 // expressions. Everything else falls under the
12246 // "may accept other forms of constant expressions" exception.
12247 //
12248 // Regular C++ code will not end up here (exceptions: language extensions,
12249 // OpenCL C++ etc), so the constant expression rules there don't matter.
12250 if (Init->isValueDependent()) {
12251 assert(Init->containsErrors() &&(static_cast <bool> (Init->containsErrors() &&
"Dependent code should only occur in error-recovery path.") ?
void (0) : __assert_fail ("Init->containsErrors() && \"Dependent code should only occur in error-recovery path.\""
, "clang/lib/Sema/SemaDecl.cpp", 12252, __extension__ __PRETTY_FUNCTION__
))
12252 "Dependent code should only occur in error-recovery path.")(static_cast <bool> (Init->containsErrors() &&
"Dependent code should only occur in error-recovery path.") ?
void (0) : __assert_fail ("Init->containsErrors() && \"Dependent code should only occur in error-recovery path.\""
, "clang/lib/Sema/SemaDecl.cpp", 12252, __extension__ __PRETTY_FUNCTION__
))
;
12253 return true;
12254 }
12255 const Expr *Culprit;
12256 if (Init->isConstantInitializer(Context, false, &Culprit))
12257 return false;
12258 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
12259 << Culprit->getSourceRange();
12260 return true;
12261}
12262
12263namespace {
12264 // Visits an initialization expression to see if OrigDecl is evaluated in
12265 // its own initialization and throws a warning if it does.
12266 class SelfReferenceChecker
12267 : public EvaluatedExprVisitor<SelfReferenceChecker> {
12268 Sema &S;
12269 Decl *OrigDecl;
12270 bool isRecordType;
12271 bool isPODType;
12272 bool isReferenceType;
12273
12274 bool isInitList;
12275 llvm::SmallVector<unsigned, 4> InitFieldIndex;
12276
12277 public:
12278 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
12279
12280 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
12281 S(S), OrigDecl(OrigDecl) {
12282 isPODType = false;
12283 isRecordType = false;
12284 isReferenceType = false;
12285 isInitList = false;
12286 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
12287 isPODType = VD->getType().isPODType(S.Context);
12288 isRecordType = VD->getType()->isRecordType();
12289 isReferenceType = VD->getType()->isReferenceType();
12290 }
12291 }
12292
12293 // For most expressions, just call the visitor. For initializer lists,
12294 // track the index of the field being initialized since fields are
12295 // initialized in order allowing use of previously initialized fields.
12296 void CheckExpr(Expr *E) {
12297 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
12298 if (!InitList) {
12299 Visit(E);
12300 return;
12301 }
12302
12303 // Track and increment the index here.
12304 isInitList = true;
12305 InitFieldIndex.push_back(0);
12306 for (auto *Child : InitList->children()) {
12307 CheckExpr(cast<Expr>(Child));
12308 ++InitFieldIndex.back();
12309 }
12310 InitFieldIndex.pop_back();
12311 }
12312
12313 // Returns true if MemberExpr is checked and no further checking is needed.
12314 // Returns false if additional checking is required.
12315 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
12316 llvm::SmallVector<FieldDecl*, 4> Fields;
12317 Expr *Base = E;
12318 bool ReferenceField = false;
12319
12320 // Get the field members used.
12321 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12322 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
12323 if (!FD)
12324 return false;
12325 Fields.push_back(FD);
12326 if (FD->getType()->isReferenceType())
12327 ReferenceField = true;
12328 Base = ME->getBase()->IgnoreParenImpCasts();
12329 }
12330
12331 // Keep checking only if the base Decl is the same.
12332 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
12333 if (!DRE || DRE->getDecl() != OrigDecl)
12334 return false;
12335
12336 // A reference field can be bound to an unininitialized field.
12337 if (CheckReference && !ReferenceField)
12338 return true;
12339
12340 // Convert FieldDecls to their index number.
12341 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
12342 for (const FieldDecl *I : llvm::reverse(Fields))
12343 UsedFieldIndex.push_back(I->getFieldIndex());
12344
12345 // See if a warning is needed by checking the first difference in index
12346 // numbers. If field being used has index less than the field being
12347 // initialized, then the use is safe.
12348 for (auto UsedIter = UsedFieldIndex.begin(),
12349 UsedEnd = UsedFieldIndex.end(),
12350 OrigIter = InitFieldIndex.begin(),
12351 OrigEnd = InitFieldIndex.end();
12352 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
12353 if (*UsedIter < *OrigIter)
12354 return true;
12355 if (*UsedIter > *OrigIter)
12356 break;
12357 }
12358
12359 // TODO: Add a different warning which will print the field names.
12360 HandleDeclRefExpr(DRE);
12361 return true;
12362 }
12363
12364 // For most expressions, the cast is directly above the DeclRefExpr.
12365 // For conditional operators, the cast can be outside the conditional
12366 // operator if both expressions are DeclRefExpr's.
12367 void HandleValue(Expr *E) {
12368 E = E->IgnoreParens();
12369 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
12370 HandleDeclRefExpr(DRE);
12371 return;
12372 }
12373
12374 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
12375 Visit(CO->getCond());
12376 HandleValue(CO->getTrueExpr());
12377 HandleValue(CO->getFalseExpr());
12378 return;
12379 }
12380
12381 if (BinaryConditionalOperator *BCO =
12382 dyn_cast<BinaryConditionalOperator>(E)) {
12383 Visit(BCO->getCond());
12384 HandleValue(BCO->getFalseExpr());
12385 return;
12386 }
12387
12388 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
12389 HandleValue(OVE->getSourceExpr());
12390 return;
12391 }
12392
12393 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12394 if (BO->getOpcode() == BO_Comma) {
12395 Visit(BO->getLHS());
12396 HandleValue(BO->getRHS());
12397 return;
12398 }
12399 }
12400
12401 if (isa<MemberExpr>(E)) {
12402 if (isInitList) {
12403 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
12404 false /*CheckReference*/))
12405 return;
12406 }
12407
12408 Expr *Base = E->IgnoreParenImpCasts();
12409 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12410 // Check for static member variables and don't warn on them.
12411 if (!isa<FieldDecl>(ME->getMemberDecl()))
12412 return;
12413 Base = ME->getBase()->IgnoreParenImpCasts();
12414 }
12415 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
12416 HandleDeclRefExpr(DRE);
12417 return;
12418 }
12419
12420 Visit(E);
12421 }
12422
12423 // Reference types not handled in HandleValue are handled here since all
12424 // uses of references are bad, not just r-value uses.
12425 void VisitDeclRefExpr(DeclRefExpr *E) {
12426 if (isReferenceType)
12427 HandleDeclRefExpr(E);
12428 }
12429
12430 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
12431 if (E->getCastKind() == CK_LValueToRValue) {
12432 HandleValue(E->getSubExpr());
12433 return;
12434 }
12435
12436 Inherited::VisitImplicitCastExpr(E);
12437 }
12438
12439 void VisitMemberExpr(MemberExpr *E) {
12440 if (isInitList) {
12441 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
12442 return;
12443 }
12444
12445 // Don't warn on arrays since they can be treated as pointers.
12446 if (E->getType()->canDecayToPointerType()) return;
12447
12448 // Warn when a non-static method call is followed by non-static member
12449 // field accesses, which is followed by a DeclRefExpr.
12450 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
12451 bool Warn = (MD && !MD->isStatic());
12452 Expr *Base = E->getBase()->IgnoreParenImpCasts();
12453 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12454 if (!isa<FieldDecl>(ME->getMemberDecl()))
12455 Warn = false;
12456 Base = ME->getBase()->IgnoreParenImpCasts();
12457 }
12458
12459 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
12460 if (Warn)
12461 HandleDeclRefExpr(DRE);
12462 return;
12463 }
12464
12465 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
12466 // Visit that expression.
12467 Visit(Base);
12468 }
12469
12470 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
12471 Expr *Callee = E->getCallee();
12472
12473 if (isa<UnresolvedLookupExpr>(Callee))
12474 return Inherited::VisitCXXOperatorCallExpr(E);
12475
12476 Visit(Callee);
12477 for (auto Arg: E->arguments())
12478 HandleValue(Arg->IgnoreParenImpCasts());
12479 }
12480
12481 void VisitUnaryOperator(UnaryOperator *E) {
12482 // For POD record types, addresses of its own members are well-defined.
12483 if (E->getOpcode() == UO_AddrOf && isRecordType &&
12484 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
12485 if (!isPODType)
12486 HandleValue(E->getSubExpr());
12487 return;
12488 }
12489
12490 if (E->isIncrementDecrementOp()) {
12491 HandleValue(E->getSubExpr());
12492 return;
12493 }
12494
12495 Inherited::VisitUnaryOperator(E);
12496 }
12497
12498 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
12499
12500 void VisitCXXConstructExpr(CXXConstructExpr *E) {
12501 if (E->getConstructor()->isCopyConstructor()) {
12502 Expr *ArgExpr = E->getArg(0);
12503 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
12504 if (ILE->getNumInits() == 1)
12505 ArgExpr = ILE->getInit(0);
12506 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
12507 if (ICE->getCastKind() == CK_NoOp)
12508 ArgExpr = ICE->getSubExpr();
12509 HandleValue(ArgExpr);
12510 return;
12511 }
12512 Inherited::VisitCXXConstructExpr(E);
12513 }
12514
12515 void VisitCallExpr(CallExpr *E) {
12516 // Treat std::move as a use.
12517 if (E->isCallToStdMove()) {
12518 HandleValue(E->getArg(0));
12519 return;
12520 }
12521
12522 Inherited::VisitCallExpr(E);
12523 }
12524
12525 void VisitBinaryOperator(BinaryOperator *E) {
12526 if (E->isCompoundAssignmentOp()) {
12527 HandleValue(E->getLHS());
12528 Visit(E->getRHS());
12529 return;
12530 }
12531
12532 Inherited::VisitBinaryOperator(E);
12533 }
12534
12535 // A custom visitor for BinaryConditionalOperator is needed because the
12536 // regular visitor would check the condition and true expression separately
12537 // but both point to the same place giving duplicate diagnostics.
12538 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
12539 Visit(E->getCond());
12540 Visit(E->getFalseExpr());
12541 }
12542
12543 void HandleDeclRefExpr(DeclRefExpr *DRE) {
12544 Decl* ReferenceDecl = DRE->getDecl();
12545 if (OrigDecl != ReferenceDecl) return;
12546 unsigned diag;
12547 if (isReferenceType) {
12548 diag = diag::warn_uninit_self_reference_in_reference_init;
12549 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
12550 diag = diag::warn_static_self_reference_in_init;
12551 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
12552 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
12553 DRE->getDecl()->getType()->isRecordType()) {
12554 diag = diag::warn_uninit_self_reference_in_init;
12555 } else {
12556 // Local variables will be handled by the CFG analysis.
12557 return;
12558 }
12559
12560 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
12561 S.PDiag(diag)
12562 << DRE->getDecl() << OrigDecl->getLocation()
12563 << DRE->getSourceRange());
12564 }
12565 };
12566
12567 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
12568 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
12569 bool DirectInit) {
12570 // Parameters arguments are occassionially constructed with itself,
12571 // for instance, in recursive functions. Skip them.
12572 if (isa<ParmVarDecl>(OrigDecl))
12573 return;
12574
12575 E = E->IgnoreParens();
12576
12577 // Skip checking T a = a where T is not a record or reference type.
12578 // Doing so is a way to silence uninitialized warnings.
12579 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
12580 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
12581 if (ICE->getCastKind() == CK_LValueToRValue)
12582 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
12583 if (DRE->getDecl() == OrigDecl)
12584 return;
12585
12586 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
12587 }
12588} // end anonymous namespace
12589
12590namespace {
12591 // Simple wrapper to add the name of a variable or (if no variable is
12592 // available) a DeclarationName into a diagnostic.
12593 struct VarDeclOrName {
12594 VarDecl *VDecl;
12595 DeclarationName Name;
12596
12597 friend const Sema::SemaDiagnosticBuilder &
12598 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
12599 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
12600 }
12601 };
12602} // end anonymous namespace
12603
12604QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
12605 DeclarationName Name, QualType Type,
12606 TypeSourceInfo *TSI,
12607 SourceRange Range, bool DirectInit,
12608 Expr *Init) {
12609 bool IsInitCapture = !VDecl;
12610 assert((!VDecl || !VDecl->isInitCapture()) &&(static_cast <bool> ((!VDecl || !VDecl->isInitCapture
()) && "init captures are expected to be deduced prior to initialization"
) ? void (0) : __assert_fail ("(!VDecl || !VDecl->isInitCapture()) && \"init captures are expected to be deduced prior to initialization\""
, "clang/lib/Sema/SemaDecl.cpp", 12611, __extension__ __PRETTY_FUNCTION__
))
12611 "init captures are expected to be deduced prior to initialization")(static_cast <bool> ((!VDecl || !VDecl->isInitCapture
()) && "init captures are expected to be deduced prior to initialization"
) ? void (0) : __assert_fail ("(!VDecl || !VDecl->isInitCapture()) && \"init captures are expected to be deduced prior to initialization\""
, "clang/lib/Sema/SemaDecl.cpp", 12611, __extension__ __PRETTY_FUNCTION__
))
;
12612
12613 VarDeclOrName VN{VDecl, Name};
12614
12615 DeducedType *Deduced = Type->getContainedDeducedType();
12616 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type")(static_cast <bool> (Deduced && "deduceVarTypeFromInitializer for non-deduced type"
) ? void (0) : __assert_fail ("Deduced && \"deduceVarTypeFromInitializer for non-deduced type\""
, "clang/lib/Sema/SemaDecl.cpp", 12616, __extension__ __PRETTY_FUNCTION__
))
;
12617
12618 // C++11 [dcl.spec.auto]p3
12619 if (!Init) {
12620 assert(VDecl && "no init for init capture deduction?")(static_cast <bool> (VDecl && "no init for init capture deduction?"
) ? void (0) : __assert_fail ("VDecl && \"no init for init capture deduction?\""
, "clang/lib/Sema/SemaDecl.cpp", 12620, __extension__ __PRETTY_FUNCTION__
))
;
12621
12622 // Except for class argument deduction, and then for an initializing
12623 // declaration only, i.e. no static at class scope or extern.
12624 if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
12625 VDecl->hasExternalStorage() ||
12626 VDecl->isStaticDataMember()) {
12627 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
12628 << VDecl->getDeclName() << Type;
12629 return QualType();
12630 }
12631 }
12632
12633 ArrayRef<Expr*> DeduceInits;
12634 if (Init)
12635 DeduceInits = Init;
12636
12637 if (DirectInit) {
12638 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
12639 DeduceInits = PL->exprs();
12640 }
12641
12642 if (isa<DeducedTemplateSpecializationType>(Deduced)) {
12643 assert(VDecl && "non-auto type for init capture deduction?")(static_cast <bool> (VDecl && "non-auto type for init capture deduction?"
) ? void (0) : __assert_fail ("VDecl && \"non-auto type for init capture deduction?\""
, "clang/lib/Sema/SemaDecl.cpp", 12643, __extension__ __PRETTY_FUNCTION__
))
;
12644 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12645 InitializationKind Kind = InitializationKind::CreateForInit(
12646 VDecl->getLocation(), DirectInit, Init);
12647 // FIXME: Initialization should not be taking a mutable list of inits.
12648 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
12649 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
12650 InitsCopy);
12651 }
12652
12653 if (DirectInit) {
12654 if (auto *IL = dyn_cast<InitListExpr>(Init))
12655 DeduceInits = IL->inits();
12656 }
12657
12658 // Deduction only works if we have exactly one source expression.
12659 if (DeduceInits.empty()) {
12660 // It isn't possible to write this directly, but it is possible to
12661 // end up in this situation with "auto x(some_pack...);"
12662 Diag(Init->getBeginLoc(), IsInitCapture
12663 ? diag::err_init_capture_no_expression
12664 : diag::err_auto_var_init_no_expression)
12665 << VN << Type << Range;
12666 return QualType();
12667 }
12668
12669 if (DeduceInits.size() > 1) {
12670 Diag(DeduceInits[1]->getBeginLoc(),
12671 IsInitCapture ? diag::err_init_capture_multiple_expressions
12672 : diag::err_auto_var_init_multiple_expressions)
12673 << VN << Type << Range;
12674 return QualType();
12675 }
12676
12677 Expr *DeduceInit = DeduceInits[0];
12678 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
12679 Diag(Init->getBeginLoc(), IsInitCapture
12680 ? diag::err_init_capture_paren_braces
12681 : diag::err_auto_var_init_paren_braces)
12682 << isa<InitListExpr>(Init) << VN << Type << Range;
12683 return QualType();
12684 }
12685
12686 // Expressions default to 'id' when we're in a debugger.
12687 bool DefaultedAnyToId = false;
12688 if (getLangOpts().DebuggerCastResultToId &&
12689 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
12690 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12691 if (Result.isInvalid()) {
12692 return QualType();
12693 }
12694 Init = Result.get();
12695 DefaultedAnyToId = true;
12696 }
12697
12698 // C++ [dcl.decomp]p1:
12699 // If the assignment-expression [...] has array type A and no ref-qualifier
12700 // is present, e has type cv A
12701 if (VDecl && isa<DecompositionDecl>(VDecl) &&
12702 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
12703 DeduceInit->getType()->isConstantArrayType())
12704 return Context.getQualifiedType(DeduceInit->getType(),
12705 Type.getQualifiers());
12706
12707 QualType DeducedType;
12708 TemplateDeductionInfo Info(DeduceInit->getExprLoc());
12709 TemplateDeductionResult Result =
12710 DeduceAutoType(TSI->getTypeLoc(), DeduceInit, DeducedType, Info);
12711 if (Result != TDK_Success && Result != TDK_AlreadyDiagnosed) {
12712 if (!IsInitCapture)
12713 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
12714 else if (isa<InitListExpr>(Init))
12715 Diag(Range.getBegin(),
12716 diag::err_init_capture_deduction_failure_from_init_list)
12717 << VN
12718 << (DeduceInit->getType().isNull() ? TSI->getType()
12719 : DeduceInit->getType())
12720 << DeduceInit->getSourceRange();
12721 else
12722 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
12723 << VN << TSI->getType()
12724 << (DeduceInit->getType().isNull() ? TSI->getType()
12725 : DeduceInit->getType())
12726 << DeduceInit->getSourceRange();
12727 }
12728
12729 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
12730 // 'id' instead of a specific object type prevents most of our usual
12731 // checks.
12732 // We only want to warn outside of template instantiations, though:
12733 // inside a template, the 'id' could have come from a parameter.
12734 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
12735 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
12736 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
12737 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
12738 }
12739
12740 return DeducedType;
12741}
12742
12743bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
12744 Expr *Init) {
12745 assert(!Init || !Init->containsErrors())(static_cast <bool> (!Init || !Init->containsErrors(
)) ? void (0) : __assert_fail ("!Init || !Init->containsErrors()"
, "clang/lib/Sema/SemaDecl.cpp", 12745, __extension__ __PRETTY_FUNCTION__
))
;
12746 QualType DeducedType = deduceVarTypeFromInitializer(
12747 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
12748 VDecl->getSourceRange(), DirectInit, Init);
12749 if (DeducedType.isNull()) {
12750 VDecl->setInvalidDecl();
12751 return true;
12752 }
12753
12754 VDecl->setType(DeducedType);
12755 assert(VDecl->isLinkageValid())(static_cast <bool> (VDecl->isLinkageValid()) ? void
(0) : __assert_fail ("VDecl->isLinkageValid()", "clang/lib/Sema/SemaDecl.cpp"
, 12755, __extension__ __PRETTY_FUNCTION__))
;
12756
12757 // In ARC, infer lifetime.
12758 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
12759 VDecl->setInvalidDecl();
12760
12761 if (getLangOpts().OpenCL)
12762 deduceOpenCLAddressSpace(VDecl);
12763
12764 // If this is a redeclaration, check that the type we just deduced matches
12765 // the previously declared type.
12766 if (VarDecl *Old = VDecl->getPreviousDecl()) {
12767 // We never need to merge the type, because we cannot form an incomplete
12768 // array of auto, nor deduce such a type.
12769 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
12770 }
12771
12772 // Check the deduced type is valid for a variable declaration.
12773 CheckVariableDeclarationType(VDecl);
12774 return VDecl->isInvalidDecl();
12775}
12776
12777void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
12778 SourceLocation Loc) {
12779 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
12780 Init = EWC->getSubExpr();
12781
12782 if (auto *CE = dyn_cast<ConstantExpr>(Init))
12783 Init = CE->getSubExpr();
12784
12785 QualType InitType = Init->getType();
12786 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||(static_cast <bool> ((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion
() || InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
"shouldn't be called if type doesn't have a non-trivial C struct"
) ? void (0) : __assert_fail ("(InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || InitType.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C struct\""
, "clang/lib/Sema/SemaDecl.cpp", 12788, __extension__ __PRETTY_FUNCTION__
))
12787 InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&(static_cast <bool> ((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion
() || InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
"shouldn't be called if type doesn't have a non-trivial C struct"
) ? void (0) : __assert_fail ("(InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || InitType.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C struct\""
, "clang/lib/Sema/SemaDecl.cpp", 12788, __extension__ __PRETTY_FUNCTION__
))
12788 "shouldn't be called if type doesn't have a non-trivial C struct")(static_cast <bool> ((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion
() || InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
"shouldn't be called if type doesn't have a non-trivial C struct"
) ? void (0) : __assert_fail ("(InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || InitType.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C struct\""
, "clang/lib/Sema/SemaDecl.cpp", 12788, __extension__ __PRETTY_FUNCTION__
))
;
12789 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
12790 for (auto *I : ILE->inits()) {
12791 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
12792 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
12793 continue;
12794 SourceLocation SL = I->getExprLoc();
12795 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
12796 }
12797 return;
12798 }
12799
12800 if (isa<ImplicitValueInitExpr>(Init)) {
12801 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12802 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
12803 NTCUK_Init);
12804 } else {
12805 // Assume all other explicit initializers involving copying some existing
12806 // object.
12807 // TODO: ignore any explicit initializers where we can guarantee
12808 // copy-elision.
12809 if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
12810 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
12811 }
12812}
12813
12814namespace {
12815
12816bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
12817 // Ignore unavailable fields. A field can be marked as unavailable explicitly
12818 // in the source code or implicitly by the compiler if it is in a union
12819 // defined in a system header and has non-trivial ObjC ownership
12820 // qualifications. We don't want those fields to participate in determining
12821 // whether the containing union is non-trivial.
12822 return FD->hasAttr<UnavailableAttr>();
12823}
12824
12825struct DiagNonTrivalCUnionDefaultInitializeVisitor
12826 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12827 void> {
12828 using Super =
12829 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12830 void>;
12831
12832 DiagNonTrivalCUnionDefaultInitializeVisitor(
12833 QualType OrigTy, SourceLocation OrigLoc,
12834 Sema::NonTrivialCUnionContext UseContext, Sema &S)
12835 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12836
12837 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
12838 const FieldDecl *FD, bool InNonTrivialUnion) {
12839 if (const auto *AT = S.Context.getAsArrayType(QT))
12840 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12841 InNonTrivialUnion);
12842 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
12843 }
12844
12845 void visitARCStrong(QualType QT, const FieldDecl *FD,
12846 bool InNonTrivialUnion) {
12847 if (InNonTrivialUnion)
12848 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12849 << 1 << 0 << QT << FD->getName();
12850 }
12851
12852 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12853 if (InNonTrivialUnion)
12854 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12855 << 1 << 0 << QT << FD->getName();
12856 }
12857
12858 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12859 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12860 if (RD->isUnion()) {
12861 if (OrigLoc.isValid()) {
12862 bool IsUnion = false;
12863 if (auto *OrigRD = OrigTy->getAsRecordDecl())
12864 IsUnion = OrigRD->isUnion();
12865 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12866 << 0 << OrigTy << IsUnion << UseContext;
12867 // Reset OrigLoc so that this diagnostic is emitted only once.
12868 OrigLoc = SourceLocation();
12869 }
12870 InNonTrivialUnion = true;
12871 }
12872
12873 if (InNonTrivialUnion)
12874 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12875 << 0 << 0 << QT.getUnqualifiedType() << "";
12876
12877 for (const FieldDecl *FD : RD->fields())
12878 if (!shouldIgnoreForRecordTriviality(FD))
12879 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12880 }
12881
12882 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12883
12884 // The non-trivial C union type or the struct/union type that contains a
12885 // non-trivial C union.
12886 QualType OrigTy;
12887 SourceLocation OrigLoc;
12888 Sema::NonTrivialCUnionContext UseContext;
12889 Sema &S;
12890};
12891
12892struct DiagNonTrivalCUnionDestructedTypeVisitor
12893 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
12894 using Super =
12895 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
12896
12897 DiagNonTrivalCUnionDestructedTypeVisitor(
12898 QualType OrigTy, SourceLocation OrigLoc,
12899 Sema::NonTrivialCUnionContext UseContext, Sema &S)
12900 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12901
12902 void visitWithKind(QualType::DestructionKind DK, QualType QT,
12903 const FieldDecl *FD, bool InNonTrivialUnion) {
12904 if (const auto *AT = S.Context.getAsArrayType(QT))
12905 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12906 InNonTrivialUnion);
12907 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
12908 }
12909
12910 void visitARCStrong(QualType QT, const FieldDecl *FD,
12911 bool InNonTrivialUnion) {
12912 if (InNonTrivialUnion)
12913 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12914 << 1 << 1 << QT << FD->getName();
12915 }
12916
12917 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12918 if (InNonTrivialUnion)
12919 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12920 << 1 << 1 << QT << FD->getName();
12921 }
12922
12923 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12924 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12925 if (RD->isUnion()) {
12926 if (OrigLoc.isValid()) {
12927 bool IsUnion = false;
12928 if (auto *OrigRD = OrigTy->getAsRecordDecl())
12929 IsUnion = OrigRD->isUnion();
12930 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12931 << 1 << OrigTy << IsUnion << UseContext;
12932 // Reset OrigLoc so that this diagnostic is emitted only once.
12933 OrigLoc = SourceLocation();
12934 }
12935 InNonTrivialUnion = true;
12936 }
12937
12938 if (InNonTrivialUnion)
12939 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12940 << 0 << 1 << QT.getUnqualifiedType() << "";
12941
12942 for (const FieldDecl *FD : RD->fields())
12943 if (!shouldIgnoreForRecordTriviality(FD))
12944 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12945 }
12946
12947 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12948 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
12949 bool InNonTrivialUnion) {}
12950
12951 // The non-trivial C union type or the struct/union type that contains a
12952 // non-trivial C union.
12953 QualType OrigTy;
12954 SourceLocation OrigLoc;
12955 Sema::NonTrivialCUnionContext UseContext;
12956 Sema &S;
12957};
12958
12959struct DiagNonTrivalCUnionCopyVisitor
12960 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
12961 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
12962
12963 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
12964 Sema::NonTrivialCUnionContext UseContext,
12965 Sema &S)
12966 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12967
12968 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
12969 const FieldDecl *FD, bool InNonTrivialUnion) {
12970 if (const auto *AT = S.Context.getAsArrayType(QT))
12971 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12972 InNonTrivialUnion);
12973 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
12974 }
12975
12976 void visitARCStrong(QualType QT, const FieldDecl *FD,
12977 bool InNonTrivialUnion) {
12978 if (InNonTrivialUnion)
12979 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12980 << 1 << 2 << QT << FD->getName();
12981 }
12982
12983 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12984 if (InNonTrivialUnion)
12985 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12986 << 1 << 2 << QT << FD->getName();
12987 }
12988
12989 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12990 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12991 if (RD->isUnion()) {
12992 if (OrigLoc.isValid()) {
12993 bool IsUnion = false;
12994 if (auto *OrigRD = OrigTy->getAsRecordDecl())
12995 IsUnion = OrigRD->isUnion();
12996 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12997 << 2 << OrigTy << IsUnion << UseContext;
12998 // Reset OrigLoc so that this diagnostic is emitted only once.
12999 OrigLoc = SourceLocation();
13000 }
13001 InNonTrivialUnion = true;
13002 }
13003
13004 if (InNonTrivialUnion)
13005 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13006 << 0 << 2 << QT.getUnqualifiedType() << "";
13007
13008 for (const FieldDecl *FD : RD->fields())
13009 if (!shouldIgnoreForRecordTriviality(FD))
13010 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13011 }
13012
13013 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13014 const FieldDecl *FD, bool InNonTrivialUnion) {}
13015 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13016 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13017 bool InNonTrivialUnion) {}
13018
13019 // The non-trivial C union type or the struct/union type that contains a
13020 // non-trivial C union.
13021 QualType OrigTy;
13022 SourceLocation OrigLoc;
13023 Sema::NonTrivialCUnionContext UseContext;
13024 Sema &S;
13025};
13026
13027} // namespace
13028
13029void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
13030 NonTrivialCUnionContext UseContext,
13031 unsigned NonTrivialKind) {
13032 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||(static_cast <bool> ((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion
() || QT.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion
()) && "shouldn't be called if type doesn't have a non-trivial C union"
) ? void (0) : __assert_fail ("(QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C union\""
, "clang/lib/Sema/SemaDecl.cpp", 13035, __extension__ __PRETTY_FUNCTION__
))
13033 QT.hasNonTrivialToPrimitiveDestructCUnion() ||(static_cast <bool> ((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion
() || QT.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion
()) && "shouldn't be called if type doesn't have a non-trivial C union"
) ? void (0) : __assert_fail ("(QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C union\""
, "clang/lib/Sema/SemaDecl.cpp", 13035, __extension__ __PRETTY_FUNCTION__
))
13034 QT.hasNonTrivialToPrimitiveCopyCUnion()) &&(static_cast <bool> ((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion
() || QT.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion
()) && "shouldn't be called if type doesn't have a non-trivial C union"
) ? void (0) : __assert_fail ("(QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C union\""
, "clang/lib/Sema/SemaDecl.cpp", 13035, __extension__ __PRETTY_FUNCTION__
))
13035 "shouldn't be called if type doesn't have a non-trivial C union")(static_cast <bool> ((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion
() || QT.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion
()) && "shouldn't be called if type doesn't have a non-trivial C union"
) ? void (0) : __assert_fail ("(QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C union\""
, "clang/lib/Sema/SemaDecl.cpp", 13035, __extension__ __PRETTY_FUNCTION__
))
;
13036
13037 if ((NonTrivialKind & NTCUK_Init) &&
13038 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13039 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
13040 .visit(QT, nullptr, false);
13041 if ((NonTrivialKind & NTCUK_Destruct) &&
13042 QT.hasNonTrivialToPrimitiveDestructCUnion())
13043 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
13044 .visit(QT, nullptr, false);
13045 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
13046 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
13047 .visit(QT, nullptr, false);
13048}
13049
13050/// AddInitializerToDecl - Adds the initializer Init to the
13051/// declaration dcl. If DirectInit is true, this is C++ direct
13052/// initialization rather than copy initialization.
13053void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
13054 // If there is no declaration, there was an error parsing it. Just ignore
13055 // the initializer.
13056 if (!RealDecl || RealDecl->isInvalidDecl()) {
13057 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
13058 return;
13059 }
13060
13061 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
13062 // Pure-specifiers are handled in ActOnPureSpecifier.
13063 Diag(Method->getLocation(), diag::err_member_function_initialization)
13064 << Method->getDeclName() << Init->getSourceRange();
13065 Method->setInvalidDecl();
13066 return;
13067 }
13068
13069 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
13070 if (!VDecl) {
13071 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here")(static_cast <bool> (!isa<FieldDecl>(RealDecl) &&
"field init shouldn't get here") ? void (0) : __assert_fail (
"!isa<FieldDecl>(RealDecl) && \"field init shouldn't get here\""
, "clang/lib/Sema/SemaDecl.cpp", 13071, __extension__ __PRETTY_FUNCTION__
))
;
13072 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
13073 RealDecl->setInvalidDecl();
13074 return;
13075 }
13076
13077 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
13078 if (VDecl->getType()->isUndeducedType()) {
13079 // Attempt typo correction early so that the type of the init expression can
13080 // be deduced based on the chosen correction if the original init contains a
13081 // TypoExpr.
13082 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
13083 if (!Res.isUsable()) {
13084 // There are unresolved typos in Init, just drop them.
13085 // FIXME: improve the recovery strategy to preserve the Init.
13086 RealDecl->setInvalidDecl();
13087 return;
13088 }
13089 if (Res.get()->containsErrors()) {
13090 // Invalidate the decl as we don't know the type for recovery-expr yet.
13091 RealDecl->setInvalidDecl();
13092 VDecl->setInit(Res.get());
13093 return;
13094 }
13095 Init = Res.get();
13096
13097 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
13098 return;
13099 }
13100
13101 // dllimport cannot be used on variable definitions.
13102 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
13103 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
13104 VDecl->setInvalidDecl();
13105 return;
13106 }
13107
13108 // C99 6.7.8p5. If the declaration of an identifier has block scope, and
13109 // the identifier has external or internal linkage, the declaration shall
13110 // have no initializer for the identifier.
13111 // C++14 [dcl.init]p5 is the same restriction for C++.
13112 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
13113 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
13114 VDecl->setInvalidDecl();
13115 return;
13116 }
13117
13118 if (!VDecl->getType()->isDependentType()) {
13119 // A definition must end up with a complete type, which means it must be
13120 // complete with the restriction that an array type might be completed by
13121 // the initializer; note that later code assumes this restriction.
13122 QualType BaseDeclType = VDecl->getType();
13123 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
13124 BaseDeclType = Array->getElementType();
13125 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
13126 diag::err_typecheck_decl_incomplete_type)) {
13127 RealDecl->setInvalidDecl();
13128 return;
13129 }
13130
13131 // The variable can not have an abstract class type.
13132 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
13133 diag::err_abstract_type_in_decl,
13134 AbstractVariableType))
13135 VDecl->setInvalidDecl();
13136 }
13137
13138 // C++ [module.import/6] external definitions are not permitted in header
13139 // units.
13140 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
13141 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
13142 VDecl->getFormalLinkage() == Linkage::ExternalLinkage &&
13143 !VDecl->isInline() && !VDecl->isTemplated() &&
13144 !isa<VarTemplateSpecializationDecl>(VDecl)) {
13145 Diag(VDecl->getLocation(), diag::err_extern_def_in_header_unit);
13146 VDecl->setInvalidDecl();
13147 }
13148
13149 // If adding the initializer will turn this declaration into a definition,
13150 // and we already have a definition for this variable, diagnose or otherwise
13151 // handle the situation.
13152 if (VarDecl *Def = VDecl->getDefinition())
13153 if (Def != VDecl &&
13154 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
13155 !VDecl->isThisDeclarationADemotedDefinition() &&
13156 checkVarDeclRedefinition(Def, VDecl))
13157 return;
13158
13159 if (getLangOpts().CPlusPlus) {
13160 // C++ [class.static.data]p4
13161 // If a static data member is of const integral or const
13162 // enumeration type, its declaration in the class definition can
13163 // specify a constant-initializer which shall be an integral
13164 // constant expression (5.19). In that case, the member can appear
13165 // in integral constant expressions. The member shall still be
13166 // defined in a namespace scope if it is used in the program and the
13167 // namespace scope definition shall not contain an initializer.
13168 //
13169 // We already performed a redefinition check above, but for static
13170 // data members we also need to check whether there was an in-class
13171 // declaration with an initializer.
13172 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
13173 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
13174 << VDecl->getDeclName();
13175 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
13176 diag::note_previous_initializer)
13177 << 0;
13178 return;
13179 }
13180
13181 if (VDecl->hasLocalStorage())
13182 setFunctionHasBranchProtectedScope();
13183
13184 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
13185 VDecl->setInvalidDecl();
13186 return;
13187 }
13188 }
13189
13190 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
13191 // a kernel function cannot be initialized."
13192 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
13193 Diag(VDecl->getLocation(), diag::err_local_cant_init);
13194 VDecl->setInvalidDecl();
13195 return;
13196 }
13197
13198 // The LoaderUninitialized attribute acts as a definition (of undef).
13199 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
13200 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
13201 VDecl->setInvalidDecl();
13202 return;
13203 }
13204
13205 // Get the decls type and save a reference for later, since
13206 // CheckInitializerTypes may change it.
13207 QualType DclT = VDecl->getType(), SavT = DclT;
13208
13209 // Expressions default to 'id' when we're in a debugger
13210 // and we are assigning it to a variable of Objective-C pointer type.
13211 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
13212 Init->getType() == Context.UnknownAnyTy) {
13213 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
13214 if (Result.isInvalid()) {
13215 VDecl->setInvalidDecl();
13216 return;
13217 }
13218 Init = Result.get();
13219 }
13220
13221 // Perform the initialization.
13222 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
13223 bool IsParenListInit = false;
13224 if (!VDecl->isInvalidDecl()) {
13225 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
13226 InitializationKind Kind = InitializationKind::CreateForInit(
13227 VDecl->getLocation(), DirectInit, Init);
13228
13229 MultiExprArg Args = Init;
13230 if (CXXDirectInit)
13231 Args = MultiExprArg(CXXDirectInit->getExprs(),
13232 CXXDirectInit->getNumExprs());
13233
13234 // Try to correct any TypoExprs in the initialization arguments.
13235 for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
13236 ExprResult Res = CorrectDelayedTyposInExpr(
13237 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
13238 [this, Entity, Kind](Expr *E) {
13239 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
13240 return Init.Failed() ? ExprError() : E;
13241 });
13242 if (Res.isInvalid()) {
13243 VDecl->setInvalidDecl();
13244 } else if (Res.get() != Args[Idx]) {
13245 Args[Idx] = Res.get();
13246 }
13247 }
13248 if (VDecl->isInvalidDecl())
13249 return;
13250
13251 InitializationSequence InitSeq(*this, Entity, Kind, Args,
13252 /*TopLevelOfInitList=*/false,
13253 /*TreatUnavailableAsInvalid=*/false);
13254 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
13255 if (Result.isInvalid()) {
13256 // If the provided initializer fails to initialize the var decl,
13257 // we attach a recovery expr for better recovery.
13258 auto RecoveryExpr =
13259 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
13260 if (RecoveryExpr.get())
13261 VDecl->setInit(RecoveryExpr.get());
13262 return;
13263 }
13264
13265 Init = Result.getAs<Expr>();
13266 IsParenListInit = !InitSeq.steps().empty() &&
13267 InitSeq.step_begin()->Kind ==
13268 InitializationSequence::SK_ParenthesizedListInit;
13269 }
13270
13271 // Check for self-references within variable initializers.
13272 // Variables declared within a function/method body (except for references)
13273 // are handled by a dataflow analysis.
13274 // This is undefined behavior in C++, but valid in C.
13275 if (getLangOpts().CPlusPlus)
13276 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
13277 VDecl->getType()->isReferenceType())
13278 CheckSelfReference(*this, RealDecl, Init, DirectInit);
13279
13280 // If the type changed, it means we had an incomplete type that was
13281 // completed by the initializer. For example:
13282 // int ary[] = { 1, 3, 5 };
13283 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
13284 if (!VDecl->isInvalidDecl() && (DclT != SavT))
13285 VDecl->setType(DclT);
13286
13287 if (!VDecl->isInvalidDecl()) {
13288 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
13289
13290 if (VDecl->hasAttr<BlocksAttr>())
13291 checkRetainCycles(VDecl, Init);
13292
13293 // It is safe to assign a weak reference into a strong variable.
13294 // Although this code can still have problems:
13295 // id x = self.weakProp;
13296 // id y = self.weakProp;
13297 // we do not warn to warn spuriously when 'x' and 'y' are on separate
13298 // paths through the function. This should be revisited if
13299 // -Wrepeated-use-of-weak is made flow-sensitive.
13300 if (FunctionScopeInfo *FSI = getCurFunction())
13301 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
13302 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
13303 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13304 Init->getBeginLoc()))
13305 FSI->markSafeWeakUse(Init);
13306 }
13307
13308 // The initialization is usually a full-expression.
13309 //
13310 // FIXME: If this is a braced initialization of an aggregate, it is not
13311 // an expression, and each individual field initializer is a separate
13312 // full-expression. For instance, in:
13313 //
13314 // struct Temp { ~Temp(); };
13315 // struct S { S(Temp); };
13316 // struct T { S a, b; } t = { Temp(), Temp() }
13317 //
13318 // we should destroy the first Temp before constructing the second.
13319 ExprResult Result =
13320 ActOnFinishFullExpr(Init, VDecl->getLocation(),
13321 /*DiscardedValue*/ false, VDecl->isConstexpr());
13322 if (Result.isInvalid()) {
13323 VDecl->setInvalidDecl();
13324 return;
13325 }
13326 Init = Result.get();
13327
13328 // Attach the initializer to the decl.
13329 VDecl->setInit(Init);
13330
13331 if (VDecl->isLocalVarDecl()) {
13332 // Don't check the initializer if the declaration is malformed.
13333 if (VDecl->isInvalidDecl()) {
13334 // do nothing
13335
13336 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
13337 // This is true even in C++ for OpenCL.
13338 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
13339 CheckForConstantInitializer(Init, DclT);
13340
13341 // Otherwise, C++ does not restrict the initializer.
13342 } else if (getLangOpts().CPlusPlus) {
13343 // do nothing
13344
13345 // C99 6.7.8p4: All the expressions in an initializer for an object that has
13346 // static storage duration shall be constant expressions or string literals.
13347 } else if (VDecl->getStorageClass() == SC_Static) {
13348 CheckForConstantInitializer(Init, DclT);
13349
13350 // C89 is stricter than C99 for aggregate initializers.
13351 // C89 6.5.7p3: All the expressions [...] in an initializer list
13352 // for an object that has aggregate or union type shall be
13353 // constant expressions.
13354 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
13355 isa<InitListExpr>(Init)) {
13356 const Expr *Culprit;
13357 if (!Init->isConstantInitializer(Context, false, &Culprit)) {
13358 Diag(Culprit->getExprLoc(),
13359 diag::ext_aggregate_init_not_constant)
13360 << Culprit->getSourceRange();
13361 }
13362 }
13363
13364 if (auto *E = dyn_cast<ExprWithCleanups>(Init))
13365 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
13366 if (VDecl->hasLocalStorage())
13367 BE->getBlockDecl()->setCanAvoidCopyToHeap();
13368 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
13369 VDecl->getLexicalDeclContext()->isRecord()) {
13370 // This is an in-class initialization for a static data member, e.g.,
13371 //
13372 // struct S {
13373 // static const int value = 17;
13374 // };
13375
13376 // C++ [class.mem]p4:
13377 // A member-declarator can contain a constant-initializer only
13378 // if it declares a static member (9.4) of const integral or
13379 // const enumeration type, see 9.4.2.
13380 //
13381 // C++11 [class.static.data]p3:
13382 // If a non-volatile non-inline const static data member is of integral
13383 // or enumeration type, its declaration in the class definition can
13384 // specify a brace-or-equal-initializer in which every initializer-clause
13385 // that is an assignment-expression is a constant expression. A static
13386 // data member of literal type can be declared in the class definition
13387 // with the constexpr specifier; if so, its declaration shall specify a
13388 // brace-or-equal-initializer in which every initializer-clause that is
13389 // an assignment-expression is a constant expression.
13390
13391 // Do nothing on dependent types.
13392 if (DclT->isDependentType()) {
13393
13394 // Allow any 'static constexpr' members, whether or not they are of literal
13395 // type. We separately check that every constexpr variable is of literal
13396 // type.
13397 } else if (VDecl->isConstexpr()) {
13398
13399 // Require constness.
13400 } else if (!DclT.isConstQualified()) {
13401 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
13402 << Init->getSourceRange();
13403 VDecl->setInvalidDecl();
13404
13405 // We allow integer constant expressions in all cases.
13406 } else if (DclT->isIntegralOrEnumerationType()) {
13407 // Check whether the expression is a constant expression.
13408 SourceLocation Loc;
13409 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
13410 // In C++11, a non-constexpr const static data member with an
13411 // in-class initializer cannot be volatile.
13412 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
13413 else if (Init->isValueDependent())
13414 ; // Nothing to check.
13415 else if (Init->isIntegerConstantExpr(Context, &Loc))
13416 ; // Ok, it's an ICE!
13417 else if (Init->getType()->isScopedEnumeralType() &&
13418 Init->isCXX11ConstantExpr(Context))
13419 ; // Ok, it is a scoped-enum constant expression.
13420 else if (Init->isEvaluatable(Context)) {
13421 // If we can constant fold the initializer through heroics, accept it,
13422 // but report this as a use of an extension for -pedantic.
13423 Diag(Loc, diag::ext_in_class_initializer_non_constant)
13424 << Init->getSourceRange();
13425 } else {
13426 // Otherwise, this is some crazy unknown case. Report the issue at the
13427 // location provided by the isIntegerConstantExpr failed check.
13428 Diag(Loc, diag::err_in_class_initializer_non_constant)
13429 << Init->getSourceRange();
13430 VDecl->setInvalidDecl();
13431 }
13432
13433 // We allow foldable floating-point constants as an extension.
13434 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
13435 // In C++98, this is a GNU extension. In C++11, it is not, but we support
13436 // it anyway and provide a fixit to add the 'constexpr'.
13437 if (getLangOpts().CPlusPlus11) {
13438 Diag(VDecl->getLocation(),
13439 diag::ext_in_class_initializer_float_type_cxx11)
13440 << DclT << Init->getSourceRange();
13441 Diag(VDecl->getBeginLoc(),
13442 diag::note_in_class_initializer_float_type_cxx11)
13443 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13444 } else {
13445 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
13446 << DclT << Init->getSourceRange();
13447
13448 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
13449 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
13450 << Init->getSourceRange();
13451 VDecl->setInvalidDecl();
13452 }
13453 }
13454
13455 // Suggest adding 'constexpr' in C++11 for literal types.
13456 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
13457 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
13458 << DclT << Init->getSourceRange()
13459 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13460 VDecl->setConstexpr(true);
13461
13462 } else {
13463 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
13464 << DclT << Init->getSourceRange();
13465 VDecl->setInvalidDecl();
13466 }
13467 } else if (VDecl->isFileVarDecl()) {
13468 // In C, extern is typically used to avoid tentative definitions when
13469 // declaring variables in headers, but adding an intializer makes it a
13470 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
13471 // In C++, extern is often used to give implictly static const variables
13472 // external linkage, so don't warn in that case. If selectany is present,
13473 // this might be header code intended for C and C++ inclusion, so apply the
13474 // C++ rules.
13475 if (VDecl->getStorageClass() == SC_Extern &&
13476 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
13477 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
13478 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
13479 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
13480 Diag(VDecl->getLocation(), diag::warn_extern_init);
13481
13482 // In Microsoft C++ mode, a const variable defined in namespace scope has
13483 // external linkage by default if the variable is declared with
13484 // __declspec(dllexport).
13485 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13486 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
13487 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
13488 VDecl->setStorageClass(SC_Extern);
13489
13490 // C99 6.7.8p4. All file scoped initializers need to be constant.
13491 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
13492 CheckForConstantInitializer(Init, DclT);
13493 }
13494
13495 QualType InitType = Init->getType();
13496 if (!InitType.isNull() &&
13497 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13498 InitType.hasNonTrivialToPrimitiveCopyCUnion()))
13499 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
13500
13501 // We will represent direct-initialization similarly to copy-initialization:
13502 // int x(1); -as-> int x = 1;
13503 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
13504 //
13505 // Clients that want to distinguish between the two forms, can check for
13506 // direct initializer using VarDecl::getInitStyle().
13507 // A major benefit is that clients that don't particularly care about which
13508 // exactly form was it (like the CodeGen) can handle both cases without
13509 // special case code.
13510
13511 // C++ 8.5p11:
13512 // The form of initialization (using parentheses or '=') is generally
13513 // insignificant, but does matter when the entity being initialized has a
13514 // class type.
13515 if (CXXDirectInit) {
13516 assert(DirectInit && "Call-style initializer must be direct init.")(static_cast <bool> (DirectInit && "Call-style initializer must be direct init."
) ? void (0) : __assert_fail ("DirectInit && \"Call-style initializer must be direct init.\""
, "clang/lib/Sema/SemaDecl.cpp", 13516, __extension__ __PRETTY_FUNCTION__
))
;
13517 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
13518 : VarDecl::CallInit);
13519 } else if (DirectInit) {
13520 // This must be list-initialization. No other way is direct-initialization.
13521 VDecl->setInitStyle(VarDecl::ListInit);
13522 }
13523
13524 if (LangOpts.OpenMP &&
13525 (LangOpts.OpenMPIsDevice || !LangOpts.OMPTargetTriples.empty()) &&
13526 VDecl->isFileVarDecl())
13527 DeclsToCheckForDeferredDiags.insert(VDecl);
13528 CheckCompleteVariableDeclaration(VDecl);
13529}
13530
13531/// ActOnInitializerError - Given that there was an error parsing an
13532/// initializer for the given declaration, try to at least re-establish
13533/// invariants such as whether a variable's type is either dependent or
13534/// complete.
13535void Sema::ActOnInitializerError(Decl *D) {
13536 // Our main concern here is re-establishing invariants like "a
13537 // variable's type is either dependent or complete".
13538 if (!D || D->isInvalidDecl()) return;
13539
13540 VarDecl *VD = dyn_cast<VarDecl>(D);
13541 if (!VD) return;
13542
13543 // Bindings are not usable if we can't make sense of the initializer.
13544 if (auto *DD = dyn_cast<DecompositionDecl>(D))
13545 for (auto *BD : DD->bindings())
13546 BD->setInvalidDecl();
13547
13548 // Auto types are meaningless if we can't make sense of the initializer.
13549 if (VD->getType()->isUndeducedType()) {
13550 D->setInvalidDecl();
13551 return;
13552 }
13553
13554 QualType Ty = VD->getType();
13555 if (Ty->isDependentType()) return;
13556
13557 // Require a complete type.
13558 if (RequireCompleteType(VD->getLocation(),
13559 Context.getBaseElementType(Ty),
13560 diag::err_typecheck_decl_incomplete_type)) {
13561 VD->setInvalidDecl();
13562 return;
13563 }
13564
13565 // Require a non-abstract type.
13566 if (RequireNonAbstractType(VD->getLocation(), Ty,
13567 diag::err_abstract_type_in_decl,
13568 AbstractVariableType)) {
13569 VD->setInvalidDecl();
13570 return;
13571 }
13572
13573 // Don't bother complaining about constructors or destructors,
13574 // though.
13575}
13576
13577void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
13578 // If there is no declaration, there was an error parsing it. Just ignore it.
13579 if (!RealDecl)
13580 return;
13581
13582 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
13583 QualType Type = Var->getType();
13584
13585 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
13586 if (isa<DecompositionDecl>(RealDecl)) {
13587 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
13588 Var->setInvalidDecl();
13589 return;
13590 }
13591
13592 if (Type->isUndeducedType() &&
13593 DeduceVariableDeclarationType(Var, false, nullptr))
13594 return;
13595
13596 // C++11 [class.static.data]p3: A static data member can be declared with
13597 // the constexpr specifier; if so, its declaration shall specify
13598 // a brace-or-equal-initializer.
13599 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
13600 // the definition of a variable [...] or the declaration of a static data
13601 // member.
13602 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
13603 !Var->isThisDeclarationADemotedDefinition()) {
13604 if (Var->isStaticDataMember()) {
13605 // C++1z removes the relevant rule; the in-class declaration is always
13606 // a definition there.
13607 if (!getLangOpts().CPlusPlus17 &&
13608 !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
13609 Diag(Var->getLocation(),
13610 diag::err_constexpr_static_mem_var_requires_init)
13611 << Var;
13612 Var->setInvalidDecl();
13613 return;
13614 }
13615 } else {
13616 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
13617 Var->setInvalidDecl();
13618 return;
13619 }
13620 }
13621
13622 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
13623 // be initialized.
13624 if (!Var->isInvalidDecl() &&
13625 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
13626 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
13627 bool HasConstExprDefaultConstructor = false;
13628 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13629 for (auto *Ctor : RD->ctors()) {
13630 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
13631 Ctor->getMethodQualifiers().getAddressSpace() ==
13632 LangAS::opencl_constant) {
13633 HasConstExprDefaultConstructor = true;
13634 }
13635 }
13636 }
13637 if (!HasConstExprDefaultConstructor) {
13638 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
13639 Var->setInvalidDecl();
13640 return;
13641 }
13642 }
13643
13644 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
13645 if (Var->getStorageClass() == SC_Extern) {
13646 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
13647 << Var;
13648 Var->setInvalidDecl();
13649 return;
13650 }
13651 if (RequireCompleteType(Var->getLocation(), Var->getType(),
13652 diag::err_typecheck_decl_incomplete_type)) {
13653 Var->setInvalidDecl();
13654 return;
13655 }
13656 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13657 if (!RD->hasTrivialDefaultConstructor()) {
13658 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
13659 Var->setInvalidDecl();
13660 return;
13661 }
13662 }
13663 // The declaration is unitialized, no need for further checks.
13664 return;
13665 }
13666
13667 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
13668 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
13669 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13670 checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
13671 NTCUC_DefaultInitializedObject, NTCUK_Init);
13672
13673
13674 switch (DefKind) {
13675 case VarDecl::Definition:
13676 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
13677 break;
13678
13679 // We have an out-of-line definition of a static data member
13680 // that has an in-class initializer, so we type-check this like
13681 // a declaration.
13682 //
13683 [[fallthrough]];
13684
13685 case VarDecl::DeclarationOnly:
13686 // It's only a declaration.
13687
13688 // Block scope. C99 6.7p7: If an identifier for an object is
13689 // declared with no linkage (C99 6.2.2p6), the type for the
13690 // object shall be complete.
13691 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
13692 !Var->hasLinkage() && !Var->isInvalidDecl() &&
13693 RequireCompleteType(Var->getLocation(), Type,
13694 diag::err_typecheck_decl_incomplete_type))
13695 Var->setInvalidDecl();
13696
13697 // Make sure that the type is not abstract.
13698 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13699 RequireNonAbstractType(Var->getLocation(), Type,
13700 diag::err_abstract_type_in_decl,
13701 AbstractVariableType))
13702 Var->setInvalidDecl();
13703 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13704 Var->getStorageClass() == SC_PrivateExtern) {
13705 Diag(Var->getLocation(), diag::warn_private_extern);
13706 Diag(Var->getLocation(), diag::note_private_extern);
13707 }
13708
13709 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
13710 !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
13711 ExternalDeclarations.push_back(Var);
13712
13713 return;
13714
13715 case VarDecl::TentativeDefinition:
13716 // File scope. C99 6.9.2p2: A declaration of an identifier for an
13717 // object that has file scope without an initializer, and without a
13718 // storage-class specifier or with the storage-class specifier "static",
13719 // constitutes a tentative definition. Note: A tentative definition with
13720 // external linkage is valid (C99 6.2.2p5).
13721 if (!Var->isInvalidDecl()) {
13722 if (const IncompleteArrayType *ArrayT
13723 = Context.getAsIncompleteArrayType(Type)) {
13724 if (RequireCompleteSizedType(
13725 Var->getLocation(), ArrayT->getElementType(),
13726 diag::err_array_incomplete_or_sizeless_type))
13727 Var->setInvalidDecl();
13728 } else if (Var->getStorageClass() == SC_Static) {
13729 // C99 6.9.2p3: If the declaration of an identifier for an object is
13730 // a tentative definition and has internal linkage (C99 6.2.2p3), the
13731 // declared type shall not be an incomplete type.
13732 // NOTE: code such as the following
13733 // static struct s;
13734 // struct s { int a; };
13735 // is accepted by gcc. Hence here we issue a warning instead of
13736 // an error and we do not invalidate the static declaration.
13737 // NOTE: to avoid multiple warnings, only check the first declaration.
13738 if (Var->isFirstDecl())
13739 RequireCompleteType(Var->getLocation(), Type,
13740 diag::ext_typecheck_decl_incomplete_type);
13741 }
13742 }
13743
13744 // Record the tentative definition; we're done.
13745 if (!Var->isInvalidDecl())
13746 TentativeDefinitions.push_back(Var);
13747 return;
13748 }
13749
13750 // Provide a specific diagnostic for uninitialized variable
13751 // definitions with incomplete array type.
13752 if (Type->isIncompleteArrayType()) {
13753 if (Var->isConstexpr())
13754 Diag(Var->getLocation(), diag::err_constexpr_var_requires_const_init)
13755 << Var;
13756 else
13757 Diag(Var->getLocation(),
13758 diag::err_typecheck_incomplete_array_needs_initializer);
13759 Var->setInvalidDecl();
13760 return;
13761 }
13762
13763 // Provide a specific diagnostic for uninitialized variable
13764 // definitions with reference type.
13765 if (Type->isReferenceType()) {
13766 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
13767 << Var << SourceRange(Var->getLocation(), Var->getLocation());
13768 return;
13769 }
13770
13771 // Do not attempt to type-check the default initializer for a
13772 // variable with dependent type.
13773 if (Type->isDependentType())
13774 return;
13775
13776 if (Var->isInvalidDecl())
13777 return;
13778
13779 if (!Var->hasAttr<AliasAttr>()) {
13780 if (RequireCompleteType(Var->getLocation(),
13781 Context.getBaseElementType(Type),
13782 diag::err_typecheck_decl_incomplete_type)) {
13783 Var->setInvalidDecl();
13784 return;
13785 }
13786 } else {
13787 return;
13788 }
13789
13790 // The variable can not have an abstract class type.
13791 if (RequireNonAbstractType(Var->getLocation(), Type,
13792 diag::err_abstract_type_in_decl,
13793 AbstractVariableType)) {
13794 Var->setInvalidDecl();
13795 return;
13796 }
13797
13798 // Check for jumps past the implicit initializer. C++0x
13799 // clarifies that this applies to a "variable with automatic
13800 // storage duration", not a "local variable".
13801 // C++11 [stmt.dcl]p3
13802 // A program that jumps from a point where a variable with automatic
13803 // storage duration is not in scope to a point where it is in scope is
13804 // ill-formed unless the variable has scalar type, class type with a
13805 // trivial default constructor and a trivial destructor, a cv-qualified
13806 // version of one of these types, or an array of one of the preceding
13807 // types and is declared without an initializer.
13808 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
13809 if (const RecordType *Record
13810 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
13811 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
13812 // Mark the function (if we're in one) for further checking even if the
13813 // looser rules of C++11 do not require such checks, so that we can
13814 // diagnose incompatibilities with C++98.
13815 if (!CXXRecord->isPOD())
13816 setFunctionHasBranchProtectedScope();
13817 }
13818 }
13819 // In OpenCL, we can't initialize objects in the __local address space,
13820 // even implicitly, so don't synthesize an implicit initializer.
13821 if (getLangOpts().OpenCL &&
13822 Var->getType().getAddressSpace() == LangAS::opencl_local)
13823 return;
13824 // C++03 [dcl.init]p9:
13825 // If no initializer is specified for an object, and the
13826 // object is of (possibly cv-qualified) non-POD class type (or
13827 // array thereof), the object shall be default-initialized; if
13828 // the object is of const-qualified type, the underlying class
13829 // type shall have a user-declared default
13830 // constructor. Otherwise, if no initializer is specified for
13831 // a non- static object, the object and its subobjects, if
13832 // any, have an indeterminate initial value); if the object
13833 // or any of its subobjects are of const-qualified type, the
13834 // program is ill-formed.
13835 // C++0x [dcl.init]p11:
13836 // If no initializer is specified for an object, the object is
13837 // default-initialized; [...].
13838 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
13839 InitializationKind Kind
13840 = InitializationKind::CreateDefault(Var->getLocation());
13841
13842 InitializationSequence InitSeq(*this, Entity, Kind, std::nullopt);
13843 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, std::nullopt);
13844
13845 if (Init.get()) {
13846 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
13847 // This is important for template substitution.
13848 Var->setInitStyle(VarDecl::CallInit);
13849 } else if (Init.isInvalid()) {
13850 // If default-init fails, attach a recovery-expr initializer to track
13851 // that initialization was attempted and failed.
13852 auto RecoveryExpr =
13853 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
13854 if (RecoveryExpr.get())
13855 Var->setInit(RecoveryExpr.get());
13856 }
13857
13858 CheckCompleteVariableDeclaration(Var);
13859 }
13860}
13861
13862void Sema::ActOnCXXForRangeDecl(Decl *D) {
13863 // If there is no declaration, there was an error parsing it. Ignore it.
13864 if (!D)
13865 return;
13866
13867 VarDecl *VD = dyn_cast<VarDecl>(D);
13868 if (!VD) {
13869 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
13870 D->setInvalidDecl();
13871 return;
13872 }
13873
13874 VD->setCXXForRangeDecl(true);
13875
13876 // for-range-declaration cannot be given a storage class specifier.
13877 int Error = -1;
13878 switch (VD->getStorageClass()) {
13879 case SC_None:
13880 break;
13881 case SC_Extern:
13882 Error = 0;
13883 break;
13884 case SC_Static:
13885 Error = 1;
13886 break;
13887 case SC_PrivateExtern:
13888 Error = 2;
13889 break;
13890 case SC_Auto:
13891 Error = 3;
13892 break;
13893 case SC_Register:
13894 Error = 4;
13895 break;
13896 }
13897
13898 // for-range-declaration cannot be given a storage class specifier con't.
13899 switch (VD->getTSCSpec()) {
13900 case TSCS_thread_local:
13901 Error = 6;
13902 break;
13903 case TSCS___thread:
13904 case TSCS__Thread_local:
13905 case TSCS_unspecified:
13906 break;
13907 }
13908
13909 if (Error != -1) {
13910 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
13911 << VD << Error;
13912 D->setInvalidDecl();
13913 }
13914}
13915
13916StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
13917 IdentifierInfo *Ident,
13918 ParsedAttributes &Attrs) {
13919 // C++1y [stmt.iter]p1:
13920 // A range-based for statement of the form
13921 // for ( for-range-identifier : for-range-initializer ) statement
13922 // is equivalent to
13923 // for ( auto&& for-range-identifier : for-range-initializer ) statement
13924 DeclSpec DS(Attrs.getPool().getFactory());
13925
13926 const char *PrevSpec;
13927 unsigned DiagID;
13928 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
13929 getPrintingPolicy());
13930
13931 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::ForInit);
13932 D.SetIdentifier(Ident, IdentLoc);
13933 D.takeAttributes(Attrs);
13934
13935 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
13936 IdentLoc);
13937 Decl *Var = ActOnDeclarator(S, D);
13938 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
13939 FinalizeDeclaration(Var);
13940 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
13941 Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
13942 : IdentLoc);
13943}
13944
13945void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
13946 if (var->isInvalidDecl()) return;
13947
13948 MaybeAddCUDAConstantAttr(var);
13949
13950 if (getLangOpts().OpenCL) {
13951 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
13952 // initialiser
13953 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
13954 !var->hasInit()) {
13955 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
13956 << 1 /*Init*/;
13957 var->setInvalidDecl();
13958 return;
13959 }
13960 }
13961
13962 // In Objective-C, don't allow jumps past the implicit initialization of a
13963 // local retaining variable.
13964 if (getLangOpts().ObjC &&
13965 var->hasLocalStorage()) {
13966 switch (var->getType().getObjCLifetime()) {
13967 case Qualifiers::OCL_None:
13968 case Qualifiers::OCL_ExplicitNone:
13969 case Qualifiers::OCL_Autoreleasing:
13970 break;
13971
13972 case Qualifiers::OCL_Weak:
13973 case Qualifiers::OCL_Strong:
13974 setFunctionHasBranchProtectedScope();
13975 break;
13976 }
13977 }
13978
13979 if (var->hasLocalStorage() &&
13980 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
13981 setFunctionHasBranchProtectedScope();
13982
13983 // Warn about externally-visible variables being defined without a
13984 // prior declaration. We only want to do this for global
13985 // declarations, but we also specifically need to avoid doing it for
13986 // class members because the linkage of an anonymous class can
13987 // change if it's later given a typedef name.
13988 if (var->isThisDeclarationADefinition() &&
13989 var->getDeclContext()->getRedeclContext()->isFileContext() &&
13990 var->isExternallyVisible() && var->hasLinkage() &&
13991 !var->isInline() && !var->getDescribedVarTemplate() &&
13992 !isa<VarTemplatePartialSpecializationDecl>(var) &&
13993 !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
13994 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
13995 var->getLocation())) {
13996 // Find a previous declaration that's not a definition.
13997 VarDecl *prev = var->getPreviousDecl();
13998 while (prev && prev->isThisDeclarationADefinition())
13999 prev = prev->getPreviousDecl();
14000
14001 if (!prev) {
14002 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
14003 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14004 << /* variable */ 0;
14005 }
14006 }
14007
14008 // Cache the result of checking for constant initialization.
14009 std::optional<bool> CacheHasConstInit;
14010 const Expr *CacheCulprit = nullptr;
14011 auto checkConstInit = [&]() mutable {
14012 if (!CacheHasConstInit)
14013 CacheHasConstInit = var->getInit()->isConstantInitializer(
14014 Context, var->getType()->isReferenceType(), &CacheCulprit);
14015 return *CacheHasConstInit;
14016 };
14017
14018 if (var->getTLSKind() == VarDecl::TLS_Static) {
14019 if (var->getType().isDestructedType()) {
14020 // GNU C++98 edits for __thread, [basic.start.term]p3:
14021 // The type of an object with thread storage duration shall not
14022 // have a non-trivial destructor.
14023 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
14024 if (getLangOpts().CPlusPlus11)
14025 Diag(var->getLocation(), diag::note_use_thread_local);
14026 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
14027 if (!checkConstInit()) {
14028 // GNU C++98 edits for __thread, [basic.start.init]p4:
14029 // An object of thread storage duration shall not require dynamic
14030 // initialization.
14031 // FIXME: Need strict checking here.
14032 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
14033 << CacheCulprit->getSourceRange();
14034 if (getLangOpts().CPlusPlus11)
14035 Diag(var->getLocation(), diag::note_use_thread_local);
14036 }
14037 }
14038 }
14039
14040
14041 if (!var->getType()->isStructureType() && var->hasInit() &&
14042 isa<InitListExpr>(var->getInit())) {
14043 const auto *ILE = cast<InitListExpr>(var->getInit());
14044 unsigned NumInits = ILE->getNumInits();
14045 if (NumInits > 2)
14046 for (unsigned I = 0; I < NumInits; ++I) {
14047 const auto *Init = ILE->getInit(I);
14048 if (!Init)
14049 break;
14050 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14051 if (!SL)
14052 break;
14053
14054 unsigned NumConcat = SL->getNumConcatenated();
14055 // Diagnose missing comma in string array initialization.
14056 // Do not warn when all the elements in the initializer are concatenated
14057 // together. Do not warn for macros too.
14058 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
14059 bool OnlyOneMissingComma = true;
14060 for (unsigned J = I + 1; J < NumInits; ++J) {
14061 const auto *Init = ILE->getInit(J);
14062 if (!Init)
14063 break;
14064 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14065 if (!SLJ || SLJ->getNumConcatenated() > 1) {
14066 OnlyOneMissingComma = false;
14067 break;
14068 }
14069 }
14070
14071 if (OnlyOneMissingComma) {
14072 SmallVector<FixItHint, 1> Hints;
14073 for (unsigned i = 0; i < NumConcat - 1; ++i)
14074 Hints.push_back(FixItHint::CreateInsertion(
14075 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
14076
14077 Diag(SL->getStrTokenLoc(1),
14078 diag::warn_concatenated_literal_array_init)
14079 << Hints;
14080 Diag(SL->getBeginLoc(),
14081 diag::note_concatenated_string_literal_silence);
14082 }
14083 // In any case, stop now.
14084 break;
14085 }
14086 }
14087 }
14088
14089
14090 QualType type = var->getType();
14091
14092 if (var->hasAttr<BlocksAttr>())
14093 getCurFunction()->addByrefBlockVar(var);
14094
14095 Expr *Init = var->getInit();
14096 bool GlobalStorage = var->hasGlobalStorage();
14097 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
14098 QualType baseType = Context.getBaseElementType(type);
14099 bool HasConstInit = true;
14100
14101 // Check whether the initializer is sufficiently constant.
14102 if (getLangOpts().CPlusPlus && !type->isDependentType() && Init &&
14103 !Init->isValueDependent() &&
14104 (GlobalStorage || var->isConstexpr() ||
14105 var->mightBeUsableInConstantExpressions(Context))) {
14106 // If this variable might have a constant initializer or might be usable in
14107 // constant expressions, check whether or not it actually is now. We can't
14108 // do this lazily, because the result might depend on things that change
14109 // later, such as which constexpr functions happen to be defined.
14110 SmallVector<PartialDiagnosticAt, 8> Notes;
14111 if (!getLangOpts().CPlusPlus11) {
14112 // Prior to C++11, in contexts where a constant initializer is required,
14113 // the set of valid constant initializers is described by syntactic rules
14114 // in [expr.const]p2-6.
14115 // FIXME: Stricter checking for these rules would be useful for constinit /
14116 // -Wglobal-constructors.
14117 HasConstInit = checkConstInit();
14118
14119 // Compute and cache the constant value, and remember that we have a
14120 // constant initializer.
14121 if (HasConstInit) {
14122 (void)var->checkForConstantInitialization(Notes);
14123 Notes.clear();
14124 } else if (CacheCulprit) {
14125 Notes.emplace_back(CacheCulprit->getExprLoc(),
14126 PDiag(diag::note_invalid_subexpr_in_const_expr));
14127 Notes.back().second << CacheCulprit->getSourceRange();
14128 }
14129 } else {
14130 // Evaluate the initializer to see if it's a constant initializer.
14131 HasConstInit = var->checkForConstantInitialization(Notes);
14132 }
14133
14134 if (HasConstInit) {
14135 // FIXME: Consider replacing the initializer with a ConstantExpr.
14136 } else if (var->isConstexpr()) {
14137 SourceLocation DiagLoc = var->getLocation();
14138 // If the note doesn't add any useful information other than a source
14139 // location, fold it into the primary diagnostic.
14140 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14141 diag::note_invalid_subexpr_in_const_expr) {
14142 DiagLoc = Notes[0].first;
14143 Notes.clear();
14144 }
14145 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
14146 << var << Init->getSourceRange();
14147 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
14148 Diag(Notes[I].first, Notes[I].second);
14149 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
14150 auto *Attr = var->getAttr<ConstInitAttr>();
14151 Diag(var->getLocation(), diag::err_require_constant_init_failed)
14152 << Init->getSourceRange();
14153 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
14154 << Attr->getRange() << Attr->isConstinit();
14155 for (auto &it : Notes)
14156 Diag(it.first, it.second);
14157 } else if (IsGlobal &&
14158 !getDiagnostics().isIgnored(diag::warn_global_constructor,
14159 var->getLocation())) {
14160 // Warn about globals which don't have a constant initializer. Don't
14161 // warn about globals with a non-trivial destructor because we already
14162 // warned about them.
14163 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
14164 if (!(RD && !RD->hasTrivialDestructor())) {
14165 // checkConstInit() here permits trivial default initialization even in
14166 // C++11 onwards, where such an initializer is not a constant initializer
14167 // but nonetheless doesn't require a global constructor.
14168 if (!checkConstInit())
14169 Diag(var->getLocation(), diag::warn_global_constructor)
14170 << Init->getSourceRange();
14171 }
14172 }
14173 }
14174
14175 // Apply section attributes and pragmas to global variables.
14176 if (GlobalStorage && var->isThisDeclarationADefinition() &&
14177 !inTemplateInstantiation()) {
14178 PragmaStack<StringLiteral *> *Stack = nullptr;
14179 int SectionFlags = ASTContext::PSF_Read;
14180 if (var->getType().isConstQualified()) {
14181 if (HasConstInit)
14182 Stack = &ConstSegStack;
14183 else {
14184 Stack = &BSSSegStack;
14185 SectionFlags |= ASTContext::PSF_Write;
14186 }
14187 } else if (var->hasInit() && HasConstInit) {
14188 Stack = &DataSegStack;
14189 SectionFlags |= ASTContext::PSF_Write;
14190 } else {
14191 Stack = &BSSSegStack;
14192 SectionFlags |= ASTContext::PSF_Write;
14193 }
14194 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
14195 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
14196 SectionFlags |= ASTContext::PSF_Implicit;
14197 UnifySection(SA->getName(), SectionFlags, var);
14198 } else if (Stack->CurrentValue) {
14199 SectionFlags |= ASTContext::PSF_Implicit;
14200 auto SectionName = Stack->CurrentValue->getString();
14201 var->addAttr(SectionAttr::CreateImplicit(Context, SectionName,
14202 Stack->CurrentPragmaLocation,
14203 SectionAttr::Declspec_allocate));
14204 if (UnifySection(SectionName, SectionFlags, var))
14205 var->dropAttr<SectionAttr>();
14206 }
14207
14208 // Apply the init_seg attribute if this has an initializer. If the
14209 // initializer turns out to not be dynamic, we'll end up ignoring this
14210 // attribute.
14211 if (CurInitSeg && var->getInit())
14212 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
14213 CurInitSegLoc));
14214 }
14215
14216 // All the following checks are C++ only.
14217 if (!getLangOpts().CPlusPlus) {
14218 // If this variable must be emitted, add it as an initializer for the
14219 // current module.
14220 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14221 Context.addModuleInitializer(ModuleScopes.back().Module, var);
14222 return;
14223 }
14224
14225 // Require the destructor.
14226 if (!type->isDependentType())
14227 if (const RecordType *recordType = baseType->getAs<RecordType>())
14228 FinalizeVarWithDestructor(var, recordType);
14229
14230 // If this variable must be emitted, add it as an initializer for the current
14231 // module.
14232 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14233 Context.addModuleInitializer(ModuleScopes.back().Module, var);
14234
14235 // Build the bindings if this is a structured binding declaration.
14236 if (auto *DD = dyn_cast<DecompositionDecl>(var))
14237 CheckCompleteDecompositionDeclaration(DD);
14238}
14239
14240/// Check if VD needs to be dllexport/dllimport due to being in a
14241/// dllexport/import function.
14242void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
14243 assert(VD->isStaticLocal())(static_cast <bool> (VD->isStaticLocal()) ? void (0)
: __assert_fail ("VD->isStaticLocal()", "clang/lib/Sema/SemaDecl.cpp"
, 14243, __extension__ __PRETTY_FUNCTION__))
;
14244
14245 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14246
14247 // Find outermost function when VD is in lambda function.
14248 while (FD && !getDLLAttr(FD) &&
14249 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
14250 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
14251 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
14252 }
14253
14254 if (!FD)
14255 return;
14256
14257 // Static locals inherit dll attributes from their function.
14258 if (Attr *A = getDLLAttr(FD)) {
14259 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
14260 NewAttr->setInherited(true);
14261 VD->addAttr(NewAttr);
14262 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
14263 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
14264 NewAttr->setInherited(true);
14265 VD->addAttr(NewAttr);
14266
14267 // Export this function to enforce exporting this static variable even
14268 // if it is not used in this compilation unit.
14269 if (!FD->hasAttr<DLLExportAttr>())
14270 FD->addAttr(NewAttr);
14271
14272 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
14273 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
14274 NewAttr->setInherited(true);
14275 VD->addAttr(NewAttr);
14276 }
14277}
14278
14279void Sema::CheckThreadLocalForLargeAlignment(VarDecl *VD) {
14280 assert(VD->getTLSKind())(static_cast <bool> (VD->getTLSKind()) ? void (0) : __assert_fail
("VD->getTLSKind()", "clang/lib/Sema/SemaDecl.cpp", 14280
, __extension__ __PRETTY_FUNCTION__))
;
14281
14282 // Perform TLS alignment check here after attributes attached to the variable
14283 // which may affect the alignment have been processed. Only perform the check
14284 // if the target has a maximum TLS alignment (zero means no constraints).
14285 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
14286 // Protect the check so that it's not performed on dependent types and
14287 // dependent alignments (we can't determine the alignment in that case).
14288 if (!VD->hasDependentAlignment()) {
14289 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
14290 if (Context.getDeclAlign(VD) > MaxAlignChars) {
14291 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
14292 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
14293 << (unsigned)MaxAlignChars.getQuantity();
14294 }
14295 }
14296 }
14297}
14298
14299/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
14300/// any semantic actions necessary after any initializer has been attached.
14301void Sema::FinalizeDeclaration(Decl *ThisDecl) {
14302 // Note that we are no longer parsing the initializer for this declaration.
14303 ParsingInitForAutoVars.erase(ThisDecl);
14304
14305 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
14306 if (!VD)
14307 return;
14308
14309 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
14310 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
14311 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
14312 if (PragmaClangBSSSection.Valid)
14313 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
14314 Context, PragmaClangBSSSection.SectionName,
14315 PragmaClangBSSSection.PragmaLocation));
14316 if (PragmaClangDataSection.Valid)
14317 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
14318 Context, PragmaClangDataSection.SectionName,
14319 PragmaClangDataSection.PragmaLocation));
14320 if (PragmaClangRodataSection.Valid)
14321 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
14322 Context, PragmaClangRodataSection.SectionName,
14323 PragmaClangRodataSection.PragmaLocation));
14324 if (PragmaClangRelroSection.Valid)
14325 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
14326 Context, PragmaClangRelroSection.SectionName,
14327 PragmaClangRelroSection.PragmaLocation));
14328 }
14329
14330 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
14331 for (auto *BD : DD->bindings()) {
14332 FinalizeDeclaration(BD);
14333 }
14334 }
14335
14336 checkAttributesAfterMerging(*this, *VD);
14337
14338 if (VD->isStaticLocal())
14339 CheckStaticLocalForDllExport(VD);
14340
14341 if (VD->getTLSKind())
14342 CheckThreadLocalForLargeAlignment(VD);
14343
14344 // Perform check for initializers of device-side global variables.
14345 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
14346 // 7.5). We must also apply the same checks to all __shared__
14347 // variables whether they are local or not. CUDA also allows
14348 // constant initializers for __constant__ and __device__ variables.
14349 if (getLangOpts().CUDA)
14350 checkAllowedCUDAInitializer(VD);
14351
14352 // Grab the dllimport or dllexport attribute off of the VarDecl.
14353 const InheritableAttr *DLLAttr = getDLLAttr(VD);
14354
14355 // Imported static data members cannot be defined out-of-line.
14356 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
14357 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
14358 VD->isThisDeclarationADefinition()) {
14359 // We allow definitions of dllimport class template static data members
14360 // with a warning.
14361 CXXRecordDecl *Context =
14362 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
14363 bool IsClassTemplateMember =
14364 isa<ClassTemplatePartialSpecializationDecl>(Context) ||
14365 Context->getDescribedClassTemplate();
14366
14367 Diag(VD->getLocation(),
14368 IsClassTemplateMember
14369 ? diag::warn_attribute_dllimport_static_field_definition
14370 : diag::err_attribute_dllimport_static_field_definition);
14371 Diag(IA->getLocation(), diag::note_attribute);
14372 if (!IsClassTemplateMember)
14373 VD->setInvalidDecl();
14374 }
14375 }
14376
14377 // dllimport/dllexport variables cannot be thread local, their TLS index
14378 // isn't exported with the variable.
14379 if (DLLAttr && VD->getTLSKind()) {
14380 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14381 if (F && getDLLAttr(F)) {
14382 assert(VD->isStaticLocal())(static_cast <bool> (VD->isStaticLocal()) ? void (0)
: __assert_fail ("VD->isStaticLocal()", "clang/lib/Sema/SemaDecl.cpp"
, 14382, __extension__ __PRETTY_FUNCTION__))
;
14383 // But if this is a static local in a dlimport/dllexport function, the
14384 // function will never be inlined, which means the var would never be
14385 // imported, so having it marked import/export is safe.
14386 } else {
14387 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
14388 << DLLAttr;
14389 VD->setInvalidDecl();
14390 }
14391 }
14392
14393 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
14394 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
14395 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
14396 << Attr;
14397 VD->dropAttr<UsedAttr>();
14398 }
14399 }
14400 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
14401 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
14402 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
14403 << Attr;
14404 VD->dropAttr<RetainAttr>();
14405 }
14406 }
14407
14408 const DeclContext *DC = VD->getDeclContext();
14409 // If there's a #pragma GCC visibility in scope, and this isn't a class
14410 // member, set the visibility of this variable.
14411 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
14412 AddPushedVisibilityAttribute(VD);
14413
14414 // FIXME: Warn on unused var template partial specializations.
14415 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
14416 MarkUnusedFileScopedDecl(VD);
14417
14418 // Now we have parsed the initializer and can update the table of magic
14419 // tag values.
14420 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
14421 !VD->getType()->isIntegralOrEnumerationType())
14422 return;
14423
14424 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
14425 const Expr *MagicValueExpr = VD->getInit();
14426 if (!MagicValueExpr) {
14427 continue;
14428 }
14429 std::optional<llvm::APSInt> MagicValueInt;
14430 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
14431 Diag(I->getRange().getBegin(),
14432 diag::err_type_tag_for_datatype_not_ice)
14433 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
14434 continue;
14435 }
14436 if (MagicValueInt->getActiveBits() > 64) {
14437 Diag(I->getRange().getBegin(),
14438 diag::err_type_tag_for_datatype_too_large)
14439 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
14440 continue;
14441 }
14442 uint64_t MagicValue = MagicValueInt->getZExtValue();
14443 RegisterTypeTagForDatatype(I->getArgumentKind(),
14444 MagicValue,
14445 I->getMatchingCType(),
14446 I->getLayoutCompatible(),
14447 I->getMustBeNull());
14448 }
14449}
14450
14451static bool hasDeducedAuto(DeclaratorDecl *DD) {
14452 auto *VD = dyn_cast<VarDecl>(DD);
14453 return VD && !VD->getType()->hasAutoForTrailingReturnType();
14454}
14455
14456Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
14457 ArrayRef<Decl *> Group) {
14458 SmallVector<Decl*, 8> Decls;
14459
14460 if (DS.isTypeSpecOwned())
14461 Decls.push_back(DS.getRepAsDecl());
14462
14463 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
14464 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
14465 bool DiagnosedMultipleDecomps = false;
14466 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
14467 bool DiagnosedNonDeducedAuto = false;
14468
14469 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
14470 if (Decl *D = Group[i]) {
14471 // For declarators, there are some additional syntactic-ish checks we need
14472 // to perform.
14473 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
14474 if (!FirstDeclaratorInGroup)
14475 FirstDeclaratorInGroup = DD;
14476 if (!FirstDecompDeclaratorInGroup)
14477 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
14478 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
14479 !hasDeducedAuto(DD))
14480 FirstNonDeducedAutoInGroup = DD;
14481
14482 if (FirstDeclaratorInGroup != DD) {
14483 // A decomposition declaration cannot be combined with any other
14484 // declaration in the same group.
14485 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
14486 Diag(FirstDecompDeclaratorInGroup->getLocation(),
14487 diag::err_decomp_decl_not_alone)
14488 << FirstDeclaratorInGroup->getSourceRange()
14489 << DD->getSourceRange();
14490 DiagnosedMultipleDecomps = true;
14491 }
14492
14493 // A declarator that uses 'auto' in any way other than to declare a
14494 // variable with a deduced type cannot be combined with any other
14495 // declarator in the same group.
14496 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
14497 Diag(FirstNonDeducedAutoInGroup->getLocation(),
14498 diag::err_auto_non_deduced_not_alone)
14499 << FirstNonDeducedAutoInGroup->getType()
14500 ->hasAutoForTrailingReturnType()
14501 << FirstDeclaratorInGroup->getSourceRange()
14502 << DD->getSourceRange();
14503 DiagnosedNonDeducedAuto = true;
14504 }
14505 }
14506 }
14507
14508 Decls.push_back(D);
14509 }
14510 }
14511
14512 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
14513 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
14514 handleTagNumbering(Tag, S);
14515 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
14516 getLangOpts().CPlusPlus)
14517 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
14518 }
14519 }
14520
14521 return BuildDeclaratorGroup(Decls);
14522}
14523
14524/// BuildDeclaratorGroup - convert a list of declarations into a declaration
14525/// group, performing any necessary semantic checking.
14526Sema::DeclGroupPtrTy
14527Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
14528 // C++14 [dcl.spec.auto]p7: (DR1347)
14529 // If the type that replaces the placeholder type is not the same in each
14530 // deduction, the program is ill-formed.
14531 if (Group.size() > 1) {
14532 QualType Deduced;
14533 VarDecl *DeducedDecl = nullptr;
14534 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
14535 VarDecl *D = dyn_cast<VarDecl>(Group[i]);
14536 if (!D || D->isInvalidDecl())
14537 break;
14538 DeducedType *DT = D->getType()->getContainedDeducedType();
14539 if (!DT || DT->getDeducedType().isNull())
14540 continue;
14541 if (Deduced.isNull()) {
14542 Deduced = DT->getDeducedType();
14543 DeducedDecl = D;
14544 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
14545 auto *AT = dyn_cast<AutoType>(DT);
14546 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
14547 diag::err_auto_different_deductions)
14548 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
14549 << DeducedDecl->getDeclName() << DT->getDeducedType()
14550 << D->getDeclName();
14551 if (DeducedDecl->hasInit())
14552 Dia << DeducedDecl->getInit()->getSourceRange();
14553 if (D->getInit())
14554 Dia << D->getInit()->getSourceRange();
14555 D->setInvalidDecl();
14556 break;
14557 }
14558 }
14559 }
14560
14561 ActOnDocumentableDecls(Group);
14562
14563 return DeclGroupPtrTy::make(
14564 DeclGroupRef::Create(Context, Group.data(), Group.size()));
14565}
14566
14567void Sema::ActOnDocumentableDecl(Decl *D) {
14568 ActOnDocumentableDecls(D);
14569}
14570
14571void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
14572 // Don't parse the comment if Doxygen diagnostics are ignored.
14573 if (Group.empty() || !Group[0])
14574 return;
14575
14576 if (Diags.isIgnored(diag::warn_doc_param_not_found,
14577 Group[0]->getLocation()) &&
14578 Diags.isIgnored(diag::warn_unknown_comment_command_name,
14579 Group[0]->getLocation()))
14580 return;
14581
14582 if (Group.size() >= 2) {
14583 // This is a decl group. Normally it will contain only declarations
14584 // produced from declarator list. But in case we have any definitions or
14585 // additional declaration references:
14586 // 'typedef struct S {} S;'
14587 // 'typedef struct S *S;'
14588 // 'struct S *pS;'
14589 // FinalizeDeclaratorGroup adds these as separate declarations.
14590 Decl *MaybeTagDecl = Group[0];
14591 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
14592 Group = Group.slice(1);
14593 }
14594 }
14595
14596 // FIMXE: We assume every Decl in the group is in the same file.
14597 // This is false when preprocessor constructs the group from decls in
14598 // different files (e. g. macros or #include).
14599 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
14600}
14601
14602/// Common checks for a parameter-declaration that should apply to both function
14603/// parameters and non-type template parameters.
14604void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
14605 // Check that there are no default arguments inside the type of this
14606 // parameter.
14607 if (getLangOpts().CPlusPlus)
14608 CheckExtraCXXDefaultArguments(D);
14609
14610 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
14611 if (D.getCXXScopeSpec().isSet()) {
14612 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
14613 << D.getCXXScopeSpec().getRange();
14614 }
14615
14616 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
14617 // simple identifier except [...irrelevant cases...].
14618 switch (D.getName().getKind()) {
14619 case UnqualifiedIdKind::IK_Identifier:
14620 break;
14621
14622 case UnqualifiedIdKind::IK_OperatorFunctionId:
14623 case UnqualifiedIdKind::IK_ConversionFunctionId:
14624 case UnqualifiedIdKind::IK_LiteralOperatorId:
14625 case UnqualifiedIdKind::IK_ConstructorName:
14626 case UnqualifiedIdKind::IK_DestructorName:
14627 case UnqualifiedIdKind::IK_ImplicitSelfParam:
14628 case UnqualifiedIdKind::IK_DeductionGuideName:
14629 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
14630 << GetNameForDeclarator(D).getName();
14631 break;
14632
14633 case UnqualifiedIdKind::IK_TemplateId:
14634 case UnqualifiedIdKind::IK_ConstructorTemplateId:
14635 // GetNameForDeclarator would not produce a useful name in this case.
14636 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
14637 break;
14638 }
14639}
14640
14641/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
14642/// to introduce parameters into function prototype scope.
14643Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
14644 const DeclSpec &DS = D.getDeclSpec();
14645
14646 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
14647
14648 // C++03 [dcl.stc]p2 also permits 'auto'.
14649 StorageClass SC = SC_None;
14650 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
14651 SC = SC_Register;
14652 // In C++11, the 'register' storage class specifier is deprecated.
14653 // In C++17, it is not allowed, but we tolerate it as an extension.
14654 if (getLangOpts().CPlusPlus11) {
14655 Diag(DS.getStorageClassSpecLoc(),
14656 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
14657 : diag::warn_deprecated_register)
14658 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
14659 }
14660 } else if (getLangOpts().CPlusPlus &&
14661 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
14662 SC = SC_Auto;
14663 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
14664 Diag(DS.getStorageClassSpecLoc(),
14665 diag::err_invalid_storage_class_in_func_decl);
14666 D.getMutableDeclSpec().ClearStorageClassSpecs();
14667 }
14668
14669 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
14670 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
14671 << DeclSpec::getSpecifierName(TSCS);
14672 if (DS.isInlineSpecified())
14673 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
14674 << getLangOpts().CPlusPlus17;
14675 if (DS.hasConstexprSpecifier())
14676 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
14677 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
14678
14679 DiagnoseFunctionSpecifiers(DS);
14680
14681 CheckFunctionOrTemplateParamDeclarator(S, D);
14682
14683 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14684 QualType parmDeclType = TInfo->getType();
14685
14686 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
14687 IdentifierInfo *II = D.getIdentifier();
14688 if (II) {
14689 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
14690 ForVisibleRedeclaration);
14691 LookupName(R, S);
14692 if (R.isSingleResult()) {
14693 NamedDecl *PrevDecl = R.getFoundDecl();
14694 if (PrevDecl->isTemplateParameter()) {
14695 // Maybe we will complain about the shadowed template parameter.
14696 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14697 // Just pretend that we didn't see the previous declaration.
14698 PrevDecl = nullptr;
14699 } else if (S->isDeclScope(PrevDecl)) {
14700 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
14701 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14702
14703 // Recover by removing the name
14704 II = nullptr;
14705 D.SetIdentifier(nullptr, D.getIdentifierLoc());
14706 D.setInvalidType(true);
14707 }
14708 }
14709 }
14710
14711 // Temporarily put parameter variables in the translation unit, not
14712 // the enclosing context. This prevents them from accidentally
14713 // looking like class members in C++.
14714 ParmVarDecl *New =
14715 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
14716 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
14717
14718 if (D.isInvalidType())
14719 New->setInvalidDecl();
14720
14721 assert(S->isFunctionPrototypeScope())(static_cast <bool> (S->isFunctionPrototypeScope()) ?
void (0) : __assert_fail ("S->isFunctionPrototypeScope()"
, "clang/lib/Sema/SemaDecl.cpp", 14721, __extension__ __PRETTY_FUNCTION__
))
;
14722 assert(S->getFunctionPrototypeDepth() >= 1)(static_cast <bool> (S->getFunctionPrototypeDepth() >=
1) ? void (0) : __assert_fail ("S->getFunctionPrototypeDepth() >= 1"
, "clang/lib/Sema/SemaDecl.cpp", 14722, __extension__ __PRETTY_FUNCTION__
))
;
14723 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
14724 S->getNextFunctionPrototypeIndex());
14725
14726 // Add the parameter declaration into this scope.
14727 S->AddDecl(New);
14728 if (II)
14729 IdResolver.AddDecl(New);
14730
14731 ProcessDeclAttributes(S, New, D);
14732
14733 if (D.getDeclSpec().isModulePrivateSpecified())
14734 Diag(New->getLocation(), diag::err_module_private_local)
14735 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14736 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
14737
14738 if (New->hasAttr<BlocksAttr>()) {
14739 Diag(New->getLocation(), diag::err_block_on_nonlocal);
14740 }
14741
14742 if (getLangOpts().OpenCL)
14743 deduceOpenCLAddressSpace(New);
14744
14745 return New;
14746}
14747
14748/// Synthesizes a variable for a parameter arising from a
14749/// typedef.
14750ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
14751 SourceLocation Loc,
14752 QualType T) {
14753 /* FIXME: setting StartLoc == Loc.
14754 Would it be worth to modify callers so as to provide proper source
14755 location for the unnamed parameters, embedding the parameter's type? */
14756 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
14757 T, Context.getTrivialTypeSourceInfo(T, Loc),
14758 SC_None, nullptr);
14759 Param->setImplicit();
14760 return Param;
14761}
14762
14763void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
14764 // Don't diagnose unused-parameter errors in template instantiations; we
14765 // will already have done so in the template itself.
14766 if (inTemplateInstantiation())
14767 return;
14768
14769 for (const ParmVarDecl *Parameter : Parameters) {
14770 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
14771 !Parameter->hasAttr<UnusedAttr>()) {
14772 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
14773 << Parameter->getDeclName();
14774 }
14775 }
14776}
14777
14778void Sema::DiagnoseSizeOfParametersAndReturnValue(
14779 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
14780 if (LangOpts.NumLargeByValueCopy == 0) // No check.
14781 return;
14782
14783 // Warn if the return value is pass-by-value and larger than the specified
14784 // threshold.
14785 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
14786 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
14787 if (Size > LangOpts.NumLargeByValueCopy)
14788 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
14789 }
14790
14791 // Warn if any parameter is pass-by-value and larger than the specified
14792 // threshold.
14793 for (const ParmVarDecl *Parameter : Parameters) {
14794 QualType T = Parameter->getType();
14795 if (T->isDependentType() || !T.isPODType(Context))
14796 continue;
14797 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
14798 if (Size > LangOpts.NumLargeByValueCopy)
14799 Diag(Parameter->getLocation(), diag::warn_parameter_size)
14800 << Parameter << Size;
14801 }
14802}
14803
14804ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
14805 SourceLocation NameLoc, IdentifierInfo *Name,
14806 QualType T, TypeSourceInfo *TSInfo,
14807 StorageClass SC) {
14808 // In ARC, infer a lifetime qualifier for appropriate parameter types.
14809 if (getLangOpts().ObjCAutoRefCount &&
14810 T.getObjCLifetime() == Qualifiers::OCL_None &&
14811 T->isObjCLifetimeType()) {
14812
14813 Qualifiers::ObjCLifetime lifetime;
14814
14815 // Special cases for arrays:
14816 // - if it's const, use __unsafe_unretained
14817 // - otherwise, it's an error
14818 if (T->isArrayType()) {
14819 if (!T.isConstQualified()) {
14820 if (DelayedDiagnostics.shouldDelayDiagnostics())
14821 DelayedDiagnostics.add(
14822 sema::DelayedDiagnostic::makeForbiddenType(
14823 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
14824 else
14825 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
14826 << TSInfo->getTypeLoc().getSourceRange();
14827 }
14828 lifetime = Qualifiers::OCL_ExplicitNone;
14829 } else {
14830 lifetime = T->getObjCARCImplicitLifetime();
14831 }
14832 T = Context.getLifetimeQualifiedType(T, lifetime);
14833 }
14834
14835 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
14836 Context.getAdjustedParameterType(T),
14837 TSInfo, SC, nullptr);
14838
14839 // Make a note if we created a new pack in the scope of a lambda, so that
14840 // we know that references to that pack must also be expanded within the
14841 // lambda scope.
14842 if (New->isParameterPack())
14843 if (auto *LSI = getEnclosingLambda())
14844 LSI->LocalPacks.push_back(New);
14845
14846 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
14847 New->getType().hasNonTrivialToPrimitiveCopyCUnion())
14848 checkNonTrivialCUnion(New->getType(), New->getLocation(),
14849 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
14850
14851 // Parameters can not be abstract class types.
14852 // For record types, this is done by the AbstractClassUsageDiagnoser once
14853 // the class has been completely parsed.
14854 if (!CurContext->isRecord() &&
14855 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
14856 AbstractParamType))
14857 New->setInvalidDecl();
14858
14859 // Parameter declarators cannot be interface types. All ObjC objects are
14860 // passed by reference.
14861 if (T->isObjCObjectType()) {
14862 SourceLocation TypeEndLoc =
14863 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
14864 Diag(NameLoc,
14865 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
14866 << FixItHint::CreateInsertion(TypeEndLoc, "*");
14867 T = Context.getObjCObjectPointerType(T);
14868 New->setType(T);
14869 }
14870
14871 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
14872 // duration shall not be qualified by an address-space qualifier."
14873 // Since all parameters have automatic store duration, they can not have
14874 // an address space.
14875 if (T.getAddressSpace() != LangAS::Default &&
14876 // OpenCL allows function arguments declared to be an array of a type
14877 // to be qualified with an address space.
14878 !(getLangOpts().OpenCL &&
14879 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&
14880 // WebAssembly allows reference types as parameters. Funcref in particular
14881 // lives in a different address space.
14882 !(T->isFunctionPointerType() &&
14883 T.getAddressSpace() == LangAS::wasm_funcref)) {
14884 Diag(NameLoc, diag::err_arg_with_address_space);
14885 New->setInvalidDecl();
14886 }
14887
14888 // PPC MMA non-pointer types are not allowed as function argument types.
14889 if (Context.getTargetInfo().getTriple().isPPC64() &&
14890 CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
14891 New->setInvalidDecl();
14892 }
14893
14894 return New;
14895}
14896
14897void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
14898 SourceLocation LocAfterDecls) {
14899 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
14900
14901 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
14902 // in the declaration list shall have at least one declarator, those
14903 // declarators shall only declare identifiers from the identifier list, and
14904 // every identifier in the identifier list shall be declared.
14905 //
14906 // C89 3.7.1p5 "If a declarator includes an identifier list, only the
14907 // identifiers it names shall be declared in the declaration list."
14908 //
14909 // This is why we only diagnose in C99 and later. Note, the other conditions
14910 // listed are checked elsewhere.
14911 if (!FTI.hasPrototype) {
14912 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
14913 --i;
14914 if (FTI.Params[i].Param == nullptr) {
14915 if (getLangOpts().C99) {
14916 SmallString<256> Code;
14917 llvm::raw_svector_ostream(Code)
14918 << " int " << FTI.Params[i].Ident->getName() << ";\n";
14919 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
14920 << FTI.Params[i].Ident
14921 << FixItHint::CreateInsertion(LocAfterDecls, Code);
14922 }
14923
14924 // Implicitly declare the argument as type 'int' for lack of a better
14925 // type.
14926 AttributeFactory attrs;
14927 DeclSpec DS(attrs);
14928 const char* PrevSpec; // unused
14929 unsigned DiagID; // unused
14930 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
14931 DiagID, Context.getPrintingPolicy());
14932 // Use the identifier location for the type source range.
14933 DS.SetRangeStart(FTI.Params[i].IdentLoc);
14934 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
14935 Declarator ParamD(DS, ParsedAttributesView::none(),
14936 DeclaratorContext::KNRTypeList);
14937 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
14938 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
14939 }
14940 }
14941 }
14942}
14943
14944Decl *
14945Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
14946 MultiTemplateParamsArg TemplateParameterLists,
14947 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
14948 assert(getCurFunctionDecl() == nullptr && "Function parsing confused")(static_cast <bool> (getCurFunctionDecl() == nullptr &&
"Function parsing confused") ? void (0) : __assert_fail ("getCurFunctionDecl() == nullptr && \"Function parsing confused\""
, "clang/lib/Sema/SemaDecl.cpp", 14948, __extension__ __PRETTY_FUNCTION__
))
;
14949 assert(D.isFunctionDeclarator() && "Not a function declarator!")(static_cast <bool> (D.isFunctionDeclarator() &&
"Not a function declarator!") ? void (0) : __assert_fail ("D.isFunctionDeclarator() && \"Not a function declarator!\""
, "clang/lib/Sema/SemaDecl.cpp", 14949, __extension__ __PRETTY_FUNCTION__
))
;
14950 Scope *ParentScope = FnBodyScope->getParent();
14951
14952 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
14953 // we define a non-templated function definition, we will create a declaration
14954 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
14955 // The base function declaration will have the equivalent of an `omp declare
14956 // variant` annotation which specifies the mangled definition as a
14957 // specialization function under the OpenMP context defined as part of the
14958 // `omp begin declare variant`.
14959 SmallVector<FunctionDecl *, 4> Bases;
14960 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
14961 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
14962 ParentScope, D, TemplateParameterLists, Bases);
14963
14964 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
14965 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
14966 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
14967
14968 if (!Bases.empty())
14969 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
14970
14971 return Dcl;
14972}
14973
14974void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
14975 Consumer.HandleInlineFunctionDefinition(D);
14976}
14977
14978static bool FindPossiblePrototype(const FunctionDecl *FD,
14979 const FunctionDecl *&PossiblePrototype) {
14980 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
14981 Prev = Prev->getPreviousDecl()) {
14982 // Ignore any declarations that occur in function or method
14983 // scope, because they aren't visible from the header.
14984 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
14985 continue;
14986
14987 PossiblePrototype = Prev;
14988 return Prev->getType()->isFunctionProtoType();
14989 }
14990 return false;
14991}
14992
14993static bool
14994ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
14995 const FunctionDecl *&PossiblePrototype) {
14996 // Don't warn about invalid declarations.
14997 if (FD->isInvalidDecl())
14998 return false;
14999
15000 // Or declarations that aren't global.
15001 if (!FD->isGlobal())
15002 return false;
15003
15004 // Don't warn about C++ member functions.
15005 if (isa<CXXMethodDecl>(FD))
15006 return false;
15007
15008 // Don't warn about 'main'.
15009 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
15010 if (IdentifierInfo *II = FD->getIdentifier())
15011 if (II->isStr("main") || II->isStr("efi_main"))
15012 return false;
15013
15014 // Don't warn about inline functions.
15015 if (FD->isInlined())
15016 return false;
15017
15018 // Don't warn about function templates.
15019 if (FD->getDescribedFunctionTemplate())
15020 return false;
15021
15022 // Don't warn about function template specializations.
15023 if (FD->isFunctionTemplateSpecialization())
15024 return false;
15025
15026 // Don't warn for OpenCL kernels.
15027 if (FD->hasAttr<OpenCLKernelAttr>())
15028 return false;
15029
15030 // Don't warn on explicitly deleted functions.
15031 if (FD->isDeleted())
15032 return false;
15033
15034 // Don't warn on implicitly local functions (such as having local-typed
15035 // parameters).
15036 if (!FD->isExternallyVisible())
15037 return false;
15038
15039 // If we were able to find a potential prototype, don't warn.
15040 if (FindPossiblePrototype(FD, PossiblePrototype))
15041 return false;
15042
15043 return true;
15044}
15045
15046void
15047Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
15048 const FunctionDecl *EffectiveDefinition,
15049 SkipBodyInfo *SkipBody) {
15050 const FunctionDecl *Definition = EffectiveDefinition;
15051 if (!Definition &&
15052 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
15053 return;
15054
15055 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
15056 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
15057 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
15058 // A merged copy of the same function, instantiated as a member of
15059 // the same class, is OK.
15060 if (declaresSameEntity(OrigFD, OrigDef) &&
15061 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
15062 cast<Decl>(FD->getLexicalDeclContext())))
15063 return;
15064 }
15065 }
15066 }
15067
15068 if (canRedefineFunction(Definition, getLangOpts()))
15069 return;
15070
15071 // Don't emit an error when this is redefinition of a typo-corrected
15072 // definition.
15073 if (TypoCorrectedFunctionDefinitions.count(Definition))
15074 return;
15075
15076 // If we don't have a visible definition of the function, and it's inline or
15077 // a template, skip the new definition.
15078 if (SkipBody && !hasVisibleDefinition(Definition) &&
15079 (Definition->getFormalLinkage() == InternalLinkage ||
15080 Definition->isInlined() ||
15081 Definition->getDescribedFunctionTemplate() ||
15082 Definition->getNumTemplateParameterLists())) {
15083 SkipBody->ShouldSkip = true;
15084 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
15085 if (auto *TD = Definition->getDescribedFunctionTemplate())
15086 makeMergedDefinitionVisible(TD);
15087 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
15088 return;
15089 }
15090
15091 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
15092 Definition->getStorageClass() == SC_Extern)
15093 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
15094 << FD << getLangOpts().CPlusPlus;
15095 else
15096 Diag(FD->getLocation(), diag::err_redefinition) << FD;
15097
15098 Diag(Definition->getLocation(), diag::note_previous_definition);
15099 FD->setInvalidDecl();
15100}
15101
15102static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
15103 Sema &S) {
15104 CXXRecordDecl *const LambdaClass = CallOperator->getParent();
15105
15106 LambdaScopeInfo *LSI = S.PushLambdaScope();
15107 LSI->CallOperator = CallOperator;
15108 LSI->Lambda = LambdaClass;
15109 LSI->ReturnType = CallOperator->getReturnType();
15110 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
15111
15112 if (LCD == LCD_None)
15113 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
15114 else if (LCD == LCD_ByCopy)
15115 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
15116 else if (LCD == LCD_ByRef)
15117 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
15118 DeclarationNameInfo DNI = CallOperator->getNameInfo();
15119
15120 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
15121 LSI->Mutable = !CallOperator->isConst();
15122
15123 // Add the captures to the LSI so they can be noted as already
15124 // captured within tryCaptureVar.
15125 auto I = LambdaClass->field_begin();
15126 for (const auto &C : LambdaClass->captures()) {
15127 if (C.capturesVariable()) {
15128 ValueDecl *VD = C.getCapturedVar();
15129 if (VD->isInitCapture())
15130 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
15131 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
15132 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
15133 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
15134 /*EllipsisLoc*/C.isPackExpansion()
15135 ? C.getEllipsisLoc() : SourceLocation(),
15136 I->getType(), /*Invalid*/false);
15137
15138 } else if (C.capturesThis()) {
15139 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
15140 C.getCaptureKind() == LCK_StarThis);
15141 } else {
15142 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
15143 I->getType());
15144 }
15145 ++I;
15146 }
15147}
15148
15149Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
15150 SkipBodyInfo *SkipBody,
15151 FnBodyKind BodyKind) {
15152 if (!D) {
15153 // Parsing the function declaration failed in some way. Push on a fake scope
15154 // anyway so we can try to parse the function body.
15155 PushFunctionScope();
15156 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
15157 return D;
15158 }
15159
15160 FunctionDecl *FD = nullptr;
15161
15162 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
15163 FD = FunTmpl->getTemplatedDecl();
15164 else
15165 FD = cast<FunctionDecl>(D);
15166
15167 // Do not push if it is a lambda because one is already pushed when building
15168 // the lambda in ActOnStartOfLambdaDefinition().
15169 if (!isLambdaCallOperator(FD))
15170 // [expr.const]/p14.1
15171 // An expression or conversion is in an immediate function context if it is
15172 // potentially evaluated and either: its innermost enclosing non-block scope
15173 // is a function parameter scope of an immediate function.
15174 PushExpressionEvaluationContext(
15175 FD->isConsteval() ? ExpressionEvaluationContext::ImmediateFunctionContext
15176 : ExprEvalContexts.back().Context);
15177
15178 // Each ExpressionEvaluationContextRecord also keeps track of whether the
15179 // context is nested in an immediate function context, so smaller contexts
15180 // that appear inside immediate functions (like variable initializers) are
15181 // considered to be inside an immediate function context even though by
15182 // themselves they are not immediate function contexts. But when a new
15183 // function is entered, we need to reset this tracking, since the entered
15184 // function might be not an immediate function.
15185 ExprEvalContexts.back().InImmediateFunctionContext = FD->isConsteval();
15186
15187 // Check for defining attributes before the check for redefinition.
15188 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
15189 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
15190 FD->dropAttr<AliasAttr>();
15191 FD->setInvalidDecl();
15192 }
15193 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
15194 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
15195 FD->dropAttr<IFuncAttr>();
15196 FD->setInvalidDecl();
15197 }
15198 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
15199 if (!Context.getTargetInfo().hasFeature("fmv") &&
15200 !Attr->isDefaultVersion()) {
15201 // If function multi versioning disabled skip parsing function body
15202 // defined with non-default target_version attribute
15203 if (SkipBody)
15204 SkipBody->ShouldSkip = true;
15205 return nullptr;
15206 }
15207 }
15208
15209 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
15210 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
15211 Ctor->isDefaultConstructor() &&
15212 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
15213 // If this is an MS ABI dllexport default constructor, instantiate any
15214 // default arguments.
15215 InstantiateDefaultCtorDefaultArgs(Ctor);
15216 }
15217 }
15218
15219 // See if this is a redefinition. If 'will have body' (or similar) is already
15220 // set, then these checks were already performed when it was set.
15221 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
15222 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
15223 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
15224
15225 // If we're skipping the body, we're done. Don't enter the scope.
15226 if (SkipBody && SkipBody->ShouldSkip)
15227 return D;
15228 }
15229
15230 // Mark this function as "will have a body eventually". This lets users to
15231 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
15232 // this function.
15233 FD->setWillHaveBody();
15234
15235 // If we are instantiating a generic lambda call operator, push
15236 // a LambdaScopeInfo onto the function stack. But use the information
15237 // that's already been calculated (ActOnLambdaExpr) to prime the current
15238 // LambdaScopeInfo.
15239 // When the template operator is being specialized, the LambdaScopeInfo,
15240 // has to be properly restored so that tryCaptureVariable doesn't try
15241 // and capture any new variables. In addition when calculating potential
15242 // captures during transformation of nested lambdas, it is necessary to
15243 // have the LSI properly restored.
15244 if (isGenericLambdaCallOperatorSpecialization(FD)) {
15245 assert(inTemplateInstantiation() &&(static_cast <bool> (inTemplateInstantiation() &&
"There should be an active template instantiation on the stack "
"when instantiating a generic lambda!") ? void (0) : __assert_fail
("inTemplateInstantiation() && \"There should be an active template instantiation on the stack \" \"when instantiating a generic lambda!\""
, "clang/lib/Sema/SemaDecl.cpp", 15247, __extension__ __PRETTY_FUNCTION__
))
15246 "There should be an active template instantiation on the stack "(static_cast <bool> (inTemplateInstantiation() &&
"There should be an active template instantiation on the stack "
"when instantiating a generic lambda!") ? void (0) : __assert_fail
("inTemplateInstantiation() && \"There should be an active template instantiation on the stack \" \"when instantiating a generic lambda!\""
, "clang/lib/Sema/SemaDecl.cpp", 15247, __extension__ __PRETTY_FUNCTION__
))
15247 "when instantiating a generic lambda!")(static_cast <bool> (inTemplateInstantiation() &&
"There should be an active template instantiation on the stack "
"when instantiating a generic lambda!") ? void (0) : __assert_fail
("inTemplateInstantiation() && \"There should be an active template instantiation on the stack \" \"when instantiating a generic lambda!\""
, "clang/lib/Sema/SemaDecl.cpp", 15247, __extension__ __PRETTY_FUNCTION__
))
;
15248 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
15249 } else {
15250 // Enter a new function scope
15251 PushFunctionScope();
15252 }
15253
15254 // Builtin functions cannot be defined.
15255 if (unsigned BuiltinID = FD->getBuiltinID()) {
15256 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
15257 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
15258 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
15259 FD->setInvalidDecl();
15260 }
15261 }
15262
15263 // The return type of a function definition must be complete (C99 6.9.1p3),
15264 // unless the function is deleted (C++ specifc, C++ [dcl.fct.def.general]p2)
15265 QualType ResultType = FD->getReturnType();
15266 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
15267 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
15268 RequireCompleteType(FD->getLocation(), ResultType,
15269 diag::err_func_def_incomplete_result))
15270 FD->setInvalidDecl();
15271
15272 if (FnBodyScope)
15273 PushDeclContext(FnBodyScope, FD);
15274
15275 // Check the validity of our function parameters
15276 if (BodyKind != FnBodyKind::Delete)
15277 CheckParmsForFunctionDef(FD->parameters(),
15278 /*CheckParameterNames=*/true);
15279
15280 // Add non-parameter declarations already in the function to the current
15281 // scope.
15282 if (FnBodyScope) {
15283 for (Decl *NPD : FD->decls()) {
15284 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
15285 if (!NonParmDecl)
15286 continue;
15287 assert(!isa<ParmVarDecl>(NonParmDecl) &&(static_cast <bool> (!isa<ParmVarDecl>(NonParmDecl
) && "parameters should not be in newly created FD yet"
) ? void (0) : __assert_fail ("!isa<ParmVarDecl>(NonParmDecl) && \"parameters should not be in newly created FD yet\""
, "clang/lib/Sema/SemaDecl.cpp", 15288, __extension__ __PRETTY_FUNCTION__
))
15288 "parameters should not be in newly created FD yet")(static_cast <bool> (!isa<ParmVarDecl>(NonParmDecl
) && "parameters should not be in newly created FD yet"
) ? void (0) : __assert_fail ("!isa<ParmVarDecl>(NonParmDecl) && \"parameters should not be in newly created FD yet\""
, "clang/lib/Sema/SemaDecl.cpp", 15288, __extension__ __PRETTY_FUNCTION__
))
;
15289
15290 // If the decl has a name, make it accessible in the current scope.
15291 if (NonParmDecl->getDeclName())
15292 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
15293
15294 // Similarly, dive into enums and fish their constants out, making them
15295 // accessible in this scope.
15296 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
15297 for (auto *EI : ED->enumerators())
15298 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
15299 }
15300 }
15301 }
15302
15303 // Introduce our parameters into the function scope
15304 for (auto *Param : FD->parameters()) {
15305 Param->setOwningFunction(FD);
15306
15307 // If this has an identifier, add it to the scope stack.
15308 if (Param->getIdentifier() && FnBodyScope) {
15309 CheckShadow(FnBodyScope, Param);
15310
15311 PushOnScopeChains(Param, FnBodyScope);
15312 }
15313 }
15314
15315 // C++ [module.import/6] external definitions are not permitted in header
15316 // units. Deleted and Defaulted functions are implicitly inline (but the
15317 // inline state is not set at this point, so check the BodyKind explicitly).
15318 // FIXME: Consider an alternate location for the test where the inlined()
15319 // state is complete.
15320 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
15321 !FD->isInvalidDecl() && !FD->isInlined() &&
15322 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
15323 FD->getFormalLinkage() == Linkage::ExternalLinkage &&
15324 !FD->isTemplated() && !FD->isTemplateInstantiation()) {
15325 assert(FD->isThisDeclarationADefinition())(static_cast <bool> (FD->isThisDeclarationADefinition
()) ? void (0) : __assert_fail ("FD->isThisDeclarationADefinition()"
, "clang/lib/Sema/SemaDecl.cpp", 15325, __extension__ __PRETTY_FUNCTION__
))
;
15326 Diag(FD->getLocation(), diag::err_extern_def_in_header_unit);
15327 FD->setInvalidDecl();
15328 }
15329
15330 // Ensure that the function's exception specification is instantiated.
15331 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
15332 ResolveExceptionSpec(D->getLocation(), FPT);
15333
15334 // dllimport cannot be applied to non-inline function definitions.
15335 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
15336 !FD->isTemplateInstantiation()) {
15337 assert(!FD->hasAttr<DLLExportAttr>())(static_cast <bool> (!FD->hasAttr<DLLExportAttr>
()) ? void (0) : __assert_fail ("!FD->hasAttr<DLLExportAttr>()"
, "clang/lib/Sema/SemaDecl.cpp", 15337, __extension__ __PRETTY_FUNCTION__
))
;
15338 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
15339 FD->setInvalidDecl();
15340 return D;
15341 }
15342 // We want to attach documentation to original Decl (which might be
15343 // a function template).
15344 ActOnDocumentableDecl(D);
15345 if (getCurLexicalContext()->isObjCContainer() &&
15346 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
15347 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
15348 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
15349
15350 return D;
15351}
15352
15353/// Given the set of return statements within a function body,
15354/// compute the variables that are subject to the named return value
15355/// optimization.
15356///
15357/// Each of the variables that is subject to the named return value
15358/// optimization will be marked as NRVO variables in the AST, and any
15359/// return statement that has a marked NRVO variable as its NRVO candidate can
15360/// use the named return value optimization.
15361///
15362/// This function applies a very simplistic algorithm for NRVO: if every return
15363/// statement in the scope of a variable has the same NRVO candidate, that
15364/// candidate is an NRVO variable.
15365void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
15366 ReturnStmt **Returns = Scope->Returns.data();
15367
15368 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
15369 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
15370 if (!NRVOCandidate->isNRVOVariable())
15371 Returns[I]->setNRVOCandidate(nullptr);
15372 }
15373 }
15374}
15375
15376bool Sema::canDelayFunctionBody(const Declarator &D) {
15377 // We can't delay parsing the body of a constexpr function template (yet).
15378 if (D.getDeclSpec().hasConstexprSpecifier())
15379 return false;
15380
15381 // We can't delay parsing the body of a function template with a deduced
15382 // return type (yet).
15383 if (D.getDeclSpec().hasAutoTypeSpec()) {
15384 // If the placeholder introduces a non-deduced trailing return type,
15385 // we can still delay parsing it.
15386 if (D.getNumTypeObjects()) {
15387 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
15388 if (Outer.Kind == DeclaratorChunk::Function &&
15389 Outer.Fun.hasTrailingReturnType()) {
15390 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
15391 return Ty.isNull() || !Ty->isUndeducedType();
15392 }
15393 }
15394 return false;
15395 }
15396
15397 return true;
15398}
15399
15400bool Sema::canSkipFunctionBody(Decl *D) {
15401 // We cannot skip the body of a function (or function template) which is
15402 // constexpr, since we may need to evaluate its body in order to parse the
15403 // rest of the file.
15404 // We cannot skip the body of a function with an undeduced return type,
15405 // because any callers of that function need to know the type.
15406 if (const FunctionDecl *FD = D->getAsFunction()) {
15407 if (FD->isConstexpr())
15408 return false;
15409 // We can't simply call Type::isUndeducedType here, because inside template
15410 // auto can be deduced to a dependent type, which is not considered
15411 // "undeduced".
15412 if (FD->getReturnType()->getContainedDeducedType())
15413 return false;
15414 }
15415 return Consumer.shouldSkipFunctionBody(D);
15416}
15417
15418Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
15419 if (!Decl)
15420 return nullptr;
15421 if (FunctionDecl *FD = Decl->getAsFunction())
15422 FD->setHasSkippedBody();
15423 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
15424 MD->setHasSkippedBody();
15425 return Decl;
15426}
15427
15428Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
15429 return ActOnFinishFunctionBody(D, BodyArg, false);
15430}
15431
15432/// RAII object that pops an ExpressionEvaluationContext when exiting a function
15433/// body.
15434class ExitFunctionBodyRAII {
15435public:
15436 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
15437 ~ExitFunctionBodyRAII() {
15438 if (!IsLambda)
15439 S.PopExpressionEvaluationContext();
15440 }
15441
15442private:
15443 Sema &S;
15444 bool IsLambda = false;
15445};
15446
15447static void diagnoseImplicitlyRetainedSelf(Sema &S) {
15448 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
15449
15450 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
15451 if (EscapeInfo.count(BD))
15452 return EscapeInfo[BD];
15453
15454 bool R = false;
15455 const BlockDecl *CurBD = BD;
15456
15457 do {
15458 R = !CurBD->doesNotEscape();
15459 if (R)
15460 break;
15461 CurBD = CurBD->getParent()->getInnermostBlockDecl();
15462 } while (CurBD);
15463
15464 return EscapeInfo[BD] = R;
15465 };
15466
15467 // If the location where 'self' is implicitly retained is inside a escaping
15468 // block, emit a diagnostic.
15469 for (const std::pair<SourceLocation, const BlockDecl *> &P :
15470 S.ImplicitlyRetainedSelfLocs)
15471 if (IsOrNestedInEscapingBlock(P.second))
15472 S.Diag(P.first, diag::warn_implicitly_retains_self)
15473 << FixItHint::CreateInsertion(P.first, "self->");
15474}
15475
15476Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
15477 bool IsInstantiation) {
15478 FunctionScopeInfo *FSI = getCurFunction();
15479 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
15480
15481 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
15482 FD->addAttr(StrictFPAttr::CreateImplicit(Context));
15483
15484 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
15485 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
15486
15487 if (getLangOpts().Coroutines && FSI->isCoroutine())
15488 CheckCompletedCoroutineBody(FD, Body);
15489
15490 {
15491 // Do not call PopExpressionEvaluationContext() if it is a lambda because
15492 // one is already popped when finishing the lambda in BuildLambdaExpr().
15493 // This is meant to pop the context added in ActOnStartOfFunctionDef().
15494 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
15495
15496 if (FD) {
15497 FD->setBody(Body);
15498 FD->setWillHaveBody(false);
15499
15500 if (getLangOpts().CPlusPlus14) {
15501 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
15502 FD->getReturnType()->isUndeducedType()) {
15503 // For a function with a deduced result type to return void,
15504 // the result type as written must be 'auto' or 'decltype(auto)',
15505 // possibly cv-qualified or constrained, but not ref-qualified.
15506 if (!FD->getReturnType()->getAs<AutoType>()) {
15507 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
15508 << FD->getReturnType();
15509 FD->setInvalidDecl();
15510 } else {
15511 // Falling off the end of the function is the same as 'return;'.
15512 Expr *Dummy = nullptr;
15513 if (DeduceFunctionTypeFromReturnExpr(
15514 FD, dcl->getLocation(), Dummy,
15515 FD->getReturnType()->getAs<AutoType>()))
15516 FD->setInvalidDecl();
15517 }
15518 }
15519 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
15520 // In C++11, we don't use 'auto' deduction rules for lambda call
15521 // operators because we don't support return type deduction.
15522 auto *LSI = getCurLambda();
15523 if (LSI->HasImplicitReturnType) {
15524 deduceClosureReturnType(*LSI);
15525
15526 // C++11 [expr.prim.lambda]p4:
15527 // [...] if there are no return statements in the compound-statement
15528 // [the deduced type is] the type void
15529 QualType RetType =
15530 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
15531
15532 // Update the return type to the deduced type.
15533 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
15534 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
15535 Proto->getExtProtoInfo()));
15536 }
15537 }
15538
15539 // If the function implicitly returns zero (like 'main') or is naked,
15540 // don't complain about missing return statements.
15541 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
15542 WP.disableCheckFallThrough();
15543
15544 // MSVC permits the use of pure specifier (=0) on function definition,
15545 // defined at class scope, warn about this non-standard construct.
15546 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
15547 Diag(FD->getLocation(), diag::ext_pure_function_definition);
15548
15549 if (!FD->isInvalidDecl()) {
15550 // Don't diagnose unused parameters of defaulted, deleted or naked
15551 // functions.
15552 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
15553 !FD->hasAttr<NakedAttr>())
15554 DiagnoseUnusedParameters(FD->parameters());
15555 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
15556 FD->getReturnType(), FD);
15557
15558 // If this is a structor, we need a vtable.
15559 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
15560 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
15561 else if (CXXDestructorDecl *Destructor =
15562 dyn_cast<CXXDestructorDecl>(FD))
15563 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
15564
15565 // Try to apply the named return value optimization. We have to check
15566 // if we can do this here because lambdas keep return statements around
15567 // to deduce an implicit return type.
15568 if (FD->getReturnType()->isRecordType() &&
15569 (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
15570 computeNRVO(Body, FSI);
15571 }
15572
15573 // GNU warning -Wmissing-prototypes:
15574 // Warn if a global function is defined without a previous
15575 // prototype declaration. This warning is issued even if the
15576 // definition itself provides a prototype. The aim is to detect
15577 // global functions that fail to be declared in header files.
15578 const FunctionDecl *PossiblePrototype = nullptr;
15579 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
15580 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
15581
15582 if (PossiblePrototype) {
15583 // We found a declaration that is not a prototype,
15584 // but that could be a zero-parameter prototype
15585 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
15586 TypeLoc TL = TI->getTypeLoc();
15587 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
15588 Diag(PossiblePrototype->getLocation(),
15589 diag::note_declaration_not_a_prototype)
15590 << (FD->getNumParams() != 0)
15591 << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
15592 FTL.getRParenLoc(), "void")
15593 : FixItHint{});
15594 }
15595 } else {
15596 // Returns true if the token beginning at this Loc is `const`.
15597 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
15598 const LangOptions &LangOpts) {
15599 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
15600 if (LocInfo.first.isInvalid())
15601 return false;
15602
15603 bool Invalid = false;
15604 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
15605 if (Invalid)
15606 return false;
15607
15608 if (LocInfo.second > Buffer.size())
15609 return false;
15610
15611 const char *LexStart = Buffer.data() + LocInfo.second;
15612 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
15613
15614 return StartTok.consume_front("const") &&
15615 (StartTok.empty() || isWhitespace(StartTok[0]) ||
15616 StartTok.startswith("/*") || StartTok.startswith("//"));
15617 };
15618
15619 auto findBeginLoc = [&]() {
15620 // If the return type has `const` qualifier, we want to insert
15621 // `static` before `const` (and not before the typename).
15622 if ((FD->getReturnType()->isAnyPointerType() &&
15623 FD->getReturnType()->getPointeeType().isConstQualified()) ||
15624 FD->getReturnType().isConstQualified()) {
15625 // But only do this if we can determine where the `const` is.
15626
15627 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
15628 getLangOpts()))
15629
15630 return FD->getBeginLoc();
15631 }
15632 return FD->getTypeSpecStartLoc();
15633 };
15634 Diag(FD->getTypeSpecStartLoc(),
15635 diag::note_static_for_internal_linkage)
15636 << /* function */ 1
15637 << (FD->getStorageClass() == SC_None
15638 ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
15639 : FixItHint{});
15640 }
15641 }
15642
15643 // We might not have found a prototype because we didn't wish to warn on
15644 // the lack of a missing prototype. Try again without the checks for
15645 // whether we want to warn on the missing prototype.
15646 if (!PossiblePrototype)
15647 (void)FindPossiblePrototype(FD, PossiblePrototype);
15648
15649 // If the function being defined does not have a prototype, then we may
15650 // need to diagnose it as changing behavior in C2x because we now know
15651 // whether the function accepts arguments or not. This only handles the
15652 // case where the definition has no prototype but does have parameters
15653 // and either there is no previous potential prototype, or the previous
15654 // potential prototype also has no actual prototype. This handles cases
15655 // like:
15656 // void f(); void f(a) int a; {}
15657 // void g(a) int a; {}
15658 // See MergeFunctionDecl() for other cases of the behavior change
15659 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
15660 // type without a prototype.
15661 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
15662 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
15663 !PossiblePrototype->isImplicit()))) {
15664 // The function definition has parameters, so this will change behavior
15665 // in C2x. If there is a possible prototype, it comes before the
15666 // function definition.
15667 // FIXME: The declaration may have already been diagnosed as being
15668 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
15669 // there's no way to test for the "changes behavior" condition in
15670 // SemaType.cpp when forming the declaration's function type. So, we do
15671 // this awkward dance instead.
15672 //
15673 // If we have a possible prototype and it declares a function with a
15674 // prototype, we don't want to diagnose it; if we have a possible
15675 // prototype and it has no prototype, it may have already been
15676 // diagnosed in SemaType.cpp as deprecated depending on whether
15677 // -Wstrict-prototypes is enabled. If we already warned about it being
15678 // deprecated, add a note that it also changes behavior. If we didn't
15679 // warn about it being deprecated (because the diagnostic is not
15680 // enabled), warn now that it is deprecated and changes behavior.
15681
15682 // This K&R C function definition definitely changes behavior in C2x,
15683 // so diagnose it.
15684 Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
15685 << /*definition*/ 1 << /* not supported in C2x */ 0;
15686
15687 // If we have a possible prototype for the function which is a user-
15688 // visible declaration, we already tested that it has no prototype.
15689 // This will change behavior in C2x. This gets a warning rather than a
15690 // note because it's the same behavior-changing problem as with the
15691 // definition.
15692 if (PossiblePrototype)
15693 Diag(PossiblePrototype->getLocation(),
15694 diag::warn_non_prototype_changes_behavior)
15695 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
15696 << /*definition*/ 1;
15697 }
15698
15699 // Warn on CPUDispatch with an actual body.
15700 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
15701 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
15702 if (!CmpndBody->body_empty())
15703 Diag(CmpndBody->body_front()->getBeginLoc(),
15704 diag::warn_dispatch_body_ignored);
15705
15706 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
15707 const CXXMethodDecl *KeyFunction;
15708 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
15709 MD->isVirtual() &&
15710 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
15711 MD == KeyFunction->getCanonicalDecl()) {
15712 // Update the key-function state if necessary for this ABI.
15713 if (FD->isInlined() &&
15714 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
15715 Context.setNonKeyFunction(MD);
15716
15717 // If the newly-chosen key function is already defined, then we
15718 // need to mark the vtable as used retroactively.
15719 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
15720 const FunctionDecl *Definition;
15721 if (KeyFunction && KeyFunction->isDefined(Definition))
15722 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
15723 } else {
15724 // We just defined they key function; mark the vtable as used.
15725 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
15726 }
15727 }
15728 }
15729
15730 assert((static_cast <bool> ((FD == getCurFunctionDecl() || getCurLambda
()->CallOperator == FD) && "Function parsing confused"
) ? void (0) : __assert_fail ("(FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && \"Function parsing confused\""
, "clang/lib/Sema/SemaDecl.cpp", 15732, __extension__ __PRETTY_FUNCTION__
))
15731 (FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&(static_cast <bool> ((FD == getCurFunctionDecl() || getCurLambda
()->CallOperator == FD) && "Function parsing confused"
) ? void (0) : __assert_fail ("(FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && \"Function parsing confused\""
, "clang/lib/Sema/SemaDecl.cpp", 15732, __extension__ __PRETTY_FUNCTION__
))
15732 "Function parsing confused")(static_cast <bool> ((FD == getCurFunctionDecl() || getCurLambda
()->CallOperator == FD) && "Function parsing confused"
) ? void (0) : __assert_fail ("(FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && \"Function parsing confused\""
, "clang/lib/Sema/SemaDecl.cpp", 15732, __extension__ __PRETTY_FUNCTION__
))
;
15733 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
15734 assert(MD == getCurMethodDecl() && "Method parsing confused")(static_cast <bool> (MD == getCurMethodDecl() &&
"Method parsing confused") ? void (0) : __assert_fail ("MD == getCurMethodDecl() && \"Method parsing confused\""
, "clang/lib/Sema/SemaDecl.cpp", 15734, __extension__ __PRETTY_FUNCTION__
))
;
15735 MD->setBody(Body);
15736 if (!MD->isInvalidDecl()) {
15737 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
15738 MD->getReturnType(), MD);
15739
15740 if (Body)
15741 computeNRVO(Body, FSI);
15742 }
15743 if (FSI->ObjCShouldCallSuper) {
15744 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
15745 << MD->getSelector().getAsString();
15746 FSI->ObjCShouldCallSuper = false;
15747 }
15748 if (FSI->ObjCWarnForNoDesignatedInitChain) {
15749 const ObjCMethodDecl *InitMethod = nullptr;
15750 bool isDesignated =
15751 MD->isDesignatedInitializerForTheInterface(&InitMethod);
15752 assert(isDesignated && InitMethod)(static_cast <bool> (isDesignated && InitMethod
) ? void (0) : __assert_fail ("isDesignated && InitMethod"
, "clang/lib/Sema/SemaDecl.cpp", 15752, __extension__ __PRETTY_FUNCTION__
))
;
15753 (void)isDesignated;
15754
15755 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
15756 auto IFace = MD->getClassInterface();
15757 if (!IFace)
15758 return false;
15759 auto SuperD = IFace->getSuperClass();
15760 if (!SuperD)
15761 return false;
15762 return SuperD->getIdentifier() ==
15763 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
15764 };
15765 // Don't issue this warning for unavailable inits or direct subclasses
15766 // of NSObject.
15767 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
15768 Diag(MD->getLocation(),
15769 diag::warn_objc_designated_init_missing_super_call);
15770 Diag(InitMethod->getLocation(),
15771 diag::note_objc_designated_init_marked_here);
15772 }
15773 FSI->ObjCWarnForNoDesignatedInitChain = false;
15774 }
15775 if (FSI->ObjCWarnForNoInitDelegation) {
15776 // Don't issue this warning for unavaialable inits.
15777 if (!MD->isUnavailable())
15778 Diag(MD->getLocation(),
15779 diag::warn_objc_secondary_init_missing_init_call);
15780 FSI->ObjCWarnForNoInitDelegation = false;
15781 }
15782
15783 diagnoseImplicitlyRetainedSelf(*this);
15784 } else {
15785 // Parsing the function declaration failed in some way. Pop the fake scope
15786 // we pushed on.
15787 PopFunctionScopeInfo(ActivePolicy, dcl);
15788 return nullptr;
15789 }
15790
15791 if (Body && FSI->HasPotentialAvailabilityViolations)
15792 DiagnoseUnguardedAvailabilityViolations(dcl);
15793
15794 assert(!FSI->ObjCShouldCallSuper &&(static_cast <bool> (!FSI->ObjCShouldCallSuper &&
"This should only be set for ObjC methods, which should have been "
"handled in the block above.") ? void (0) : __assert_fail ("!FSI->ObjCShouldCallSuper && \"This should only be set for ObjC methods, which should have been \" \"handled in the block above.\""
, "clang/lib/Sema/SemaDecl.cpp", 15796, __extension__ __PRETTY_FUNCTION__
))
15795 "This should only be set for ObjC methods, which should have been "(static_cast <bool> (!FSI->ObjCShouldCallSuper &&
"This should only be set for ObjC methods, which should have been "
"handled in the block above.") ? void (0) : __assert_fail ("!FSI->ObjCShouldCallSuper && \"This should only be set for ObjC methods, which should have been \" \"handled in the block above.\""
, "clang/lib/Sema/SemaDecl.cpp", 15796, __extension__ __PRETTY_FUNCTION__
))
15796 "handled in the block above.")(static_cast <bool> (!FSI->ObjCShouldCallSuper &&
"This should only be set for ObjC methods, which should have been "
"handled in the block above.") ? void (0) : __assert_fail ("!FSI->ObjCShouldCallSuper && \"This should only be set for ObjC methods, which should have been \" \"handled in the block above.\""
, "clang/lib/Sema/SemaDecl.cpp", 15796, __extension__ __PRETTY_FUNCTION__
))
;
15797
15798 // Verify and clean out per-function state.
15799 if (Body && (!FD || !FD->isDefaulted())) {
15800 // C++ constructors that have function-try-blocks can't have return
15801 // statements in the handlers of that block. (C++ [except.handle]p14)
15802 // Verify this.
15803 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
15804 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
15805
15806 // Verify that gotos and switch cases don't jump into scopes illegally.
15807 if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
15808 DiagnoseInvalidJumps(Body);
15809
15810 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
15811 if (!Destructor->getParent()->isDependentType())
15812 CheckDestructor(Destructor);
15813
15814 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
15815 Destructor->getParent());
15816 }
15817
15818 // If any errors have occurred, clear out any temporaries that may have
15819 // been leftover. This ensures that these temporaries won't be picked up
15820 // for deletion in some later function.
15821 if (hasUncompilableErrorOccurred() ||
15822 getDiagnostics().getSuppressAllDiagnostics()) {
15823 DiscardCleanupsInEvaluationContext();
15824 }
15825 if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {
15826 // Since the body is valid, issue any analysis-based warnings that are
15827 // enabled.
15828 ActivePolicy = &WP;
15829 }
15830
15831 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
15832 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
15833 FD->setInvalidDecl();
15834
15835 if (FD && FD->hasAttr<NakedAttr>()) {
15836 for (const Stmt *S : Body->children()) {
15837 // Allow local register variables without initializer as they don't
15838 // require prologue.
15839 bool RegisterVariables = false;
15840 if (auto *DS = dyn_cast<DeclStmt>(S)) {
15841 for (const auto *Decl : DS->decls()) {
15842 if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
15843 RegisterVariables =
15844 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
15845 if (!RegisterVariables)
15846 break;
15847 }
15848 }
15849 }
15850 if (RegisterVariables)
15851 continue;
15852 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
15853 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
15854 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
15855 FD->setInvalidDecl();
15856 break;
15857 }
15858 }
15859 }
15860
15861 assert(ExprCleanupObjects.size() ==(static_cast <bool> (ExprCleanupObjects.size() == ExprEvalContexts
.back().NumCleanupObjects && "Leftover temporaries in function"
) ? void (0) : __assert_fail ("ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && \"Leftover temporaries in function\""
, "clang/lib/Sema/SemaDecl.cpp", 15863, __extension__ __PRETTY_FUNCTION__
))
15862 ExprEvalContexts.back().NumCleanupObjects &&(static_cast <bool> (ExprCleanupObjects.size() == ExprEvalContexts
.back().NumCleanupObjects && "Leftover temporaries in function"
) ? void (0) : __assert_fail ("ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && \"Leftover temporaries in function\""
, "clang/lib/Sema/SemaDecl.cpp", 15863, __extension__ __PRETTY_FUNCTION__
))
15863 "Leftover temporaries in function")(static_cast <bool> (ExprCleanupObjects.size() == ExprEvalContexts
.back().NumCleanupObjects && "Leftover temporaries in function"
) ? void (0) : __assert_fail ("ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && \"Leftover temporaries in function\""
, "clang/lib/Sema/SemaDecl.cpp", 15863, __extension__ __PRETTY_FUNCTION__
))
;
15864 assert(!Cleanup.exprNeedsCleanups() &&(static_cast <bool> (!Cleanup.exprNeedsCleanups() &&
"Unaccounted cleanups in function") ? void (0) : __assert_fail
("!Cleanup.exprNeedsCleanups() && \"Unaccounted cleanups in function\""
, "clang/lib/Sema/SemaDecl.cpp", 15865, __extension__ __PRETTY_FUNCTION__
))
15865 "Unaccounted cleanups in function")(static_cast <bool> (!Cleanup.exprNeedsCleanups() &&
"Unaccounted cleanups in function") ? void (0) : __assert_fail
("!Cleanup.exprNeedsCleanups() && \"Unaccounted cleanups in function\""
, "clang/lib/Sema/SemaDecl.cpp", 15865, __extension__ __PRETTY_FUNCTION__
))
;
15866 assert(MaybeODRUseExprs.empty() &&(static_cast <bool> (MaybeODRUseExprs.empty() &&
"Leftover expressions for odr-use checking") ? void (0) : __assert_fail
("MaybeODRUseExprs.empty() && \"Leftover expressions for odr-use checking\""
, "clang/lib/Sema/SemaDecl.cpp", 15867, __extension__ __PRETTY_FUNCTION__
))
15867 "Leftover expressions for odr-use checking")(static_cast <bool> (MaybeODRUseExprs.empty() &&
"Leftover expressions for odr-use checking") ? void (0) : __assert_fail
("MaybeODRUseExprs.empty() && \"Leftover expressions for odr-use checking\""
, "clang/lib/Sema/SemaDecl.cpp", 15867, __extension__ __PRETTY_FUNCTION__
))
;
15868 }
15869 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
15870 // the declaration context below. Otherwise, we're unable to transform
15871 // 'this' expressions when transforming immediate context functions.
15872
15873 if (!IsInstantiation)
15874 PopDeclContext();
15875
15876 PopFunctionScopeInfo(ActivePolicy, dcl);
15877 // If any errors have occurred, clear out any temporaries that may have
15878 // been leftover. This ensures that these temporaries won't be picked up for
15879 // deletion in some later function.
15880 if (hasUncompilableErrorOccurred()) {
15881 DiscardCleanupsInEvaluationContext();
15882 }
15883
15884 if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsDevice ||
15885 !LangOpts.OMPTargetTriples.empty())) ||
15886 LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
15887 auto ES = getEmissionStatus(FD);
15888 if (ES == Sema::FunctionEmissionStatus::Emitted ||
15889 ES == Sema::FunctionEmissionStatus::Unknown)
15890 DeclsToCheckForDeferredDiags.insert(FD);
15891 }
15892
15893 if (FD && !FD->isDeleted())
15894 checkTypeSupport(FD->getType(), FD->getLocation(), FD);
15895
15896 return dcl;
15897}
15898
15899/// When we finish delayed parsing of an attribute, we must attach it to the
15900/// relevant Decl.
15901void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
15902 ParsedAttributes &Attrs) {
15903 // Always attach attributes to the underlying decl.
15904 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
15905 D = TD->getTemplatedDecl();
15906 ProcessDeclAttributeList(S, D, Attrs);
15907
15908 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
15909 if (Method->isStatic())
15910 checkThisInStaticMemberFunctionAttributes(Method);
15911}
15912
15913/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
15914/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
15915NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
15916 IdentifierInfo &II, Scope *S) {
15917 // It is not valid to implicitly define a function in C2x.
15918 assert(LangOpts.implicitFunctionsAllowed() &&(static_cast <bool> (LangOpts.implicitFunctionsAllowed(
) && "Implicit function declarations aren't allowed in this language mode"
) ? void (0) : __assert_fail ("LangOpts.implicitFunctionsAllowed() && \"Implicit function declarations aren't allowed in this language mode\""
, "clang/lib/Sema/SemaDecl.cpp", 15919, __extension__ __PRETTY_FUNCTION__
))
15919 "Implicit function declarations aren't allowed in this language mode")(static_cast <bool> (LangOpts.implicitFunctionsAllowed(
) && "Implicit function declarations aren't allowed in this language mode"
) ? void (0) : __assert_fail ("LangOpts.implicitFunctionsAllowed() && \"Implicit function declarations aren't allowed in this language mode\""
, "clang/lib/Sema/SemaDecl.cpp", 15919, __extension__ __PRETTY_FUNCTION__
))
;
15920
15921 // Find the scope in which the identifier is injected and the corresponding
15922 // DeclContext.
15923 // FIXME: C89 does not say what happens if there is no enclosing block scope.
15924 // In that case, we inject the declaration into the translation unit scope
15925 // instead.
15926 Scope *BlockScope = S;
15927 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
15928 BlockScope = BlockScope->getParent();
15929
15930 Scope *ContextScope = BlockScope;
15931 while (!ContextScope->getEntity())
15932 ContextScope = ContextScope->getParent();
15933 ContextRAII SavedContext(*this, ContextScope->getEntity());
15934
15935 // Before we produce a declaration for an implicitly defined
15936 // function, see whether there was a locally-scoped declaration of
15937 // this name as a function or variable. If so, use that
15938 // (non-visible) declaration, and complain about it.
15939 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
15940 if (ExternCPrev) {
15941 // We still need to inject the function into the enclosing block scope so
15942 // that later (non-call) uses can see it.
15943 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
15944
15945 // C89 footnote 38:
15946 // If in fact it is not defined as having type "function returning int",
15947 // the behavior is undefined.
15948 if (!isa<FunctionDecl>(ExternCPrev) ||
15949 !Context.typesAreCompatible(
15950 cast<FunctionDecl>(ExternCPrev)->getType(),
15951 Context.getFunctionNoProtoType(Context.IntTy))) {
15952 Diag(Loc, diag::ext_use_out_of_scope_declaration)
15953 << ExternCPrev << !getLangOpts().C99;
15954 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
15955 return ExternCPrev;
15956 }
15957 }
15958
15959 // Extension in C99 (defaults to error). Legal in C89, but warn about it.
15960 unsigned diag_id;
15961 if (II.getName().startswith("__builtin_"))
15962 diag_id = diag::warn_builtin_unknown;
15963 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
15964 else if (getLangOpts().C99)
15965 diag_id = diag::ext_implicit_function_decl_c99;
15966 else
15967 diag_id = diag::warn_implicit_function_decl;
15968
15969 TypoCorrection Corrected;
15970 // Because typo correction is expensive, only do it if the implicit
15971 // function declaration is going to be treated as an error.
15972 //
15973 // Perform the correction before issuing the main diagnostic, as some
15974 // consumers use typo-correction callbacks to enhance the main diagnostic.
15975 if (S && !ExternCPrev &&
15976 (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {
15977 DeclFilterCCC<FunctionDecl> CCC{};
15978 Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
15979 S, nullptr, CCC, CTK_NonError);
15980 }
15981
15982 Diag(Loc, diag_id) << &II;
15983 if (Corrected) {
15984 // If the correction is going to suggest an implicitly defined function,
15985 // skip the correction as not being a particularly good idea.
15986 bool Diagnose = true;
15987 if (const auto *D = Corrected.getCorrectionDecl())
15988 Diagnose = !D->isImplicit();
15989 if (Diagnose)
15990 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
15991 /*ErrorRecovery*/ false);
15992 }
15993
15994 // If we found a prior declaration of this function, don't bother building
15995 // another one. We've already pushed that one into scope, so there's nothing
15996 // more to do.
15997 if (ExternCPrev)
15998 return ExternCPrev;
15999
16000 // Set a Declarator for the implicit definition: int foo();
16001 const char *Dummy;
16002 AttributeFactory attrFactory;
16003 DeclSpec DS(attrFactory);
16004 unsigned DiagID;
16005 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
16006 Context.getPrintingPolicy());
16007 (void)Error; // Silence warning.
16008 assert(!Error && "Error setting up implicit decl!")(static_cast <bool> (!Error && "Error setting up implicit decl!"
) ? void (0) : __assert_fail ("!Error && \"Error setting up implicit decl!\""
, "clang/lib/Sema/SemaDecl.cpp", 16008, __extension__ __PRETTY_FUNCTION__
))
;
16009 SourceLocation NoLoc;
16010 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::Block);
16011 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
16012 /*IsAmbiguous=*/false,
16013 /*LParenLoc=*/NoLoc,
16014 /*Params=*/nullptr,
16015 /*NumParams=*/0,
16016 /*EllipsisLoc=*/NoLoc,
16017 /*RParenLoc=*/NoLoc,
16018 /*RefQualifierIsLvalueRef=*/true,
16019 /*RefQualifierLoc=*/NoLoc,
16020 /*MutableLoc=*/NoLoc, EST_None,
16021 /*ESpecRange=*/SourceRange(),
16022 /*Exceptions=*/nullptr,
16023 /*ExceptionRanges=*/nullptr,
16024 /*NumExceptions=*/0,
16025 /*NoexceptExpr=*/nullptr,
16026 /*ExceptionSpecTokens=*/nullptr,
16027 /*DeclsInPrototype=*/std::nullopt,
16028 Loc, Loc, D),
16029 std::move(DS.getAttributes()), SourceLocation());
16030 D.SetIdentifier(&II, Loc);
16031
16032 // Insert this function into the enclosing block scope.
16033 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
16034 FD->setImplicit();
16035
16036 AddKnownFunctionAttributes(FD);
16037
16038 return FD;
16039}
16040
16041/// If this function is a C++ replaceable global allocation function
16042/// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
16043/// adds any function attributes that we know a priori based on the standard.
16044///
16045/// We need to check for duplicate attributes both here and where user-written
16046/// attributes are applied to declarations.
16047void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
16048 FunctionDecl *FD) {
16049 if (FD->isInvalidDecl())
16050 return;
16051
16052 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
16053 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
16054 return;
16055
16056 std::optional<unsigned> AlignmentParam;
16057 bool IsNothrow = false;
16058 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
16059 return;
16060
16061 // C++2a [basic.stc.dynamic.allocation]p4:
16062 // An allocation function that has a non-throwing exception specification
16063 // indicates failure by returning a null pointer value. Any other allocation
16064 // function never returns a null pointer value and indicates failure only by
16065 // throwing an exception [...]
16066 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
16067 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
16068
16069 // C++2a [basic.stc.dynamic.allocation]p2:
16070 // An allocation function attempts to allocate the requested amount of
16071 // storage. [...] If the request succeeds, the value returned by a
16072 // replaceable allocation function is a [...] pointer value p0 different
16073 // from any previously returned value p1 [...]
16074 //
16075 // However, this particular information is being added in codegen,
16076 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
16077
16078 // C++2a [basic.stc.dynamic.allocation]p2:
16079 // An allocation function attempts to allocate the requested amount of
16080 // storage. If it is successful, it returns the address of the start of a
16081 // block of storage whose length in bytes is at least as large as the
16082 // requested size.
16083 if (!FD->hasAttr<AllocSizeAttr>()) {
16084 FD->addAttr(AllocSizeAttr::CreateImplicit(
16085 Context, /*ElemSizeParam=*/ParamIdx(1, FD),
16086 /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
16087 }
16088
16089 // C++2a [basic.stc.dynamic.allocation]p3:
16090 // For an allocation function [...], the pointer returned on a successful
16091 // call shall represent the address of storage that is aligned as follows:
16092 // (3.1) If the allocation function takes an argument of type
16093 // std​::​align_­val_­t, the storage will have the alignment
16094 // specified by the value of this argument.
16095 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
16096 FD->addAttr(AllocAlignAttr::CreateImplicit(
16097 Context, ParamIdx(*AlignmentParam, FD), FD->getLocation()));
16098 }
16099
16100 // FIXME:
16101 // C++2a [basic.stc.dynamic.allocation]p3:
16102 // For an allocation function [...], the pointer returned on a successful
16103 // call shall represent the address of storage that is aligned as follows:
16104 // (3.2) Otherwise, if the allocation function is named operator new[],
16105 // the storage is aligned for any object that does not have
16106 // new-extended alignment ([basic.align]) and is no larger than the
16107 // requested size.
16108 // (3.3) Otherwise, the storage is aligned for any object that does not
16109 // have new-extended alignment and is of the requested size.
16110}
16111
16112/// Adds any function attributes that we know a priori based on
16113/// the declaration of this function.
16114///
16115/// These attributes can apply both to implicitly-declared builtins
16116/// (like __builtin___printf_chk) or to library-declared functions
16117/// like NSLog or printf.
16118///
16119/// We need to check for duplicate attributes both here and where user-written
16120/// attributes are applied to declarations.
16121void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
16122 if (FD->isInvalidDecl())
16123 return;
16124
16125 // If this is a built-in function, map its builtin attributes to
16126 // actual attributes.
16127 if (unsigned BuiltinID = FD->getBuiltinID()) {
16128 // Handle printf-formatting attributes.
16129 unsigned FormatIdx;
16130 bool HasVAListArg;
16131 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
16132 if (!FD->hasAttr<FormatAttr>()) {
16133 const char *fmt = "printf";
16134 unsigned int NumParams = FD->getNumParams();
16135 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
16136 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
16137 fmt = "NSString";
16138 FD->addAttr(FormatAttr::CreateImplicit(Context,
16139 &Context.Idents.get(fmt),
16140 FormatIdx+1,
16141 HasVAListArg ? 0 : FormatIdx+2,
16142 FD->getLocation()));
16143 }
16144 }
16145 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
16146 HasVAListArg)) {
16147 if (!FD->hasAttr<FormatAttr>())
16148 FD->addAttr(FormatAttr::CreateImplicit(Context,
16149 &Context.Idents.get("scanf"),
16150 FormatIdx+1,
16151 HasVAListArg ? 0 : FormatIdx+2,
16152 FD->getLocation()));
16153 }
16154
16155 // Handle automatically recognized callbacks.
16156 SmallVector<int, 4> Encoding;
16157 if (!FD->hasAttr<CallbackAttr>() &&
16158 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
16159 FD->addAttr(CallbackAttr::CreateImplicit(
16160 Context, Encoding.data(), Encoding.size(), FD->getLocation()));
16161
16162 // Mark const if we don't care about errno and/or floating point exceptions
16163 // that are the only thing preventing the function from being const. This
16164 // allows IRgen to use LLVM intrinsics for such functions.
16165 bool NoExceptions =
16166 getLangOpts().getDefaultExceptionMode() == LangOptions::FPE_Ignore;
16167 bool ConstWithoutErrnoAndExceptions =
16168 Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(BuiltinID);
16169 bool ConstWithoutExceptions =
16170 Context.BuiltinInfo.isConstWithoutExceptions(BuiltinID);
16171 if (!FD->hasAttr<ConstAttr>() &&
16172 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
16173 (!ConstWithoutErrnoAndExceptions ||
16174 (!getLangOpts().MathErrno && NoExceptions)) &&
16175 (!ConstWithoutExceptions || NoExceptions))
16176 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16177
16178 // We make "fma" on GNU or Windows const because we know it does not set
16179 // errno in those environments even though it could set errno based on the
16180 // C standard.
16181 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
16182 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
16183 !FD->hasAttr<ConstAttr>()) {
16184 switch (BuiltinID) {
16185 case Builtin::BI__builtin_fma:
16186 case Builtin::BI__builtin_fmaf:
16187 case Builtin::BI__builtin_fmal:
16188 case Builtin::BIfma:
16189 case Builtin::BIfmaf:
16190 case Builtin::BIfmal:
16191 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16192 break;
16193 default:
16194 break;
16195 }
16196 }
16197
16198 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
16199 !FD->hasAttr<ReturnsTwiceAttr>())
16200 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
16201 FD->getLocation()));
16202 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
16203 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
16204 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
16205 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
16206 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
16207 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16208 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
16209 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
16210 // Add the appropriate attribute, depending on the CUDA compilation mode
16211 // and which target the builtin belongs to. For example, during host
16212 // compilation, aux builtins are __device__, while the rest are __host__.
16213 if (getLangOpts().CUDAIsDevice !=
16214 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
16215 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
16216 else
16217 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
16218 }
16219
16220 // Add known guaranteed alignment for allocation functions.
16221 switch (BuiltinID) {
16222 case Builtin::BImemalign:
16223 case Builtin::BIaligned_alloc:
16224 if (!FD->hasAttr<AllocAlignAttr>())
16225 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
16226 FD->getLocation()));
16227 break;
16228 default:
16229 break;
16230 }
16231
16232 // Add allocsize attribute for allocation functions.
16233 switch (BuiltinID) {
16234 case Builtin::BIcalloc:
16235 FD->addAttr(AllocSizeAttr::CreateImplicit(
16236 Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
16237 break;
16238 case Builtin::BImemalign:
16239 case Builtin::BIaligned_alloc:
16240 case Builtin::BIrealloc:
16241 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
16242 ParamIdx(), FD->getLocation()));
16243 break;
16244 case Builtin::BImalloc:
16245 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
16246 ParamIdx(), FD->getLocation()));
16247 break;
16248 default:
16249 break;
16250 }
16251
16252 // Add lifetime attribute to std::move, std::fowrard et al.
16253 switch (BuiltinID) {
16254 case Builtin::BIaddressof:
16255 case Builtin::BI__addressof:
16256 case Builtin::BI__builtin_addressof:
16257 case Builtin::BIas_const:
16258 case Builtin::BIforward:
16259 case Builtin::BIforward_like:
16260 case Builtin::BImove:
16261 case Builtin::BImove_if_noexcept:
16262 if (ParmVarDecl *P = FD->getParamDecl(0u);
16263 !P->hasAttr<LifetimeBoundAttr>())
16264 P->addAttr(
16265 LifetimeBoundAttr::CreateImplicit(Context, FD->getLocation()));
16266 break;
16267 default:
16268 break;
16269 }
16270 }
16271
16272 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
16273
16274 // If C++ exceptions are enabled but we are told extern "C" functions cannot
16275 // throw, add an implicit nothrow attribute to any extern "C" function we come
16276 // across.
16277 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
16278 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
16279 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
16280 if (!FPT || FPT->getExceptionSpecType() == EST_None)
16281 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
16282 }
16283
16284 IdentifierInfo *Name = FD->getIdentifier();
16285 if (!Name)
16286 return;
16287 if ((!getLangOpts().CPlusPlus &&
16288 FD->getDeclContext()->isTranslationUnit()) ||
16289 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
16290 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
16291 LinkageSpecDecl::lang_c)) {
16292 // Okay: this could be a libc/libm/Objective-C function we know
16293 // about.
16294 } else
16295 return;
16296
16297 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
16298 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
16299 // target-specific builtins, perhaps?
16300 if (!FD->hasAttr<FormatAttr>())
16301 FD->addAttr(FormatAttr::CreateImplicit(Context,
16302 &Context.Idents.get("printf"), 2,
16303 Name->isStr("vasprintf") ? 0 : 3,
16304 FD->getLocation()));
16305 }
16306
16307 if (Name->isStr("__CFStringMakeConstantString")) {
16308 // We already have a __builtin___CFStringMakeConstantString,
16309 // but builds that use -fno-constant-cfstrings don't go through that.
16310 if (!FD->hasAttr<FormatArgAttr>())
16311 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
16312 FD->getLocation()));
16313 }
16314}
16315
16316TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
16317 TypeSourceInfo *TInfo) {
16318 assert(D.getIdentifier() && "Wrong callback for declspec without declarator")(static_cast <bool> (D.getIdentifier() && "Wrong callback for declspec without declarator"
) ? void (0) : __assert_fail ("D.getIdentifier() && \"Wrong callback for declspec without declarator\""
, "clang/lib/Sema/SemaDecl.cpp", 16318, __extension__ __PRETTY_FUNCTION__
))
;
16319 assert(!T.isNull() && "GetTypeForDeclarator() returned null type")(static_cast <bool> (!T.isNull() && "GetTypeForDeclarator() returned null type"
) ? void (0) : __assert_fail ("!T.isNull() && \"GetTypeForDeclarator() returned null type\""
, "clang/lib/Sema/SemaDecl.cpp", 16319, __extension__ __PRETTY_FUNCTION__
))
;
16320
16321 if (!TInfo) {
16322 assert(D.isInvalidType() && "no declarator info for valid type")(static_cast <bool> (D.isInvalidType() && "no declarator info for valid type"
) ? void (0) : __assert_fail ("D.isInvalidType() && \"no declarator info for valid type\""
, "clang/lib/Sema/SemaDecl.cpp", 16322, __extension__ __PRETTY_FUNCTION__
))
;
16323 TInfo = Context.getTrivialTypeSourceInfo(T);
16324 }
16325
16326 // Scope manipulation handled by caller.
16327 TypedefDecl *NewTD =
16328 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
16329 D.getIdentifierLoc(), D.getIdentifier(), TInfo);
16330
16331 // Bail out immediately if we have an invalid declaration.
16332 if (D.isInvalidType()) {
16333 NewTD->setInvalidDecl();
16334 return NewTD;
16335 }
16336
16337 if (D.getDeclSpec().isModulePrivateSpecified()) {
16338 if (CurContext->isFunctionOrMethod())
16339 Diag(NewTD->getLocation(), diag::err_module_private_local)
16340 << 2 << NewTD
16341 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
16342 << FixItHint::CreateRemoval(
16343 D.getDeclSpec().getModulePrivateSpecLoc());
16344 else
16345 NewTD->setModulePrivate();
16346 }
16347
16348 // C++ [dcl.typedef]p8:
16349 // If the typedef declaration defines an unnamed class (or
16350 // enum), the first typedef-name declared by the declaration
16351 // to be that class type (or enum type) is used to denote the
16352 // class type (or enum type) for linkage purposes only.
16353 // We need to check whether the type was declared in the declaration.
16354 switch (D.getDeclSpec().getTypeSpecType()) {
16355 case TST_enum:
16356 case TST_struct:
16357 case TST_interface:
16358 case TST_union:
16359 case TST_class: {
16360 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
16361 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
16362 break;
16363 }
16364
16365 default:
16366 break;
16367 }
16368
16369 return NewTD;
16370}
16371
16372/// Check that this is a valid underlying type for an enum declaration.
16373bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
16374 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
16375 QualType T = TI->getType();
16376
16377 if (T->isDependentType())
16378 return false;
16379
16380 // This doesn't use 'isIntegralType' despite the error message mentioning
16381 // integral type because isIntegralType would also allow enum types in C.
16382 if (const BuiltinType *BT = T->getAs<BuiltinType>())
16383 if (BT->isInteger())
16384 return false;
16385
16386 if (T->isBitIntType())
16387 return false;
16388
16389 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
16390}
16391
16392/// Check whether this is a valid redeclaration of a previous enumeration.
16393/// \return true if the redeclaration was invalid.
16394bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
16395 QualType EnumUnderlyingTy, bool IsFixed,
16396 const EnumDecl *Prev) {
16397 if (IsScoped != Prev->isScoped()) {
16398 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
16399 << Prev->isScoped();
16400 Diag(Prev->getLocation(), diag::note_previous_declaration);
16401 return true;
16402 }
16403
16404 if (IsFixed && Prev->isFixed()) {
16405 if (!EnumUnderlyingTy->isDependentType() &&
16406 !Prev->getIntegerType()->isDependentType() &&
16407 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
16408 Prev->getIntegerType())) {
16409 // TODO: Highlight the underlying type of the redeclaration.
16410 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
16411 << EnumUnderlyingTy << Prev->getIntegerType();
16412 Diag(Prev->getLocation(), diag::note_previous_declaration)
16413 << Prev->getIntegerTypeRange();
16414 return true;
16415 }
16416 } else if (IsFixed != Prev->isFixed()) {
16417 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
16418 << Prev->isFixed();
16419 Diag(Prev->getLocation(), diag::note_previous_declaration);
16420 return true;
16421 }
16422
16423 return false;
16424}
16425
16426/// Get diagnostic %select index for tag kind for
16427/// redeclaration diagnostic message.
16428/// WARNING: Indexes apply to particular diagnostics only!
16429///
16430/// \returns diagnostic %select index.
16431static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
16432 switch (Tag) {
16433 case TTK_Struct: return 0;
16434 case TTK_Interface: return 1;
16435 case TTK_Class: return 2;
16436 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!")::llvm::llvm_unreachable_internal("Invalid tag kind for redecl diagnostic!"
, "clang/lib/Sema/SemaDecl.cpp", 16436)
;
16437 }
16438}
16439
16440/// Determine if tag kind is a class-key compatible with
16441/// class for redeclaration (class, struct, or __interface).
16442///
16443/// \returns true iff the tag kind is compatible.
16444static bool isClassCompatTagKind(TagTypeKind Tag)
16445{
16446 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
16447}
16448
16449Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
16450 TagTypeKind TTK) {
16451 if (isa<TypedefDecl>(PrevDecl))
16452 return NTK_Typedef;
16453 else if (isa<TypeAliasDecl>(PrevDecl))
16454 return NTK_TypeAlias;
16455 else if (isa<ClassTemplateDecl>(PrevDecl))
16456 return NTK_Template;
16457 else if (isa<TypeAliasTemplateDecl>(PrevDecl))
16458 return NTK_TypeAliasTemplate;
16459 else if (isa<TemplateTemplateParmDecl>(PrevDecl))
16460 return NTK_TemplateTemplateArgument;
16461 switch (TTK) {
16462 case TTK_Struct:
16463 case TTK_Interface:
16464 case TTK_Class:
16465 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
16466 case TTK_Union:
16467 return NTK_NonUnion;
16468 case TTK_Enum:
16469 return NTK_NonEnum;
16470 }
16471 llvm_unreachable("invalid TTK")::llvm::llvm_unreachable_internal("invalid TTK", "clang/lib/Sema/SemaDecl.cpp"
, 16471)
;
16472}
16473
16474/// Determine whether a tag with a given kind is acceptable
16475/// as a redeclaration of the given tag declaration.
16476///
16477/// \returns true if the new tag kind is acceptable, false otherwise.
16478bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
16479 TagTypeKind NewTag, bool isDefinition,
16480 SourceLocation NewTagLoc,
16481 const IdentifierInfo *Name) {
16482 // C++ [dcl.type.elab]p3:
16483 // The class-key or enum keyword present in the
16484 // elaborated-type-specifier shall agree in kind with the
16485 // declaration to which the name in the elaborated-type-specifier
16486 // refers. This rule also applies to the form of
16487 // elaborated-type-specifier that declares a class-name or
16488 // friend class since it can be construed as referring to the
16489 // definition of the class. Thus, in any
16490 // elaborated-type-specifier, the enum keyword shall be used to
16491 // refer to an enumeration (7.2), the union class-key shall be
16492 // used to refer to a union (clause 9), and either the class or
16493 // struct class-key shall be used to refer to a class (clause 9)
16494 // declared using the class or struct class-key.
16495 TagTypeKind OldTag = Previous->getTagKind();
16496 if (OldTag != NewTag &&
16497 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
16498 return false;
16499
16500 // Tags are compatible, but we might still want to warn on mismatched tags.
16501 // Non-class tags can't be mismatched at this point.
16502 if (!isClassCompatTagKind(NewTag))
16503 return true;
16504
16505 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
16506 // by our warning analysis. We don't want to warn about mismatches with (eg)
16507 // declarations in system headers that are designed to be specialized, but if
16508 // a user asks us to warn, we should warn if their code contains mismatched
16509 // declarations.
16510 auto IsIgnoredLoc = [&](SourceLocation Loc) {
16511 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
16512 Loc);
16513 };
16514 if (IsIgnoredLoc(NewTagLoc))
16515 return true;
16516
16517 auto IsIgnored = [&](const TagDecl *Tag) {
16518 return IsIgnoredLoc(Tag->getLocation());
16519 };
16520 while (IsIgnored(Previous)) {
16521 Previous = Previous->getPreviousDecl();
16522 if (!Previous)
16523 return true;
16524 OldTag = Previous->getTagKind();
16525 }
16526
16527 bool isTemplate = false;
16528 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
16529 isTemplate = Record->getDescribedClassTemplate();
16530
16531 if (inTemplateInstantiation()) {
16532 if (OldTag != NewTag) {
16533 // In a template instantiation, do not offer fix-its for tag mismatches
16534 // since they usually mess up the template instead of fixing the problem.
16535 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
16536 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
16537 << getRedeclDiagFromTagKind(OldTag);
16538 // FIXME: Note previous location?
16539 }
16540 return true;
16541 }
16542
16543 if (isDefinition) {
16544 // On definitions, check all previous tags and issue a fix-it for each
16545 // one that doesn't match the current tag.
16546 if (Previous->getDefinition()) {
16547 // Don't suggest fix-its for redefinitions.
16548 return true;
16549 }
16550
16551 bool previousMismatch = false;
16552 for (const TagDecl *I : Previous->redecls()) {
16553 if (I->getTagKind() != NewTag) {
16554 // Ignore previous declarations for which the warning was disabled.
16555 if (IsIgnored(I))
16556 continue;
16557
16558 if (!previousMismatch) {
16559 previousMismatch = true;
16560 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
16561 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
16562 << getRedeclDiagFromTagKind(I->getTagKind());
16563 }
16564 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
16565 << getRedeclDiagFromTagKind(NewTag)
16566 << FixItHint::CreateReplacement(I->getInnerLocStart(),
16567 TypeWithKeyword::getTagTypeKindName(NewTag));
16568 }
16569 }
16570 return true;
16571 }
16572
16573 // Identify the prevailing tag kind: this is the kind of the definition (if
16574 // there is a non-ignored definition), or otherwise the kind of the prior
16575 // (non-ignored) declaration.
16576 const TagDecl *PrevDef = Previous->getDefinition();
16577 if (PrevDef && IsIgnored(PrevDef))
16578 PrevDef = nullptr;
16579 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
16580 if (Redecl->getTagKind() != NewTag) {
16581 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
16582 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
16583 << getRedeclDiagFromTagKind(OldTag);
16584 Diag(Redecl->getLocation(), diag::note_previous_use);
16585
16586 // If there is a previous definition, suggest a fix-it.
16587 if (PrevDef) {
16588 Diag(NewTagLoc, diag::note_struct_class_suggestion)
16589 << getRedeclDiagFromTagKind(Redecl->getTagKind())
16590 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
16591 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
16592 }
16593 }
16594
16595 return true;
16596}
16597
16598/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
16599/// from an outer enclosing namespace or file scope inside a friend declaration.
16600/// This should provide the commented out code in the following snippet:
16601/// namespace N {
16602/// struct X;
16603/// namespace M {
16604/// struct Y { friend struct /*N::*/ X; };
16605/// }
16606/// }
16607static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
16608 SourceLocation NameLoc) {
16609 // While the decl is in a namespace, do repeated lookup of that name and see
16610 // if we get the same namespace back. If we do not, continue until
16611 // translation unit scope, at which point we have a fully qualified NNS.
16612 SmallVector<IdentifierInfo *, 4> Namespaces;
16613 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
16614 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
16615 // This tag should be declared in a namespace, which can only be enclosed by
16616 // other namespaces. Bail if there's an anonymous namespace in the chain.
16617 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
16618 if (!Namespace || Namespace->isAnonymousNamespace())
16619 return FixItHint();
16620 IdentifierInfo *II = Namespace->getIdentifier();
16621 Namespaces.push_back(II);
16622 NamedDecl *Lookup = SemaRef.LookupSingleName(
16623 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
16624 if (Lookup == Namespace)
16625 break;
16626 }
16627
16628 // Once we have all the namespaces, reverse them to go outermost first, and
16629 // build an NNS.
16630 SmallString<64> Insertion;
16631 llvm::raw_svector_ostream OS(Insertion);
16632 if (DC->isTranslationUnit())
16633 OS << "::";
16634 std::reverse(Namespaces.begin(), Namespaces.end());
16635 for (auto *II : Namespaces)
16636 OS << II->getName() << "::";
16637 return FixItHint::CreateInsertion(NameLoc, Insertion);
16638}
16639
16640/// Determine whether a tag originally declared in context \p OldDC can
16641/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
16642/// found a declaration in \p OldDC as a previous decl, perhaps through a
16643/// using-declaration).
16644static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
16645 DeclContext *NewDC) {
16646 OldDC = OldDC->getRedeclContext();
16647 NewDC = NewDC->getRedeclContext();
16648
16649 if (OldDC->Equals(NewDC))
16650 return true;
16651
16652 // In MSVC mode, we allow a redeclaration if the contexts are related (either
16653 // encloses the other).
16654 if (S.getLangOpts().MSVCCompat &&
16655 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
16656 return true;
16657
16658 return false;
16659}
16660
16661/// This is invoked when we see 'struct foo' or 'struct {'. In the
16662/// former case, Name will be non-null. In the later case, Name will be null.
16663/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
16664/// reference/declaration/definition of a tag.
16665///
16666/// \param IsTypeSpecifier \c true if this is a type-specifier (or
16667/// trailing-type-specifier) other than one in an alias-declaration.
16668///
16669/// \param SkipBody If non-null, will be set to indicate if the caller should
16670/// skip the definition of this tag and treat it as if it were a declaration.
16671DeclResult
16672Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
16673 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
16674 const ParsedAttributesView &Attrs, AccessSpecifier AS,
16675 SourceLocation ModulePrivateLoc,
16676 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
16677 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
16678 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
16679 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
16680 OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
16681 // If this is not a definition, it must have a name.
16682 IdentifierInfo *OrigName = Name;
16683 assert((Name != nullptr || TUK == TUK_Definition) &&(static_cast <bool> ((Name != nullptr || TUK == TUK_Definition
) && "Nameless record must be a definition!") ? void (
0) : __assert_fail ("(Name != nullptr || TUK == TUK_Definition) && \"Nameless record must be a definition!\""
, "clang/lib/Sema/SemaDecl.cpp", 16684, __extension__ __PRETTY_FUNCTION__
))
16684 "Nameless record must be a definition!")(static_cast <bool> ((Name != nullptr || TUK == TUK_Definition
) && "Nameless record must be a definition!") ? void (
0) : __assert_fail ("(Name != nullptr || TUK == TUK_Definition) && \"Nameless record must be a definition!\""
, "clang/lib/Sema/SemaDecl.cpp", 16684, __extension__ __PRETTY_FUNCTION__
))
;
16685 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference)(static_cast <bool> (TemplateParameterLists.size() == 0
|| TUK != TUK_Reference) ? void (0) : __assert_fail ("TemplateParameterLists.size() == 0 || TUK != TUK_Reference"
, "clang/lib/Sema/SemaDecl.cpp", 16685, __extension__ __PRETTY_FUNCTION__
))
;
16686
16687 OwnedDecl = false;
16688 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
16689 bool ScopedEnum = ScopedEnumKWLoc.isValid();
16690
16691 // FIXME: Check member specializations more carefully.
16692 bool isMemberSpecialization = false;
16693 bool Invalid = false;
16694
16695 // We only need to do this matching if we have template parameters
16696 // or a scope specifier, which also conveniently avoids this work
16697 // for non-C++ cases.
16698 if (TemplateParameterLists.size() > 0 ||
16699 (SS.isNotEmpty() && TUK != TUK_Reference)) {
16700 if (TemplateParameterList *TemplateParams =
16701 MatchTemplateParametersToScopeSpecifier(
16702 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
16703 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
16704 if (Kind == TTK_Enum) {
16705 Diag(KWLoc, diag::err_enum_template);
16706 return true;
16707 }
16708
16709 if (TemplateParams->size() > 0) {
16710 // This is a declaration or definition of a class template (which may
16711 // be a member of another template).
16712
16713 if (Invalid)
16714 return true;
16715
16716 OwnedDecl = false;
16717 DeclResult Result = CheckClassTemplate(
16718 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
16719 AS, ModulePrivateLoc,
16720 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
16721 TemplateParameterLists.data(), SkipBody);
16722 return Result.get();
16723 } else {
16724 // The "template<>" header is extraneous.
16725 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16726 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
16727 isMemberSpecialization = true;
16728 }
16729 }
16730
16731 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
16732 CheckTemplateDeclScope(S, TemplateParameterLists.back()))
16733 return true;
16734 }
16735
16736 // Figure out the underlying type if this a enum declaration. We need to do
16737 // this early, because it's needed to detect if this is an incompatible
16738 // redeclaration.
16739 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
16740 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
16741
16742 if (Kind == TTK_Enum) {
16743 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
16744 // No underlying type explicitly specified, or we failed to parse the
16745 // type, default to int.
16746 EnumUnderlying = Context.IntTy.getTypePtr();
16747 } else if (UnderlyingType.get()) {
16748 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
16749 // integral type; any cv-qualification is ignored.
16750 TypeSourceInfo *TI = nullptr;
16751 GetTypeFromParser(UnderlyingType.get(), &TI);
16752 EnumUnderlying = TI;
16753
16754 if (CheckEnumUnderlyingType(TI))
16755 // Recover by falling back to int.
16756 EnumUnderlying = Context.IntTy.getTypePtr();
16757
16758 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
16759 UPPC_FixedUnderlyingType))
16760 EnumUnderlying = Context.IntTy.getTypePtr();
16761
16762 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
16763 // For MSVC ABI compatibility, unfixed enums must use an underlying type
16764 // of 'int'. However, if this is an unfixed forward declaration, don't set
16765 // the underlying type unless the user enables -fms-compatibility. This
16766 // makes unfixed forward declared enums incomplete and is more conforming.
16767 if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
16768 EnumUnderlying = Context.IntTy.getTypePtr();
16769 }
16770 }
16771
16772 DeclContext *SearchDC = CurContext;
16773 DeclContext *DC = CurContext;
16774 bool isStdBadAlloc = false;
16775 bool isStdAlignValT = false;
16776
16777 RedeclarationKind Redecl = forRedeclarationInCurContext();
16778 if (TUK == TUK_Friend || TUK == TUK_Reference)
16779 Redecl = NotForRedeclaration;
16780
16781 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
16782 /// implemented asks for structural equivalence checking, the returned decl
16783 /// here is passed back to the parser, allowing the tag body to be parsed.
16784 auto createTagFromNewDecl = [&]() -> TagDecl * {
16785 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage")(static_cast <bool> (!getLangOpts().CPlusPlus &&
"not meant for C++ usage") ? void (0) : __assert_fail ("!getLangOpts().CPlusPlus && \"not meant for C++ usage\""
, "clang/lib/Sema/SemaDecl.cpp", 16785, __extension__ __PRETTY_FUNCTION__
))
;
16786 // If there is an identifier, use the location of the identifier as the
16787 // location of the decl, otherwise use the location of the struct/union
16788 // keyword.
16789 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16790 TagDecl *New = nullptr;
16791
16792 if (Kind == TTK_Enum) {
16793 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
16794 ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
16795 // If this is an undefined enum, bail.
16796 if (TUK != TUK_Definition && !Invalid)
16797 return nullptr;
16798 if (EnumUnderlying) {
16799 EnumDecl *ED = cast<EnumDecl>(New);
16800 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
16801 ED->setIntegerTypeSourceInfo(TI);
16802 else
16803 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
16804 QualType EnumTy = ED->getIntegerType();
16805 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
16806 ? Context.getPromotedIntegerType(EnumTy)
16807 : EnumTy);
16808 }
16809 } else { // struct/union
16810 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16811 nullptr);
16812 }
16813
16814 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16815 // Add alignment attributes if necessary; these attributes are checked
16816 // when the ASTContext lays out the structure.
16817 //
16818 // It is important for implementing the correct semantics that this
16819 // happen here (in ActOnTag). The #pragma pack stack is
16820 // maintained as a result of parser callbacks which can occur at
16821 // many points during the parsing of a struct declaration (because
16822 // the #pragma tokens are effectively skipped over during the
16823 // parsing of the struct).
16824 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16825 AddAlignmentAttributesForRecord(RD);
16826 AddMsStructLayoutForRecord(RD);
16827 }
16828 }
16829 New->setLexicalDeclContext(CurContext);
16830 return New;
16831 };
16832
16833 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
16834 if (Name && SS.isNotEmpty()) {
16835 // We have a nested-name tag ('struct foo::bar').
16836
16837 // Check for invalid 'foo::'.
16838 if (SS.isInvalid()) {
16839 Name = nullptr;
16840 goto CreateNewDecl;
16841 }
16842
16843 // If this is a friend or a reference to a class in a dependent
16844 // context, don't try to make a decl for it.
16845 if (TUK == TUK_Friend || TUK == TUK_Reference) {
16846 DC = computeDeclContext(SS, false);
16847 if (!DC) {
16848 IsDependent = true;
16849 return true;
16850 }
16851 } else {
16852 DC = computeDeclContext(SS, true);
16853 if (!DC) {
16854 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
16855 << SS.getRange();
16856 return true;
16857 }
16858 }
16859
16860 if (RequireCompleteDeclContext(SS, DC))
16861 return true;
16862
16863 SearchDC = DC;
16864 // Look-up name inside 'foo::'.
16865 LookupQualifiedName(Previous, DC);
16866
16867 if (Previous.isAmbiguous())
16868 return true;
16869
16870 if (Previous.empty()) {
16871 // Name lookup did not find anything. However, if the
16872 // nested-name-specifier refers to the current instantiation,
16873 // and that current instantiation has any dependent base
16874 // classes, we might find something at instantiation time: treat
16875 // this as a dependent elaborated-type-specifier.
16876 // But this only makes any sense for reference-like lookups.
16877 if (Previous.wasNotFoundInCurrentInstantiation() &&
16878 (TUK == TUK_Reference || TUK == TUK_Friend)) {
16879 IsDependent = true;
16880 return true;
16881 }
16882
16883 // A tag 'foo::bar' must already exist.
16884 Diag(NameLoc, diag::err_not_tag_in_scope)
16885 << Kind << Name << DC << SS.getRange();
16886 Name = nullptr;
16887 Invalid = true;
16888 goto CreateNewDecl;
16889 }
16890 } else if (Name) {
16891 // C++14 [class.mem]p14:
16892 // If T is the name of a class, then each of the following shall have a
16893 // name different from T:
16894 // -- every member of class T that is itself a type
16895 if (TUK != TUK_Reference && TUK != TUK_Friend &&
16896 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
16897 return true;
16898
16899 // If this is a named struct, check to see if there was a previous forward
16900 // declaration or definition.
16901 // FIXME: We're looking into outer scopes here, even when we
16902 // shouldn't be. Doing so can result in ambiguities that we
16903 // shouldn't be diagnosing.
16904 LookupName(Previous, S);
16905
16906 // When declaring or defining a tag, ignore ambiguities introduced
16907 // by types using'ed into this scope.
16908 if (Previous.isAmbiguous() &&
16909 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
16910 LookupResult::Filter F = Previous.makeFilter();
16911 while (F.hasNext()) {
16912 NamedDecl *ND = F.next();
16913 if (!ND->getDeclContext()->getRedeclContext()->Equals(
16914 SearchDC->getRedeclContext()))
16915 F.erase();
16916 }
16917 F.done();
16918 }
16919
16920 // C++11 [namespace.memdef]p3:
16921 // If the name in a friend declaration is neither qualified nor
16922 // a template-id and the declaration is a function or an
16923 // elaborated-type-specifier, the lookup to determine whether
16924 // the entity has been previously declared shall not consider
16925 // any scopes outside the innermost enclosing namespace.
16926 //
16927 // MSVC doesn't implement the above rule for types, so a friend tag
16928 // declaration may be a redeclaration of a type declared in an enclosing
16929 // scope. They do implement this rule for friend functions.
16930 //
16931 // Does it matter that this should be by scope instead of by
16932 // semantic context?
16933 if (!Previous.empty() && TUK == TUK_Friend) {
16934 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
16935 LookupResult::Filter F = Previous.makeFilter();
16936 bool FriendSawTagOutsideEnclosingNamespace = false;
16937 while (F.hasNext()) {
16938 NamedDecl *ND = F.next();
16939 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
16940 if (DC->isFileContext() &&
16941 !EnclosingNS->Encloses(ND->getDeclContext())) {
16942 if (getLangOpts().MSVCCompat)
16943 FriendSawTagOutsideEnclosingNamespace = true;
16944 else
16945 F.erase();
16946 }
16947 }
16948 F.done();
16949
16950 // Diagnose this MSVC extension in the easy case where lookup would have
16951 // unambiguously found something outside the enclosing namespace.
16952 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
16953 NamedDecl *ND = Previous.getFoundDecl();
16954 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
16955 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
16956 }
16957 }
16958
16959 // Note: there used to be some attempt at recovery here.
16960 if (Previous.isAmbiguous())
16961 return true;
16962
16963 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
16964 // FIXME: This makes sure that we ignore the contexts associated
16965 // with C structs, unions, and enums when looking for a matching
16966 // tag declaration or definition. See the similar lookup tweak
16967 // in Sema::LookupName; is there a better way to deal with this?
16968 while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC))
16969 SearchDC = SearchDC->getParent();
16970 } else if (getLangOpts().CPlusPlus) {
16971 // Inside ObjCContainer want to keep it as a lexical decl context but go
16972 // past it (most often to TranslationUnit) to find the semantic decl
16973 // context.
16974 while (isa<ObjCContainerDecl>(SearchDC))
16975 SearchDC = SearchDC->getParent();
16976 }
16977 } else if (getLangOpts().CPlusPlus) {
16978 // Don't use ObjCContainerDecl as the semantic decl context for anonymous
16979 // TagDecl the same way as we skip it for named TagDecl.
16980 while (isa<ObjCContainerDecl>(SearchDC))
16981 SearchDC = SearchDC->getParent();
16982 }
16983
16984 if (Previous.isSingleResult() &&
16985 Previous.getFoundDecl()->isTemplateParameter()) {
16986 // Maybe we will complain about the shadowed template parameter.
16987 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
16988 // Just pretend that we didn't see the previous declaration.
16989 Previous.clear();
16990 }
16991
16992 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
16993 DC->Equals(getStdNamespace())) {
16994 if (Name->isStr("bad_alloc")) {
16995 // This is a declaration of or a reference to "std::bad_alloc".
16996 isStdBadAlloc = true;
16997
16998 // If std::bad_alloc has been implicitly declared (but made invisible to
16999 // name lookup), fill in this implicit declaration as the previous
17000 // declaration, so that the declarations get chained appropriately.
17001 if (Previous.empty() && StdBadAlloc)
17002 Previous.addDecl(getStdBadAlloc());
17003 } else if (Name->isStr("align_val_t")) {
17004 isStdAlignValT = true;
17005 if (Previous.empty() && StdAlignValT)
17006 Previous.addDecl(getStdAlignValT());
17007 }
17008 }
17009
17010 // If we didn't find a previous declaration, and this is a reference
17011 // (or friend reference), move to the correct scope. In C++, we
17012 // also need to do a redeclaration lookup there, just in case
17013 // there's a shadow friend decl.
17014 if (Name && Previous.empty() &&
17015 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
17016 if (Invalid) goto CreateNewDecl;
17017 assert(SS.isEmpty())(static_cast <bool> (SS.isEmpty()) ? void (0) : __assert_fail
("SS.isEmpty()", "clang/lib/Sema/SemaDecl.cpp", 17017, __extension__
__PRETTY_FUNCTION__))
;
17018
17019 if (TUK == TUK_Reference || IsTemplateParamOrArg) {
17020 // C++ [basic.scope.pdecl]p5:
17021 // -- for an elaborated-type-specifier of the form
17022 //
17023 // class-key identifier
17024 //
17025 // if the elaborated-type-specifier is used in the
17026 // decl-specifier-seq or parameter-declaration-clause of a
17027 // function defined in namespace scope, the identifier is
17028 // declared as a class-name in the namespace that contains
17029 // the declaration; otherwise, except as a friend
17030 // declaration, the identifier is declared in the smallest
17031 // non-class, non-function-prototype scope that contains the
17032 // declaration.
17033 //
17034 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
17035 // C structs and unions.
17036 //
17037 // It is an error in C++ to declare (rather than define) an enum
17038 // type, including via an elaborated type specifier. We'll
17039 // diagnose that later; for now, declare the enum in the same
17040 // scope as we would have picked for any other tag type.
17041 //
17042 // GNU C also supports this behavior as part of its incomplete
17043 // enum types extension, while GNU C++ does not.
17044 //
17045 // Find the context where we'll be declaring the tag.
17046 // FIXME: We would like to maintain the current DeclContext as the
17047 // lexical context,
17048 SearchDC = getTagInjectionContext(SearchDC);
17049
17050 // Find the scope where we'll be declaring the tag.
17051 S = getTagInjectionScope(S, getLangOpts());
17052 } else {
17053 assert(TUK == TUK_Friend)(static_cast <bool> (TUK == TUK_Friend) ? void (0) : __assert_fail
("TUK == TUK_Friend", "clang/lib/Sema/SemaDecl.cpp", 17053, __extension__
__PRETTY_FUNCTION__))
;
17054 // C++ [namespace.memdef]p3:
17055 // If a friend declaration in a non-local class first declares a
17056 // class or function, the friend class or function is a member of
17057 // the innermost enclosing namespace.
17058 SearchDC = SearchDC->getEnclosingNamespaceContext();
17059 }
17060
17061 // In C++, we need to do a redeclaration lookup to properly
17062 // diagnose some problems.
17063 // FIXME: redeclaration lookup is also used (with and without C++) to find a
17064 // hidden declaration so that we don't get ambiguity errors when using a
17065 // type declared by an elaborated-type-specifier. In C that is not correct
17066 // and we should instead merge compatible types found by lookup.
17067 if (getLangOpts().CPlusPlus) {
17068 // FIXME: This can perform qualified lookups into function contexts,
17069 // which are meaningless.
17070 Previous.setRedeclarationKind(forRedeclarationInCurContext());
17071 LookupQualifiedName(Previous, SearchDC);
17072 } else {
17073 Previous.setRedeclarationKind(forRedeclarationInCurContext());
17074 LookupName(Previous, S);
17075 }
17076 }
17077
17078 // If we have a known previous declaration to use, then use it.
17079 if (Previous.empty() && SkipBody && SkipBody->Previous)
17080 Previous.addDecl(SkipBody->Previous);
17081
17082 if (!Previous.empty()) {
17083 NamedDecl *PrevDecl = Previous.getFoundDecl();
17084 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
17085
17086 // It's okay to have a tag decl in the same scope as a typedef
17087 // which hides a tag decl in the same scope. Finding this
17088 // with a redeclaration lookup can only actually happen in C++.
17089 //
17090 // This is also okay for elaborated-type-specifiers, which is
17091 // technically forbidden by the current standard but which is
17092 // okay according to the likely resolution of an open issue;
17093 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
17094 if (getLangOpts().CPlusPlus) {
17095 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
17096 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
17097 TagDecl *Tag = TT->getDecl();
17098 if (Tag->getDeclName() == Name &&
17099 Tag->getDeclContext()->getRedeclContext()
17100 ->Equals(TD->getDeclContext()->getRedeclContext())) {
17101 PrevDecl = Tag;
17102 Previous.clear();
17103 Previous.addDecl(Tag);
17104 Previous.resolveKind();
17105 }
17106 }
17107 }
17108 }
17109
17110 // If this is a redeclaration of a using shadow declaration, it must
17111 // declare a tag in the same context. In MSVC mode, we allow a
17112 // redefinition if either context is within the other.
17113 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
17114 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
17115 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
17116 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
17117 !(OldTag && isAcceptableTagRedeclContext(
17118 *this, OldTag->getDeclContext(), SearchDC))) {
17119 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
17120 Diag(Shadow->getTargetDecl()->getLocation(),
17121 diag::note_using_decl_target);
17122 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
17123 << 0;
17124 // Recover by ignoring the old declaration.
17125 Previous.clear();
17126 goto CreateNewDecl;
17127 }
17128 }
17129
17130 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
17131 // If this is a use of a previous tag, or if the tag is already declared
17132 // in the same scope (so that the definition/declaration completes or
17133 // rementions the tag), reuse the decl.
17134 if (TUK == TUK_Reference || TUK == TUK_Friend ||
17135 isDeclInScope(DirectPrevDecl, SearchDC, S,
17136 SS.isNotEmpty() || isMemberSpecialization)) {
17137 // Make sure that this wasn't declared as an enum and now used as a
17138 // struct or something similar.
17139 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
17140 TUK == TUK_Definition, KWLoc,
17141 Name)) {
17142 bool SafeToContinue
17143 = (PrevTagDecl->getTagKind() != TTK_Enum &&
17144 Kind != TTK_Enum);
17145 if (SafeToContinue)
17146 Diag(KWLoc, diag::err_use_with_wrong_tag)
17147 << Name
17148 << FixItHint::CreateReplacement(SourceRange(KWLoc),
17149 PrevTagDecl->getKindName());
17150 else
17151 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
17152 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
17153
17154 if (SafeToContinue)
17155 Kind = PrevTagDecl->getTagKind();
17156 else {
17157 // Recover by making this an anonymous redefinition.
17158 Name = nullptr;
17159 Previous.clear();
17160 Invalid = true;
17161 }
17162 }
17163
17164 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
17165 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
17166 if (TUK == TUK_Reference || TUK == TUK_Friend)
17167 return PrevTagDecl;
17168
17169 QualType EnumUnderlyingTy;
17170 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
17171 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
17172 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
17173 EnumUnderlyingTy = QualType(T, 0);
17174
17175 // All conflicts with previous declarations are recovered by
17176 // returning the previous declaration, unless this is a definition,
17177 // in which case we want the caller to bail out.
17178 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
17179 ScopedEnum, EnumUnderlyingTy,
17180 IsFixed, PrevEnum))
17181 return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
17182 }
17183
17184 // C++11 [class.mem]p1:
17185 // A member shall not be declared twice in the member-specification,
17186 // except that a nested class or member class template can be declared
17187 // and then later defined.
17188 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
17189 S->isDeclScope(PrevDecl)) {
17190 Diag(NameLoc, diag::ext_member_redeclared);
17191 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
17192 }
17193
17194 if (!Invalid) {
17195 // If this is a use, just return the declaration we found, unless
17196 // we have attributes.
17197 if (TUK == TUK_Reference || TUK == TUK_Friend) {
17198 if (!Attrs.empty()) {
17199 // FIXME: Diagnose these attributes. For now, we create a new
17200 // declaration to hold them.
17201 } else if (TUK == TUK_Reference &&
17202 (PrevTagDecl->getFriendObjectKind() ==
17203 Decl::FOK_Undeclared ||
17204 PrevDecl->getOwningModule() != getCurrentModule()) &&
17205 SS.isEmpty()) {
17206 // This declaration is a reference to an existing entity, but
17207 // has different visibility from that entity: it either makes
17208 // a friend visible or it makes a type visible in a new module.
17209 // In either case, create a new declaration. We only do this if
17210 // the declaration would have meant the same thing if no prior
17211 // declaration were found, that is, if it was found in the same
17212 // scope where we would have injected a declaration.
17213 if (!getTagInjectionContext(CurContext)->getRedeclContext()
17214 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
17215 return PrevTagDecl;
17216 // This is in the injected scope, create a new declaration in
17217 // that scope.
17218 S = getTagInjectionScope(S, getLangOpts());
17219 } else {
17220 return PrevTagDecl;
17221 }
17222 }
17223
17224 // Diagnose attempts to redefine a tag.
17225 if (TUK == TUK_Definition) {
17226 if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
17227 // If we're defining a specialization and the previous definition
17228 // is from an implicit instantiation, don't emit an error
17229 // here; we'll catch this in the general case below.
17230 bool IsExplicitSpecializationAfterInstantiation = false;
17231 if (isMemberSpecialization) {
17232 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
17233 IsExplicitSpecializationAfterInstantiation =
17234 RD->getTemplateSpecializationKind() !=
17235 TSK_ExplicitSpecialization;
17236 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
17237 IsExplicitSpecializationAfterInstantiation =
17238 ED->getTemplateSpecializationKind() !=
17239 TSK_ExplicitSpecialization;
17240 }
17241
17242 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
17243 // not keep more that one definition around (merge them). However,
17244 // ensure the decl passes the structural compatibility check in
17245 // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
17246 NamedDecl *Hidden = nullptr;
17247 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
17248 // There is a definition of this tag, but it is not visible. We
17249 // explicitly make use of C++'s one definition rule here, and
17250 // assume that this definition is identical to the hidden one
17251 // we already have. Make the existing definition visible and
17252 // use it in place of this one.
17253 if (!getLangOpts().CPlusPlus) {
17254 // Postpone making the old definition visible until after we
17255 // complete parsing the new one and do the structural
17256 // comparison.
17257 SkipBody->CheckSameAsPrevious = true;
17258 SkipBody->New = createTagFromNewDecl();
17259 SkipBody->Previous = Def;
17260 return Def;
17261 } else {
17262 SkipBody->ShouldSkip = true;
17263 SkipBody->Previous = Def;
17264 makeMergedDefinitionVisible(Hidden);
17265 // Carry on and handle it like a normal definition. We'll
17266 // skip starting the definitiion later.
17267 }
17268 } else if (!IsExplicitSpecializationAfterInstantiation) {
17269 // A redeclaration in function prototype scope in C isn't
17270 // visible elsewhere, so merely issue a warning.
17271 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
17272 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
17273 else
17274 Diag(NameLoc, diag::err_redefinition) << Name;
17275 notePreviousDefinition(Def,
17276 NameLoc.isValid() ? NameLoc : KWLoc);
17277 // If this is a redefinition, recover by making this
17278 // struct be anonymous, which will make any later
17279 // references get the previous definition.
17280 Name = nullptr;
17281 Previous.clear();
17282 Invalid = true;
17283 }
17284 } else {
17285 // If the type is currently being defined, complain
17286 // about a nested redefinition.
17287 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
17288 if (TD->isBeingDefined()) {
17289 Diag(NameLoc, diag::err_nested_redefinition) << Name;
17290 Diag(PrevTagDecl->getLocation(),
17291 diag::note_previous_definition);
17292 Name = nullptr;
17293 Previous.clear();
17294 Invalid = true;
17295 }
17296 }
17297
17298 // Okay, this is definition of a previously declared or referenced
17299 // tag. We're going to create a new Decl for it.
17300 }
17301
17302 // Okay, we're going to make a redeclaration. If this is some kind
17303 // of reference, make sure we build the redeclaration in the same DC
17304 // as the original, and ignore the current access specifier.
17305 if (TUK == TUK_Friend || TUK == TUK_Reference) {
17306 SearchDC = PrevTagDecl->getDeclContext();
17307 AS = AS_none;
17308 }
17309 }
17310 // If we get here we have (another) forward declaration or we
17311 // have a definition. Just create a new decl.
17312
17313 } else {
17314 // If we get here, this is a definition of a new tag type in a nested
17315 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
17316 // new decl/type. We set PrevDecl to NULL so that the entities
17317 // have distinct types.
17318 Previous.clear();
17319 }
17320 // If we get here, we're going to create a new Decl. If PrevDecl
17321 // is non-NULL, it's a definition of the tag declared by
17322 // PrevDecl. If it's NULL, we have a new definition.
17323
17324 // Otherwise, PrevDecl is not a tag, but was found with tag
17325 // lookup. This is only actually possible in C++, where a few
17326 // things like templates still live in the tag namespace.
17327 } else {
17328 // Use a better diagnostic if an elaborated-type-specifier
17329 // found the wrong kind of type on the first
17330 // (non-redeclaration) lookup.
17331 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
17332 !Previous.isForRedeclaration()) {
17333 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
17334 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
17335 << Kind;
17336 Diag(PrevDecl->getLocation(), diag::note_declared_at);
17337 Invalid = true;
17338
17339 // Otherwise, only diagnose if the declaration is in scope.
17340 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
17341 SS.isNotEmpty() || isMemberSpecialization)) {
17342 // do nothing
17343
17344 // Diagnose implicit declarations introduced by elaborated types.
17345 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
17346 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
17347 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
17348 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
17349 Invalid = true;
17350
17351 // Otherwise it's a declaration. Call out a particularly common
17352 // case here.
17353 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
17354 unsigned Kind = 0;
17355 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
17356 Diag(NameLoc, diag::err_tag_definition_of_typedef)
17357 << Name << Kind << TND->getUnderlyingType();
17358 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
17359 Invalid = true;
17360
17361 // Otherwise, diagnose.
17362 } else {
17363 // The tag name clashes with something else in the target scope,
17364 // issue an error and recover by making this tag be anonymous.
17365 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
17366 notePreviousDefinition(PrevDecl, NameLoc);
17367 Name = nullptr;
17368 Invalid = true;
17369 }
17370
17371 // The existing declaration isn't relevant to us; we're in a
17372 // new scope, so clear out the previous declaration.
17373 Previous.clear();
17374 }
17375 }
17376
17377CreateNewDecl:
17378
17379 TagDecl *PrevDecl = nullptr;
17380 if (Previous.isSingleResult())
17381 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
17382
17383 // If there is an identifier, use the location of the identifier as the
17384 // location of the decl, otherwise use the location of the struct/union
17385 // keyword.
17386 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
17387
17388 // Otherwise, create a new declaration. If there is a previous
17389 // declaration of the same entity, the two will be linked via
17390 // PrevDecl.
17391 TagDecl *New;
17392
17393 if (Kind == TTK_Enum) {
17394 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
17395 // enum X { A, B, C } D; D should chain to X.
17396 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
17397 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
17398 ScopedEnumUsesClassTag, IsFixed);
17399
17400 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
17401 StdAlignValT = cast<EnumDecl>(New);
17402
17403 // If this is an undefined enum, warn.
17404 if (TUK != TUK_Definition && !Invalid) {
17405 TagDecl *Def;
17406 if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
17407 // C++0x: 7.2p2: opaque-enum-declaration.
17408 // Conflicts are diagnosed above. Do nothing.
17409 }
17410 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
17411 Diag(Loc, diag::ext_forward_ref_enum_def)
17412 << New;
17413 Diag(Def->getLocation(), diag::note_previous_definition);
17414 } else {
17415 unsigned DiagID = diag::ext_forward_ref_enum;
17416 if (getLangOpts().MSVCCompat)
17417 DiagID = diag::ext_ms_forward_ref_enum;
17418 else if (getLangOpts().CPlusPlus)
17419 DiagID = diag::err_forward_ref_enum;
17420 Diag(Loc, DiagID);
17421 }
17422 }
17423
17424 if (EnumUnderlying) {
17425 EnumDecl *ED = cast<EnumDecl>(New);
17426 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
17427 ED->setIntegerTypeSourceInfo(TI);
17428 else
17429 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
17430 QualType EnumTy = ED->getIntegerType();
17431 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
17432 ? Context.getPromotedIntegerType(EnumTy)
17433 : EnumTy);
17434 assert(ED->isComplete() && "enum with type should be complete")(static_cast <bool> (ED->isComplete() && "enum with type should be complete"
) ? void (0) : __assert_fail ("ED->isComplete() && \"enum with type should be complete\""
, "clang/lib/Sema/SemaDecl.cpp", 17434, __extension__ __PRETTY_FUNCTION__
))
;
17435 }
17436 } else {
17437 // struct/union/class
17438
17439 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
17440 // struct X { int A; } D; D should chain to X.
17441 if (getLangOpts().CPlusPlus) {
17442 // FIXME: Look for a way to use RecordDecl for simple structs.
17443 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17444 cast_or_null<CXXRecordDecl>(PrevDecl));
17445
17446 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
17447 StdBadAlloc = cast<CXXRecordDecl>(New);
17448 } else
17449 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17450 cast_or_null<RecordDecl>(PrevDecl));
17451 }
17452
17453 if (OOK != OOK_Outside && TUK == TUK_Definition && !getLangOpts().CPlusPlus)
17454 Diag(New->getLocation(), diag::ext_type_defined_in_offsetof)
17455 << (OOK == OOK_Macro) << New->getSourceRange();
17456
17457 // C++11 [dcl.type]p3:
17458 // A type-specifier-seq shall not define a class or enumeration [...].
17459 if (!Invalid && getLangOpts().CPlusPlus &&
17460 (IsTypeSpecifier || IsTemplateParamOrArg) && TUK == TUK_Definition) {
17461 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
17462 << Context.getTagDeclType(New);
17463 Invalid = true;
17464 }
17465
17466 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
17467 DC->getDeclKind() == Decl::Enum) {
17468 Diag(New->getLocation(), diag::err_type_defined_in_enum)
17469 << Context.getTagDeclType(New);
17470 Invalid = true;
17471 }
17472
17473 // Maybe add qualifier info.
17474 if (SS.isNotEmpty()) {
17475 if (SS.isSet()) {
17476 // If this is either a declaration or a definition, check the
17477 // nested-name-specifier against the current context.
17478 if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
17479 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
17480 isMemberSpecialization))
17481 Invalid = true;
17482
17483 New->setQualifierInfo(SS.getWithLocInContext(Context));
17484 if (TemplateParameterLists.size() > 0) {
17485 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
17486 }
17487 }
17488 else
17489 Invalid = true;
17490 }
17491
17492 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
17493 // Add alignment attributes if necessary; these attributes are checked when
17494 // the ASTContext lays out the structure.
17495 //
17496 // It is important for implementing the correct semantics that this
17497 // happen here (in ActOnTag). The #pragma pack stack is
17498 // maintained as a result of parser callbacks which can occur at
17499 // many points during the parsing of a struct declaration (because
17500 // the #pragma tokens are effectively skipped over during the
17501 // parsing of the struct).
17502 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
17503 AddAlignmentAttributesForRecord(RD);
17504 AddMsStructLayoutForRecord(RD);
17505 }
17506 }
17507
17508 if (ModulePrivateLoc.isValid()) {
17509 if (isMemberSpecialization)
17510 Diag(New->getLocation(), diag::err_module_private_specialization)
17511 << 2
17512 << FixItHint::CreateRemoval(ModulePrivateLoc);
17513 // __module_private__ does not apply to local classes. However, we only
17514 // diagnose this as an error when the declaration specifiers are
17515 // freestanding. Here, we just ignore the __module_private__.
17516 else if (!SearchDC->isFunctionOrMethod())
17517 New->setModulePrivate();
17518 }
17519
17520 // If this is a specialization of a member class (of a class template),
17521 // check the specialization.
17522 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
17523 Invalid = true;
17524
17525 // If we're declaring or defining a tag in function prototype scope in C,
17526 // note that this type can only be used within the function and add it to
17527 // the list of decls to inject into the function definition scope.
17528 if ((Name || Kind == TTK_Enum) &&
17529 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
17530 if (getLangOpts().CPlusPlus) {
17531 // C++ [dcl.fct]p6:
17532 // Types shall not be defined in return or parameter types.
17533 if (TUK == TUK_Definition && !IsTypeSpecifier) {
17534 Diag(Loc, diag::err_type_defined_in_param_type)
17535 << Name;
17536 Invalid = true;
17537 }
17538 } else if (!PrevDecl) {
17539 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
17540 }
17541 }
17542
17543 if (Invalid)
17544 New->setInvalidDecl();
17545
17546 // Set the lexical context. If the tag has a C++ scope specifier, the
17547 // lexical context will be different from the semantic context.
17548 New->setLexicalDeclContext(CurContext);
17549
17550 // Mark this as a friend decl if applicable.
17551 // In Microsoft mode, a friend declaration also acts as a forward
17552 // declaration so we always pass true to setObjectOfFriendDecl to make
17553 // the tag name visible.
17554 if (TUK == TUK_Friend)
17555 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
17556
17557 // Set the access specifier.
17558 if (!Invalid && SearchDC->isRecord())
17559 SetMemberAccessSpecifier(New, PrevDecl, AS);
17560
17561 if (PrevDecl)
17562 CheckRedeclarationInModule(New, PrevDecl);
17563
17564 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
17565 New->startDefinition();
17566
17567 ProcessDeclAttributeList(S, New, Attrs);
17568 AddPragmaAttributes(S, New);
17569
17570 // If this has an identifier, add it to the scope stack.
17571 if (TUK == TUK_Friend) {
17572 // We might be replacing an existing declaration in the lookup tables;
17573 // if so, borrow its access specifier.
17574 if (PrevDecl)
17575 New->setAccess(PrevDecl->getAccess());
17576
17577 DeclContext *DC = New->getDeclContext()->getRedeclContext();
17578 DC->makeDeclVisibleInContext(New);
17579 if (Name) // can be null along some error paths
17580 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
17581 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
17582 } else if (Name) {
17583 S = getNonFieldDeclScope(S);
17584 PushOnScopeChains(New, S, true);
17585 } else {
17586 CurContext->addDecl(New);
17587 }
17588
17589 // If this is the C FILE type, notify the AST context.
17590 if (IdentifierInfo *II = New->getIdentifier())
17591 if (!New->isInvalidDecl() &&
17592 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
17593 II->isStr("FILE"))
17594 Context.setFILEDecl(New);
17595
17596 if (PrevDecl)
17597 mergeDeclAttributes(New, PrevDecl);
17598
17599 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
17600 inferGslOwnerPointerAttribute(CXXRD);
17601
17602 // If there's a #pragma GCC visibility in scope, set the visibility of this
17603 // record.
17604 AddPushedVisibilityAttribute(New);
17605
17606 if (isMemberSpecialization && !New->isInvalidDecl())
17607 CompleteMemberSpecialization(New, Previous);
17608
17609 OwnedDecl = true;
17610 // In C++, don't return an invalid declaration. We can't recover well from
17611 // the cases where we make the type anonymous.
17612 if (Invalid && getLangOpts().CPlusPlus) {
17613 if (New->isBeingDefined())
17614 if (auto RD = dyn_cast<RecordDecl>(New))
17615 RD->completeDefinition();
17616 return true;
17617 } else if (SkipBody && SkipBody->ShouldSkip) {
17618 return SkipBody->Previous;
17619 } else {
17620 return New;
17621 }
17622}
17623
17624void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
17625 AdjustDeclIfTemplate(TagD);
17626 TagDecl *Tag = cast<TagDecl>(TagD);
17627
17628 // Enter the tag context.
17629 PushDeclContext(S, Tag);
17630
17631 ActOnDocumentableDecl(TagD);
17632
17633 // If there's a #pragma GCC visibility in scope, set the visibility of this
17634 // record.
17635 AddPushedVisibilityAttribute(Tag);
17636}
17637
17638bool Sema::ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody) {
17639 if (!hasStructuralCompatLayout(Prev, SkipBody.New))
17640 return false;
17641
17642 // Make the previous decl visible.
17643 makeMergedDefinitionVisible(SkipBody.Previous);
17644 return true;
17645}
17646
17647void Sema::ActOnObjCContainerStartDefinition(ObjCContainerDecl *IDecl) {
17648 assert(IDecl->getLexicalParent() == CurContext &&(static_cast <bool> (IDecl->getLexicalParent() == CurContext
&& "The next DeclContext should be lexically contained in the current one."
) ? void (0) : __assert_fail ("IDecl->getLexicalParent() == CurContext && \"The next DeclContext should be lexically contained in the current one.\""
, "clang/lib/Sema/SemaDecl.cpp", 17649, __extension__ __PRETTY_FUNCTION__
))
17649 "The next DeclContext should be lexically contained in the current one.")(static_cast <bool> (IDecl->getLexicalParent() == CurContext
&& "The next DeclContext should be lexically contained in the current one."
) ? void (0) : __assert_fail ("IDecl->getLexicalParent() == CurContext && \"The next DeclContext should be lexically contained in the current one.\""
, "clang/lib/Sema/SemaDecl.cpp", 17649, __extension__ __PRETTY_FUNCTION__
))
;
17650 CurContext = IDecl;
17651}
17652
17653void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
17654 SourceLocation FinalLoc,
17655 bool IsFinalSpelledSealed,
17656 bool IsAbstract,
17657 SourceLocation LBraceLoc) {
17658 AdjustDeclIfTemplate(TagD);
17659 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
17660
17661 FieldCollector->StartClass();
17662
17663 if (!Record->getIdentifier())
17664 return;
17665
17666 if (IsAbstract)
17667 Record->markAbstract();
17668
17669 if (FinalLoc.isValid()) {
17670 Record->addAttr(FinalAttr::Create(Context, FinalLoc,
17671 IsFinalSpelledSealed
17672 ? FinalAttr::Keyword_sealed
17673 : FinalAttr::Keyword_final));
17674 }
17675 // C++ [class]p2:
17676 // [...] The class-name is also inserted into the scope of the
17677 // class itself; this is known as the injected-class-name. For
17678 // purposes of access checking, the injected-class-name is treated
17679 // as if it were a public member name.
17680 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
17681 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
17682 Record->getLocation(), Record->getIdentifier(),
17683 /*PrevDecl=*/nullptr,
17684 /*DelayTypeCreation=*/true);
17685 Context.getTypeDeclType(InjectedClassName, Record);
17686 InjectedClassName->setImplicit();
17687 InjectedClassName->setAccess(AS_public);
17688 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
17689 InjectedClassName->setDescribedClassTemplate(Template);
17690 PushOnScopeChains(InjectedClassName, S);
17691 assert(InjectedClassName->isInjectedClassName() &&(static_cast <bool> (InjectedClassName->isInjectedClassName
() && "Broken injected-class-name") ? void (0) : __assert_fail
("InjectedClassName->isInjectedClassName() && \"Broken injected-class-name\""
, "clang/lib/Sema/SemaDecl.cpp", 17692, __extension__ __PRETTY_FUNCTION__
))
17692 "Broken injected-class-name")(static_cast <bool> (InjectedClassName->isInjectedClassName
() && "Broken injected-class-name") ? void (0) : __assert_fail
("InjectedClassName->isInjectedClassName() && \"Broken injected-class-name\""
, "clang/lib/Sema/SemaDecl.cpp", 17692, __extension__ __PRETTY_FUNCTION__
))
;
17693}
17694
17695void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
17696 SourceRange BraceRange) {
17697 AdjustDeclIfTemplate(TagD);
17698 TagDecl *Tag = cast<TagDecl>(TagD);
17699 Tag->setBraceRange(BraceRange);
17700
17701 // Make sure we "complete" the definition even it is invalid.
17702 if (Tag->isBeingDefined()) {
17703 assert(Tag->isInvalidDecl() && "We should already have completed it")(static_cast <bool> (Tag->isInvalidDecl() &&
"We should already have completed it") ? void (0) : __assert_fail
("Tag->isInvalidDecl() && \"We should already have completed it\""
, "clang/lib/Sema/SemaDecl.cpp", 17703, __extension__ __PRETTY_FUNCTION__
))
;
17704 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
17705 RD->completeDefinition();
17706 }
17707
17708 if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
17709 FieldCollector->FinishClass();
17710 if (RD->hasAttr<SYCLSpecialClassAttr>()) {
17711 auto *Def = RD->getDefinition();
17712 assert(Def && "The record is expected to have a completed definition")(static_cast <bool> (Def && "The record is expected to have a completed definition"
) ? void (0) : __assert_fail ("Def && \"The record is expected to have a completed definition\""
, "clang/lib/Sema/SemaDecl.cpp", 17712, __extension__ __PRETTY_FUNCTION__
))
;
17713 unsigned NumInitMethods = 0;
17714 for (auto *Method : Def->methods()) {
17715 if (!Method->getIdentifier())
17716 continue;
17717 if (Method->getName() == "__init")
17718 NumInitMethods++;
17719 }
17720 if (NumInitMethods > 1 || !Def->hasInitMethod())
17721 Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
17722 }
17723 }
17724
17725 // Exit this scope of this tag's definition.
17726 PopDeclContext();
17727
17728 if (getCurLexicalContext()->isObjCContainer() &&
17729 Tag->getDeclContext()->isFileContext())
17730 Tag->setTopLevelDeclInObjCContainer();
17731
17732 // Notify the consumer that we've defined a tag.
17733 if (!Tag->isInvalidDecl())
17734 Consumer.HandleTagDeclDefinition(Tag);
17735
17736 // Clangs implementation of #pragma align(packed) differs in bitfield layout
17737 // from XLs and instead matches the XL #pragma pack(1) behavior.
17738 if (Context.getTargetInfo().getTriple().isOSAIX() &&
17739 AlignPackStack.hasValue()) {
17740 AlignPackInfo APInfo = AlignPackStack.CurrentValue;
17741 // Only diagnose #pragma align(packed).
17742 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
17743 return;
17744 const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
17745 if (!RD)
17746 return;
17747 // Only warn if there is at least 1 bitfield member.
17748 if (llvm::any_of(RD->fields(),
17749 [](const FieldDecl *FD) { return FD->isBitField(); }))
17750 Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
17751 }
17752}
17753
17754void Sema::ActOnObjCContainerFinishDefinition() {
17755 // Exit this scope of this interface definition.
17756 PopDeclContext();
17757}
17758
17759void Sema::ActOnObjCTemporaryExitContainerContext(ObjCContainerDecl *ObjCCtx) {
17760 assert(ObjCCtx == CurContext && "Mismatch of container contexts")(static_cast <bool> (ObjCCtx == CurContext && "Mismatch of container contexts"
) ? void (0) : __assert_fail ("ObjCCtx == CurContext && \"Mismatch of container contexts\""
, "clang/lib/Sema/SemaDecl.cpp", 17760, __extension__ __PRETTY_FUNCTION__
))
;
17761 OriginalLexicalContext = ObjCCtx;
17762 ActOnObjCContainerFinishDefinition();
17763}
17764
17765void Sema::ActOnObjCReenterContainerContext(ObjCContainerDecl *ObjCCtx) {
17766 ActOnObjCContainerStartDefinition(ObjCCtx);
17767 OriginalLexicalContext = nullptr;
17768}
17769
17770void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
17771 AdjustDeclIfTemplate(TagD);
17772 TagDecl *Tag = cast<TagDecl>(TagD);
17773 Tag->setInvalidDecl();
17774
17775 // Make sure we "complete" the definition even it is invalid.
17776 if (Tag->isBeingDefined()) {
17777 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
17778 RD->completeDefinition();
17779 }
17780
17781 // We're undoing ActOnTagStartDefinition here, not
17782 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
17783 // the FieldCollector.
17784
17785 PopDeclContext();
17786}
17787
17788// Note that FieldName may be null for anonymous bitfields.
17789ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
17790 IdentifierInfo *FieldName, QualType FieldTy,
17791 bool IsMsStruct, Expr *BitWidth) {
17792 assert(BitWidth)(static_cast <bool> (BitWidth) ? void (0) : __assert_fail
("BitWidth", "clang/lib/Sema/SemaDecl.cpp", 17792, __extension__
__PRETTY_FUNCTION__))
;
17793 if (BitWidth->containsErrors())
17794 return ExprError();
17795
17796 // C99 6.7.2.1p4 - verify the field type.
17797 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
17798 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
17799 // Handle incomplete and sizeless types with a specific error.
17800 if (RequireCompleteSizedType(FieldLoc, FieldTy,
17801 diag::err_field_incomplete_or_sizeless))
17802 return ExprError();
17803 if (FieldName)
17804 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
17805 << FieldName << FieldTy << BitWidth->getSourceRange();
17806 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
17807 << FieldTy << BitWidth->getSourceRange();
17808 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
17809 UPPC_BitFieldWidth))
17810 return ExprError();
17811
17812 // If the bit-width is type- or value-dependent, don't try to check
17813 // it now.
17814 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
17815 return BitWidth;
17816
17817 llvm::APSInt Value;
17818 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
17819 if (ICE.isInvalid())
17820 return ICE;
17821 BitWidth = ICE.get();
17822
17823 // Zero-width bitfield is ok for anonymous field.
17824 if (Value == 0 && FieldName)
17825 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
17826
17827 if (Value.isSigned() && Value.isNegative()) {
17828 if (FieldName)
17829 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
17830 << FieldName << toString(Value, 10);
17831 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
17832 << toString(Value, 10);
17833 }
17834
17835 // The size of the bit-field must not exceed our maximum permitted object
17836 // size.
17837 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
17838 return Diag(FieldLoc, diag::err_bitfield_too_wide)
17839 << !FieldName << FieldName << toString(Value, 10);
17840 }
17841
17842 if (!FieldTy->isDependentType()) {
17843 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
17844 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
17845 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
17846
17847 // Over-wide bitfields are an error in C or when using the MSVC bitfield
17848 // ABI.
17849 bool CStdConstraintViolation =
17850 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
17851 bool MSBitfieldViolation =
17852 Value.ugt(TypeStorageSize) &&
17853 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
17854 if (CStdConstraintViolation || MSBitfieldViolation) {
17855 unsigned DiagWidth =
17856 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
17857 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
17858 << (bool)FieldName << FieldName << toString(Value, 10)
17859 << !CStdConstraintViolation << DiagWidth;
17860 }
17861
17862 // Warn on types where the user might conceivably expect to get all
17863 // specified bits as value bits: that's all integral types other than
17864 // 'bool'.
17865 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
17866 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
17867 << FieldName << toString(Value, 10)
17868 << (unsigned)TypeWidth;
17869 }
17870 }
17871
17872 return BitWidth;
17873}
17874
17875/// ActOnField - Each field of a C struct/union is passed into this in order
17876/// to create a FieldDecl object for it.
17877Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
17878 Declarator &D, Expr *BitfieldWidth) {
17879 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
1
Assuming null pointer is passed into cast
2
Passing null pointer value via 2nd parameter 'Record'
3
Calling 'Sema::HandleField'
17880 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
17881 /*InitStyle=*/ICIS_NoInit, AS_public);
17882 return Res;
17883}
17884
17885/// HandleField - Analyze a field of a C struct or a C++ data member.
17886///
17887FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
17888 SourceLocation DeclStart,
17889 Declarator &D, Expr *BitWidth,
17890 InClassInitStyle InitStyle,
17891 AccessSpecifier AS) {
17892 if (D.isDecompositionDeclarator()) {
4
Taking false branch
17893 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
17894 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
17895 << Decomp.getSourceRange();
17896 return nullptr;
17897 }
17898
17899 IdentifierInfo *II = D.getIdentifier();
17900 SourceLocation Loc = DeclStart;
17901 if (II
4.1
'II' is null
) Loc = D.getIdentifierLoc();
5
Taking false branch
17902
17903 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17904 QualType T = TInfo->getType();
17905 if (getLangOpts().CPlusPlus) {
6
Assuming field 'CPlusPlus' is 0
7
Taking false branch
17906 CheckExtraCXXDefaultArguments(D);
17907
17908 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
17909 UPPC_DataMemberType)) {
17910 D.setInvalidType();
17911 T = Context.IntTy;
17912 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
17913 }
17914 }
17915
17916 DiagnoseFunctionSpecifiers(D.getDeclSpec());
17917
17918 if (D.getDeclSpec().isInlineSpecified())
8
Assuming the condition is false
9
Taking false branch
17919 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
17920 << getLangOpts().CPlusPlus17;
17921 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
10
Assuming 'TSCS' is 0
11
Taking false branch
17922 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
17923 diag::err_invalid_thread)
17924 << DeclSpec::getSpecifierName(TSCS);
17925
17926 // Check to see if this name was declared as a member previously
17927 NamedDecl *PrevDecl = nullptr;
17928 LookupResult Previous(*this, II, Loc, LookupMemberName,
17929 ForVisibleRedeclaration);
17930 LookupName(Previous, S);
17931 switch (Previous.getResultKind()) {
12
Control jumps to 'case Ambiguous:' at line 17943
17932 case LookupResult::Found:
17933 case LookupResult::FoundUnresolvedValue:
17934 PrevDecl = Previous.getAsSingle<NamedDecl>();
17935 break;
17936
17937 case LookupResult::FoundOverloaded:
17938 PrevDecl = Previous.getRepresentativeDecl();
17939 break;
17940
17941 case LookupResult::NotFound:
17942 case LookupResult::NotFoundInCurrentInstantiation:
17943 case LookupResult::Ambiguous:
17944 break;
13
Execution continues on line 17946
17945 }
17946 Previous.suppressDiagnostics();
17947
17948 if (PrevDecl
13.1
'PrevDecl' is null
&& PrevDecl->isTemplateParameter()) {
17949 // Maybe we will complain about the shadowed template parameter.
17950 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
17951 // Just pretend that we didn't see the previous declaration.
17952 PrevDecl = nullptr;
17953 }
17954
17955 if (PrevDecl
13.2
'PrevDecl' is null
&& !isDeclInScope(PrevDecl, Record, S))
17956 PrevDecl = nullptr;
17957
17958 bool Mutable
17959 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
14
Assuming the condition is false
17960 SourceLocation TSSL = D.getBeginLoc();
17961 FieldDecl *NewFD
17962 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
17963 TSSL, AS, PrevDecl, &D);
17964
17965 if (NewFD->isInvalidDecl())
15
Assuming the condition is true
16
Taking true branch
17966 Record->setInvalidDecl();
17
Called C++ object pointer is null
17967
17968 if (D.getDeclSpec().isModulePrivateSpecified())
17969 NewFD->setModulePrivate();
17970
17971 if (NewFD->isInvalidDecl() && PrevDecl) {
17972 // Don't introduce NewFD into scope; there's already something
17973 // with the same name in the same scope.
17974 } else if (II) {
17975 PushOnScopeChains(NewFD, S);
17976 } else
17977 Record->addDecl(NewFD);
17978
17979 return NewFD;
17980}
17981
17982/// Build a new FieldDecl and check its well-formedness.
17983///
17984/// This routine builds a new FieldDecl given the fields name, type,
17985/// record, etc. \p PrevDecl should refer to any previous declaration
17986/// with the same name and in the same scope as the field to be
17987/// created.
17988///
17989/// \returns a new FieldDecl.
17990///
17991/// \todo The Declarator argument is a hack. It will be removed once
17992FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
17993 TypeSourceInfo *TInfo,
17994 RecordDecl *Record, SourceLocation Loc,
17995 bool Mutable, Expr *BitWidth,
17996 InClassInitStyle InitStyle,
17997 SourceLocation TSSL,
17998 AccessSpecifier AS, NamedDecl *PrevDecl,
17999 Declarator *D) {
18000 IdentifierInfo *II = Name.getAsIdentifierInfo();
18001 bool InvalidDecl = false;
18002 if (D) InvalidDecl = D->isInvalidType();
18003
18004 // If we receive a broken type, recover by assuming 'int' and
18005 // marking this declaration as invalid.
18006 if (T.isNull() || T->containsErrors()) {
18007 InvalidDecl = true;
18008 T = Context.IntTy;
18009 }
18010
18011 QualType EltTy = Context.getBaseElementType(T);
18012 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
18013 if (RequireCompleteSizedType(Loc, EltTy,
18014 diag::err_field_incomplete_or_sizeless)) {
18015 // Fields of incomplete type force their record to be invalid.
18016 Record->setInvalidDecl();
18017 InvalidDecl = true;
18018 } else {
18019 NamedDecl *Def;
18020 EltTy->isIncompleteType(&Def);
18021 if (Def && Def->isInvalidDecl()) {
18022 Record->setInvalidDecl();
18023 InvalidDecl = true;
18024 }
18025 }
18026 }
18027
18028 // TR 18037 does not allow fields to be declared with address space
18029 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
18030 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
18031 Diag(Loc, diag::err_field_with_address_space);
18032 Record->setInvalidDecl();
18033 InvalidDecl = true;
18034 }
18035
18036 if (LangOpts.OpenCL) {
18037 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
18038 // used as structure or union field: image, sampler, event or block types.
18039 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
18040 T->isBlockPointerType()) {
18041 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
18042 Record->setInvalidDecl();
18043 InvalidDecl = true;
18044 }
18045 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
18046 // is enabled.
18047 if (BitWidth && !getOpenCLOptions().isAvailableOption(
18048 "__cl_clang_bitfields", LangOpts)) {
18049 Diag(Loc, diag::err_opencl_bitfields);
18050 InvalidDecl = true;
18051 }
18052 }
18053
18054 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
18055 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
18056 T.hasQualifiers()) {
18057 InvalidDecl = true;
18058 Diag(Loc, diag::err_anon_bitfield_qualifiers);
18059 }
18060
18061 // C99 6.7.2.1p8: A member of a structure or union may have any type other
18062 // than a variably modified type.
18063 if (!InvalidDecl && T->isVariablyModifiedType()) {
18064 if (!tryToFixVariablyModifiedVarType(
18065 TInfo, T, Loc, diag::err_typecheck_field_variable_size))
18066 InvalidDecl = true;
18067 }
18068
18069 // Fields can not have abstract class types
18070 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
18071 diag::err_abstract_type_in_decl,
18072 AbstractFieldType))
18073 InvalidDecl = true;
18074
18075 if (InvalidDecl)
18076 BitWidth = nullptr;
18077 // If this is declared as a bit-field, check the bit-field.
18078 if (BitWidth) {
18079 BitWidth =
18080 VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get();
18081 if (!BitWidth) {
18082 InvalidDecl = true;
18083 BitWidth = nullptr;
18084 }
18085 }
18086
18087 // Check that 'mutable' is consistent with the type of the declaration.
18088 if (!InvalidDecl && Mutable) {
18089 unsigned DiagID = 0;
18090 if (T->isReferenceType())
18091 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
18092 : diag::err_mutable_reference;
18093 else if (T.isConstQualified())
18094 DiagID = diag::err_mutable_const;
18095
18096 if (DiagID) {
18097 SourceLocation ErrLoc = Loc;
18098 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
18099 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
18100 Diag(ErrLoc, DiagID);
18101 if (DiagID != diag::ext_mutable_reference) {
18102 Mutable = false;
18103 InvalidDecl = true;
18104 }
18105 }
18106 }
18107
18108 // C++11 [class.union]p8 (DR1460):
18109 // At most one variant member of a union may have a
18110 // brace-or-equal-initializer.
18111 if (InitStyle != ICIS_NoInit)
18112 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
18113
18114 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
18115 BitWidth, Mutable, InitStyle);
18116 if (InvalidDecl)
18117 NewFD->setInvalidDecl();
18118
18119 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
18120 Diag(Loc, diag::err_duplicate_member) << II;
18121 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
18122 NewFD->setInvalidDecl();
18123 }
18124
18125 if (!InvalidDecl && getLangOpts().CPlusPlus) {
18126 if (Record->isUnion()) {
18127 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18128 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
18129 if (RDecl->getDefinition()) {
18130 // C++ [class.union]p1: An object of a class with a non-trivial
18131 // constructor, a non-trivial copy constructor, a non-trivial
18132 // destructor, or a non-trivial copy assignment operator
18133 // cannot be a member of a union, nor can an array of such
18134 // objects.
18135 if (CheckNontrivialField(NewFD))
18136 NewFD->setInvalidDecl();
18137 }
18138 }
18139
18140 // C++ [class.union]p1: If a union contains a member of reference type,
18141 // the program is ill-formed, except when compiling with MSVC extensions
18142 // enabled.
18143 if (EltTy->isReferenceType()) {
18144 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
18145 diag::ext_union_member_of_reference_type :
18146 diag::err_union_member_of_reference_type)
18147 << NewFD->getDeclName() << EltTy;
18148 if (!getLangOpts().MicrosoftExt)
18149 NewFD->setInvalidDecl();
18150 }
18151 }
18152 }
18153
18154 // FIXME: We need to pass in the attributes given an AST
18155 // representation, not a parser representation.
18156 if (D) {
18157 // FIXME: The current scope is almost... but not entirely... correct here.
18158 ProcessDeclAttributes(getCurScope(), NewFD, *D);
18159
18160 if (NewFD->hasAttrs())
18161 CheckAlignasUnderalignment(NewFD);
18162 }
18163
18164 // In auto-retain/release, infer strong retension for fields of
18165 // retainable type.
18166 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
18167 NewFD->setInvalidDecl();
18168
18169 if (T.isObjCGCWeak())
18170 Diag(Loc, diag::warn_attribute_weak_on_field);
18171
18172 // PPC MMA non-pointer types are not allowed as field types.
18173 if (Context.getTargetInfo().getTriple().isPPC64() &&
18174 CheckPPCMMAType(T, NewFD->getLocation()))
18175 NewFD->setInvalidDecl();
18176
18177 NewFD->setAccess(AS);
18178 return NewFD;
18179}
18180
18181bool Sema::CheckNontrivialField(FieldDecl *FD) {
18182 assert(FD)(static_cast <bool> (FD) ? void (0) : __assert_fail ("FD"
, "clang/lib/Sema/SemaDecl.cpp", 18182, __extension__ __PRETTY_FUNCTION__
))
;
18183 assert(getLangOpts().CPlusPlus && "valid check only for C++")(static_cast <bool> (getLangOpts().CPlusPlus &&
"valid check only for C++") ? void (0) : __assert_fail ("getLangOpts().CPlusPlus && \"valid check only for C++\""
, "clang/lib/Sema/SemaDecl.cpp", 18183, __extension__ __PRETTY_FUNCTION__
))
;
18184
18185 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
18186 return false;
18187
18188 QualType EltTy = Context.getBaseElementType(FD->getType());
18189 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18190 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
18191 if (RDecl->getDefinition()) {
18192 // We check for copy constructors before constructors
18193 // because otherwise we'll never get complaints about
18194 // copy constructors.
18195
18196 CXXSpecialMember member = CXXInvalid;
18197 // We're required to check for any non-trivial constructors. Since the
18198 // implicit default constructor is suppressed if there are any
18199 // user-declared constructors, we just need to check that there is a
18200 // trivial default constructor and a trivial copy constructor. (We don't
18201 // worry about move constructors here, since this is a C++98 check.)
18202 if (RDecl->hasNonTrivialCopyConstructor())
18203 member = CXXCopyConstructor;
18204 else if (!RDecl->hasTrivialDefaultConstructor())
18205 member = CXXDefaultConstructor;
18206 else if (RDecl->hasNonTrivialCopyAssignment())
18207 member = CXXCopyAssignment;
18208 else if (RDecl->hasNonTrivialDestructor())
18209 member = CXXDestructor;
18210
18211 if (member != CXXInvalid) {
18212 if (!getLangOpts().CPlusPlus11 &&
18213 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
18214 // Objective-C++ ARC: it is an error to have a non-trivial field of
18215 // a union. However, system headers in Objective-C programs
18216 // occasionally have Objective-C lifetime objects within unions,
18217 // and rather than cause the program to fail, we make those
18218 // members unavailable.
18219 SourceLocation Loc = FD->getLocation();
18220 if (getSourceManager().isInSystemHeader(Loc)) {
18221 if (!FD->hasAttr<UnavailableAttr>())
18222 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
18223 UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
18224 return false;
18225 }
18226 }
18227
18228 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
18229 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
18230 diag::err_illegal_union_or_anon_struct_member)
18231 << FD->getParent()->isUnion() << FD->getDeclName() << member;
18232 DiagnoseNontrivial(RDecl, member);
18233 return !getLangOpts().CPlusPlus11;
18234 }
18235 }
18236 }
18237
18238 return false;
18239}
18240
18241/// TranslateIvarVisibility - Translate visibility from a token ID to an
18242/// AST enum value.
18243static ObjCIvarDecl::AccessControl
18244TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
18245 switch (ivarVisibility) {
18246 default: llvm_unreachable("Unknown visitibility kind")::llvm::llvm_unreachable_internal("Unknown visitibility kind"
, "clang/lib/Sema/SemaDecl.cpp", 18246)
;
18247 case tok::objc_private: return ObjCIvarDecl::Private;
18248 case tok::objc_public: return ObjCIvarDecl::Public;
18249 case tok::objc_protected: return ObjCIvarDecl::Protected;
18250 case tok::objc_package: return ObjCIvarDecl::Package;
18251 }
18252}
18253
18254/// ActOnIvar - Each ivar field of an objective-c class is passed into this
18255/// in order to create an IvarDecl object for it.
18256Decl *Sema::ActOnIvar(Scope *S,
18257 SourceLocation DeclStart,
18258 Declarator &D, Expr *BitfieldWidth,
18259 tok::ObjCKeywordKind Visibility) {
18260
18261 IdentifierInfo *II = D.getIdentifier();
18262 Expr *BitWidth = (Expr*)BitfieldWidth;
18263 SourceLocation Loc = DeclStart;
18264 if (II) Loc = D.getIdentifierLoc();
18265
18266 // FIXME: Unnamed fields can be handled in various different ways, for
18267 // example, unnamed unions inject all members into the struct namespace!
18268
18269 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
18270 QualType T = TInfo->getType();
18271
18272 if (BitWidth) {
18273 // 6.7.2.1p3, 6.7.2.1p4
18274 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
18275 if (!BitWidth)
18276 D.setInvalidType();
18277 } else {
18278 // Not a bitfield.
18279
18280 // validate II.
18281
18282 }
18283 if (T->isReferenceType()) {
18284 Diag(Loc, diag::err_ivar_reference_type);
18285 D.setInvalidType();
18286 }
18287 // C99 6.7.2.1p8: A member of a structure or union may have any type other
18288 // than a variably modified type.
18289 else if (T->isVariablyModifiedType()) {
18290 if (!tryToFixVariablyModifiedVarType(
18291 TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
18292 D.setInvalidType();
18293 }
18294
18295 // Get the visibility (access control) for this ivar.
18296 ObjCIvarDecl::AccessControl ac =
18297 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
18298 : ObjCIvarDecl::None;
18299 // Must set ivar's DeclContext to its enclosing interface.
18300 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
18301 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
18302 return nullptr;
18303 ObjCContainerDecl *EnclosingContext;
18304 if (ObjCImplementationDecl *IMPDecl =
18305 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
18306 if (LangOpts.ObjCRuntime.isFragile()) {
18307 // Case of ivar declared in an implementation. Context is that of its class.
18308 EnclosingContext = IMPDecl->getClassInterface();
18309 assert(EnclosingContext && "Implementation has no class interface!")(static_cast <bool> (EnclosingContext && "Implementation has no class interface!"
) ? void (0) : __assert_fail ("EnclosingContext && \"Implementation has no class interface!\""
, "clang/lib/Sema/SemaDecl.cpp", 18309, __extension__ __PRETTY_FUNCTION__
))
;
18310 }
18311 else
18312 EnclosingContext = EnclosingDecl;
18313 } else {
18314 if (ObjCCategoryDecl *CDecl =
18315 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
18316 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
18317 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
18318 return nullptr;
18319 }
18320 }
18321 EnclosingContext = EnclosingDecl;
18322 }
18323
18324 // Construct the decl.
18325 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
18326 DeclStart, Loc, II, T,
18327 TInfo, ac, (Expr *)BitfieldWidth);
18328
18329 if (II) {
18330 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
18331 ForVisibleRedeclaration);
18332 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
18333 && !isa<TagDecl>(PrevDecl)) {
18334 Diag(Loc, diag::err_duplicate_member) << II;
18335 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
18336 NewID->setInvalidDecl();
18337 }
18338 }
18339
18340 // Process attributes attached to the ivar.
18341 ProcessDeclAttributes(S, NewID, D);
18342
18343 if (D.isInvalidType())
18344 NewID->setInvalidDecl();
18345
18346 // In ARC, infer 'retaining' for ivars of retainable type.
18347 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
18348 NewID->setInvalidDecl();
18349
18350 if (D.getDeclSpec().isModulePrivateSpecified())
18351 NewID->setModulePrivate();
18352
18353 if (II) {
18354 // FIXME: When interfaces are DeclContexts, we'll need to add
18355 // these to the interface.
18356 S->AddDecl(NewID);
18357 IdResolver.AddDecl(NewID);
18358 }
18359
18360 if (LangOpts.ObjCRuntime.isNonFragile() &&
18361 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
18362 Diag(Loc, diag::warn_ivars_in_interface);
18363
18364 return NewID;
18365}
18366
18367/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
18368/// class and class extensions. For every class \@interface and class
18369/// extension \@interface, if the last ivar is a bitfield of any type,
18370/// then add an implicit `char :0` ivar to the end of that interface.
18371void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
18372 SmallVectorImpl<Decl *> &AllIvarDecls) {
18373 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
18374 return;
18375
18376 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
18377 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
18378
18379 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
18380 return;
18381 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
18382 if (!ID) {
18383 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
18384 if (!CD->IsClassExtension())
18385 return;
18386 }
18387 // No need to add this to end of @implementation.
18388 else
18389 return;
18390 }
18391 // All conditions are met. Add a new bitfield to the tail end of ivars.
18392 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
18393 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
18394
18395 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
18396 DeclLoc, DeclLoc, nullptr,
18397 Context.CharTy,
18398 Context.getTrivialTypeSourceInfo(Context.CharTy,
18399 DeclLoc),
18400 ObjCIvarDecl::Private, BW,
18401 true);
18402 AllIvarDecls.push_back(Ivar);
18403}
18404
18405/// [class.dtor]p4:
18406/// At the end of the definition of a class, overload resolution is
18407/// performed among the prospective destructors declared in that class with
18408/// an empty argument list to select the destructor for the class, also
18409/// known as the selected destructor.
18410///
18411/// We do the overload resolution here, then mark the selected constructor in the AST.
18412/// Later CXXRecordDecl::getDestructor() will return the selected constructor.
18413static void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record) {
18414 if (!Record->hasUserDeclaredDestructor()) {
18415 return;
18416 }
18417
18418 SourceLocation Loc = Record->getLocation();
18419 OverloadCandidateSet OCS(Loc, OverloadCandidateSet::CSK_Normal);
18420
18421 for (auto *Decl : Record->decls()) {
18422 if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {
18423 if (DD->isInvalidDecl())
18424 continue;
18425 S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},
18426 OCS);
18427 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.")(static_cast <bool> (DD->isIneligibleOrNotSelected()
&& "Selecting a destructor but a destructor was already selected."
) ? void (0) : __assert_fail ("DD->isIneligibleOrNotSelected() && \"Selecting a destructor but a destructor was already selected.\""
, "clang/lib/Sema/SemaDecl.cpp", 18427, __extension__ __PRETTY_FUNCTION__
))
;
18428 }
18429 }
18430
18431 if (OCS.empty()) {
18432 return;
18433 }
18434 OverloadCandidateSet::iterator Best;
18435 unsigned Msg = 0;
18436 OverloadCandidateDisplayKind DisplayKind;
18437
18438 switch (OCS.BestViableFunction(S, Loc, Best)) {
18439 case OR_Success:
18440 case OR_Deleted:
18441 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function));
18442 break;
18443
18444 case OR_Ambiguous:
18445 Msg = diag::err_ambiguous_destructor;
18446 DisplayKind = OCD_AmbiguousCandidates;
18447 break;
18448
18449 case OR_No_Viable_Function:
18450 Msg = diag::err_no_viable_destructor;
18451 DisplayKind = OCD_AllCandidates;
18452 break;
18453 }
18454
18455 if (Msg) {
18456 // OpenCL have got their own thing going with destructors. It's slightly broken,
18457 // but we allow it.
18458 if (!S.LangOpts.OpenCL) {
18459 PartialDiagnostic Diag = S.PDiag(Msg) << Record;
18460 OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {});
18461 Record->setInvalidDecl();
18462 }
18463 // It's a bit hacky: At this point we've raised an error but we want the
18464 // rest of the compiler to continue somehow working. However almost
18465 // everything we'll try to do with the class will depend on there being a
18466 // destructor. So let's pretend the first one is selected and hope for the
18467 // best.
18468 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function));
18469 }
18470}
18471
18472/// [class.mem.special]p5
18473/// Two special member functions are of the same kind if:
18474/// - they are both default constructors,
18475/// - they are both copy or move constructors with the same first parameter
18476/// type, or
18477/// - they are both copy or move assignment operators with the same first
18478/// parameter type and the same cv-qualifiers and ref-qualifier, if any.
18479static bool AreSpecialMemberFunctionsSameKind(ASTContext &Context,
18480 CXXMethodDecl *M1,
18481 CXXMethodDecl *M2,
18482 Sema::CXXSpecialMember CSM) {
18483 // We don't want to compare templates to non-templates: See
18484 // https://github.com/llvm/llvm-project/issues/59206
18485 if (CSM == Sema::CXXDefaultConstructor)
18486 return bool(M1->getDescribedFunctionTemplate()) ==
18487 bool(M2->getDescribedFunctionTemplate());
18488 if (!Context.hasSameType(M1->getParamDecl(0)->getType(),
18489 M2->getParamDecl(0)->getType()))
18490 return false;
18491 if (!Context.hasSameType(M1->getThisType(), M2->getThisType()))
18492 return false;
18493
18494 return true;
18495}
18496
18497/// [class.mem.special]p6:
18498/// An eligible special member function is a special member function for which:
18499/// - the function is not deleted,
18500/// - the associated constraints, if any, are satisfied, and
18501/// - no special member function of the same kind whose associated constraints
18502/// [CWG2595], if any, are satisfied is more constrained.
18503static void SetEligibleMethods(Sema &S, CXXRecordDecl *Record,
18504 ArrayRef<CXXMethodDecl *> Methods,
18505 Sema::CXXSpecialMember CSM) {
18506 SmallVector<bool, 4> SatisfactionStatus;
18507
18508 for (CXXMethodDecl *Method : Methods) {
18509 const Expr *Constraints = Method->getTrailingRequiresClause();
18510 if (!Constraints)
18511 SatisfactionStatus.push_back(true);
18512 else {
18513 ConstraintSatisfaction Satisfaction;
18514 if (S.CheckFunctionConstraints(Method, Satisfaction))
18515 SatisfactionStatus.push_back(false);
18516 else
18517 SatisfactionStatus.push_back(Satisfaction.IsSatisfied);
18518 }
18519 }
18520
18521 for (size_t i = 0; i < Methods.size(); i++) {
18522 if (!SatisfactionStatus[i])
18523 continue;
18524 CXXMethodDecl *Method = Methods[i];
18525 CXXMethodDecl *OrigMethod = Method;
18526 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
18527 OrigMethod = cast<CXXMethodDecl>(MF);
18528
18529 const Expr *Constraints = OrigMethod->getTrailingRequiresClause();
18530 bool AnotherMethodIsMoreConstrained = false;
18531 for (size_t j = 0; j < Methods.size(); j++) {
18532 if (i == j || !SatisfactionStatus[j])
18533 continue;
18534 CXXMethodDecl *OtherMethod = Methods[j];
18535 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
18536 OtherMethod = cast<CXXMethodDecl>(MF);
18537
18538 if (!AreSpecialMemberFunctionsSameKind(S.Context, OrigMethod, OtherMethod,
18539 CSM))
18540 continue;
18541
18542 const Expr *OtherConstraints = OtherMethod->getTrailingRequiresClause();
18543 if (!OtherConstraints)
18544 continue;
18545 if (!Constraints) {
18546 AnotherMethodIsMoreConstrained = true;
18547 break;
18548 }
18549 if (S.IsAtLeastAsConstrained(OtherMethod, {OtherConstraints}, OrigMethod,
18550 {Constraints},
18551 AnotherMethodIsMoreConstrained)) {
18552 // There was an error with the constraints comparison. Exit the loop
18553 // and don't consider this function eligible.
18554 AnotherMethodIsMoreConstrained = true;
18555 }
18556 if (AnotherMethodIsMoreConstrained)
18557 break;
18558 }
18559 // FIXME: Do not consider deleted methods as eligible after implementing
18560 // DR1734 and DR1496.
18561 if (!AnotherMethodIsMoreConstrained) {
18562 Method->setIneligibleOrNotSelected(false);
18563 Record->addedEligibleSpecialMemberFunction(Method, 1 << CSM);
18564 }
18565 }
18566}
18567
18568static void ComputeSpecialMemberFunctionsEligiblity(Sema &S,
18569 CXXRecordDecl *Record) {
18570 SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
18571 SmallVector<CXXMethodDecl *, 4> CopyConstructors;
18572 SmallVector<CXXMethodDecl *, 4> MoveConstructors;
18573 SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
18574 SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
18575
18576 for (auto *Decl : Record->decls()) {
18577 auto *MD = dyn_cast<CXXMethodDecl>(Decl);
18578 if (!MD) {
18579 auto *FTD = dyn_cast<FunctionTemplateDecl>(Decl);
18580 if (FTD)
18581 MD = dyn_cast<CXXMethodDecl>(FTD->getTemplatedDecl());
18582 }
18583 if (!MD)
18584 continue;
18585 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
18586 if (CD->isInvalidDecl())
18587 continue;
18588 if (CD->isDefaultConstructor())
18589 DefaultConstructors.push_back(MD);
18590 else if (CD->isCopyConstructor())
18591 CopyConstructors.push_back(MD);
18592 else if (CD->isMoveConstructor())
18593 MoveConstructors.push_back(MD);
18594 } else if (MD->isCopyAssignmentOperator()) {
18595 CopyAssignmentOperators.push_back(MD);
18596 } else if (MD->isMoveAssignmentOperator()) {
18597 MoveAssignmentOperators.push_back(MD);
18598 }
18599 }
18600
18601 SetEligibleMethods(S, Record, DefaultConstructors,
18602 Sema::CXXDefaultConstructor);
18603 SetEligibleMethods(S, Record, CopyConstructors, Sema::CXXCopyConstructor);
18604 SetEligibleMethods(S, Record, MoveConstructors, Sema::CXXMoveConstructor);
18605 SetEligibleMethods(S, Record, CopyAssignmentOperators,
18606 Sema::CXXCopyAssignment);
18607 SetEligibleMethods(S, Record, MoveAssignmentOperators,
18608 Sema::CXXMoveAssignment);
18609}
18610
18611void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
18612 ArrayRef<Decl *> Fields, SourceLocation LBrac,
18613 SourceLocation RBrac,
18614 const ParsedAttributesView &Attrs) {
18615 assert(EnclosingDecl && "missing record or interface decl")(static_cast <bool> (EnclosingDecl && "missing record or interface decl"
) ? void (0) : __assert_fail ("EnclosingDecl && \"missing record or interface decl\""
, "clang/lib/Sema/SemaDecl.cpp", 18615, __extension__ __PRETTY_FUNCTION__
))
;
18616
18617 // If this is an Objective-C @implementation or category and we have
18618 // new fields here we should reset the layout of the interface since
18619 // it will now change.
18620 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
18621 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
18622 switch (DC->getKind()) {
18623 default: break;
18624 case Decl::ObjCCategory:
18625 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
18626 break;
18627 case Decl::ObjCImplementation:
18628 Context.
18629 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
18630 break;
18631 }
18632 }
18633
18634 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
18635 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
18636
18637 // Start counting up the number of named members; make sure to include
18638 // members of anonymous structs and unions in the total.
18639 unsigned NumNamedMembers = 0;
18640 if (Record) {
18641 for (const auto *I : Record->decls()) {
18642 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
18643 if (IFD->getDeclName())
18644 ++NumNamedMembers;
18645 }
18646 }
18647
18648 // Verify that all the fields are okay.
18649 SmallVector<FieldDecl*, 32> RecFields;
18650
18651 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
18652 i != end; ++i) {
18653 FieldDecl *FD = cast<FieldDecl>(*i);
18654
18655 // Get the type for the field.
18656 const Type *FDTy = FD->getType().getTypePtr();
18657
18658 if (!FD->isAnonymousStructOrUnion()) {
18659 // Remember all fields written by the user.
18660 RecFields.push_back(FD);
18661 }
18662
18663 // If the field is already invalid for some reason, don't emit more
18664 // diagnostics about it.
18665 if (FD->isInvalidDecl()) {
18666 EnclosingDecl->setInvalidDecl();
18667 continue;
18668 }
18669
18670 // C99 6.7.2.1p2:
18671 // A structure or union shall not contain a member with
18672 // incomplete or function type (hence, a structure shall not
18673 // contain an instance of itself, but may contain a pointer to
18674 // an instance of itself), except that the last member of a
18675 // structure with more than one named member may have incomplete
18676 // array type; such a structure (and any union containing,
18677 // possibly recursively, a member that is such a structure)
18678 // shall not be a member of a structure or an element of an
18679 // array.
18680 bool IsLastField = (i + 1 == Fields.end());
18681 if (FDTy->isFunctionType()) {
18682 // Field declared as a function.
18683 Diag(FD->getLocation(), diag::err_field_declared_as_function)
18684 << FD->getDeclName();
18685 FD->setInvalidDecl();
18686 EnclosingDecl->setInvalidDecl();
18687 continue;
18688 } else if (FDTy->isIncompleteArrayType() &&
18689 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
18690 if (Record) {
18691 // Flexible array member.
18692 // Microsoft and g++ is more permissive regarding flexible array.
18693 // It will accept flexible array in union and also
18694 // as the sole element of a struct/class.
18695 unsigned DiagID = 0;
18696 if (!Record->isUnion() && !IsLastField) {
18697 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
18698 << FD->getDeclName() << FD->getType() << Record->getTagKind();
18699 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
18700 FD->setInvalidDecl();
18701 EnclosingDecl->setInvalidDecl();
18702 continue;
18703 } else if (Record->isUnion())
18704 DiagID = getLangOpts().MicrosoftExt
18705 ? diag::ext_flexible_array_union_ms
18706 : getLangOpts().CPlusPlus
18707 ? diag::ext_flexible_array_union_gnu
18708 : diag::err_flexible_array_union;
18709 else if (NumNamedMembers < 1)
18710 DiagID = getLangOpts().MicrosoftExt
18711 ? diag::ext_flexible_array_empty_aggregate_ms
18712 : getLangOpts().CPlusPlus
18713 ? diag::ext_flexible_array_empty_aggregate_gnu
18714 : diag::err_flexible_array_empty_aggregate;
18715
18716 if (DiagID)
18717 Diag(FD->getLocation(), DiagID) << FD->getDeclName()
18718 << Record->getTagKind();
18719 // While the layout of types that contain virtual bases is not specified
18720 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
18721 // virtual bases after the derived members. This would make a flexible
18722 // array member declared at the end of an object not adjacent to the end
18723 // of the type.
18724 if (CXXRecord && CXXRecord->getNumVBases() != 0)
18725 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
18726 << FD->getDeclName() << Record->getTagKind();
18727 if (!getLangOpts().C99)
18728 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
18729 << FD->getDeclName() << Record->getTagKind();
18730
18731 // If the element type has a non-trivial destructor, we would not
18732 // implicitly destroy the elements, so disallow it for now.
18733 //
18734 // FIXME: GCC allows this. We should probably either implicitly delete
18735 // the destructor of the containing class, or just allow this.
18736 QualType BaseElem = Context.getBaseElementType(FD->getType());
18737 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
18738 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
18739 << FD->getDeclName() << FD->getType();
18740 FD->setInvalidDecl();
18741 EnclosingDecl->setInvalidDecl();
18742 continue;
18743 }
18744 // Okay, we have a legal flexible array member at the end of the struct.
18745 Record->setHasFlexibleArrayMember(true);
18746 } else {
18747 // In ObjCContainerDecl ivars with incomplete array type are accepted,
18748 // unless they are followed by another ivar. That check is done
18749 // elsewhere, after synthesized ivars are known.
18750 }
18751 } else if (!FDTy->isDependentType() &&
18752 RequireCompleteSizedType(
18753 FD->getLocation(), FD->getType(),
18754 diag::err_field_incomplete_or_sizeless)) {
18755 // Incomplete type
18756 FD->setInvalidDecl();
18757 EnclosingDecl->setInvalidDecl();
18758 continue;
18759 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
18760 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
18761 // A type which contains a flexible array member is considered to be a
18762 // flexible array member.
18763 Record->setHasFlexibleArrayMember(true);
18764 if (!Record->isUnion()) {
18765 // If this is a struct/class and this is not the last element, reject
18766 // it. Note that GCC supports variable sized arrays in the middle of
18767 // structures.
18768 if (!IsLastField)
18769 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
18770 << FD->getDeclName() << FD->getType();
18771 else {
18772 // We support flexible arrays at the end of structs in
18773 // other structs as an extension.
18774 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
18775 << FD->getDeclName();
18776 }
18777 }
18778 }
18779 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
18780 RequireNonAbstractType(FD->getLocation(), FD->getType(),
18781 diag::err_abstract_type_in_decl,
18782 AbstractIvarType)) {
18783 // Ivars can not have abstract class types
18784 FD->setInvalidDecl();
18785 }
18786 if (Record && FDTTy->getDecl()->hasObjectMember())
18787 Record->setHasObjectMember(true);
18788 if (Record && FDTTy->getDecl()->hasVolatileMember())
18789 Record->setHasVolatileMember(true);
18790 } else if (FDTy->isObjCObjectType()) {
18791 /// A field cannot be an Objective-c object
18792 Diag(FD->getLocation(), diag::err_statically_allocated_object)
18793 << FixItHint::CreateInsertion(FD->getLocation(), "*");
18794 QualType T = Context.getObjCObjectPointerType(FD->getType());
18795 FD->setType(T);
18796 } else if (Record && Record->isUnion() &&
18797 FD->getType().hasNonTrivialObjCLifetime() &&
18798 getSourceManager().isInSystemHeader(FD->getLocation()) &&
18799 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
18800 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
18801 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
18802 // For backward compatibility, fields of C unions declared in system
18803 // headers that have non-trivial ObjC ownership qualifications are marked
18804 // as unavailable unless the qualifier is explicit and __strong. This can
18805 // break ABI compatibility between programs compiled with ARC and MRR, but
18806 // is a better option than rejecting programs using those unions under
18807 // ARC.
18808 FD->addAttr(UnavailableAttr::CreateImplicit(
18809 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
18810 FD->getLocation()));
18811 } else if (getLangOpts().ObjC &&
18812 getLangOpts().getGC() != LangOptions::NonGC && Record &&
18813 !Record->hasObjectMember()) {
18814 if (FD->getType()->isObjCObjectPointerType() ||
18815 FD->getType().isObjCGCStrong())
18816 Record->setHasObjectMember(true);
18817 else if (Context.getAsArrayType(FD->getType())) {
18818 QualType BaseType = Context.getBaseElementType(FD->getType());
18819 if (BaseType->isRecordType() &&
18820 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
18821 Record->setHasObjectMember(true);
18822 else if (BaseType->isObjCObjectPointerType() ||
18823 BaseType.isObjCGCStrong())
18824 Record->setHasObjectMember(true);
18825 }
18826 }
18827
18828 if (Record && !getLangOpts().CPlusPlus &&
18829 !shouldIgnoreForRecordTriviality(FD)) {
18830 QualType FT = FD->getType();
18831 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
18832 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
18833 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
18834 Record->isUnion())
18835 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
18836 }
18837 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
18838 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
18839 Record->setNonTrivialToPrimitiveCopy(true);
18840 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
18841 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
18842 }
18843 if (FT.isDestructedType()) {
18844 Record->setNonTrivialToPrimitiveDestroy(true);
18845 Record->setParamDestroyedInCallee(true);
18846 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
18847 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
18848 }
18849
18850 if (const auto *RT = FT->getAs<RecordType>()) {
18851 if (RT->getDecl()->getArgPassingRestrictions() ==
18852 RecordDecl::APK_CanNeverPassInRegs)
18853 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
18854 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
18855 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
18856 }
18857
18858 if (Record && FD->getType().isVolatileQualified())
18859 Record->setHasVolatileMember(true);
18860 // Keep track of the number of named members.
18861 if (FD->getIdentifier())
18862 ++NumNamedMembers;
18863 }
18864
18865 // Okay, we successfully defined 'Record'.
18866 if (Record) {
18867 bool Completed = false;
18868 if (CXXRecord) {
18869 if (!CXXRecord->isInvalidDecl()) {
18870 // Set access bits correctly on the directly-declared conversions.
18871 for (CXXRecordDecl::conversion_iterator
18872 I = CXXRecord->conversion_begin(),
18873 E = CXXRecord->conversion_end(); I != E; ++I)
18874 I.setAccess((*I)->getAccess());
18875 }
18876
18877 // Add any implicitly-declared members to this class.
18878 AddImplicitlyDeclaredMembersToClass(CXXRecord);
18879
18880 if (!CXXRecord->isDependentType()) {
18881 if (!CXXRecord->isInvalidDecl()) {
18882 // If we have virtual base classes, we may end up finding multiple
18883 // final overriders for a given virtual function. Check for this
18884 // problem now.
18885 if (CXXRecord->getNumVBases()) {
18886 CXXFinalOverriderMap FinalOverriders;
18887 CXXRecord->getFinalOverriders(FinalOverriders);
18888
18889 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
18890 MEnd = FinalOverriders.end();
18891 M != MEnd; ++M) {
18892 for (OverridingMethods::iterator SO = M->second.begin(),
18893 SOEnd = M->second.end();
18894 SO != SOEnd; ++SO) {
18895 assert(SO->second.size() > 0 &&(static_cast <bool> (SO->second.size() > 0 &&
"Virtual function without overriding functions?") ? void (0)
: __assert_fail ("SO->second.size() > 0 && \"Virtual function without overriding functions?\""
, "clang/lib/Sema/SemaDecl.cpp", 18896, __extension__ __PRETTY_FUNCTION__
))
18896 "Virtual function without overriding functions?")(static_cast <bool> (SO->second.size() > 0 &&
"Virtual function without overriding functions?") ? void (0)
: __assert_fail ("SO->second.size() > 0 && \"Virtual function without overriding functions?\""
, "clang/lib/Sema/SemaDecl.cpp", 18896, __extension__ __PRETTY_FUNCTION__
))
;
18897 if (SO->second.size() == 1)
18898 continue;
18899
18900 // C++ [class.virtual]p2:
18901 // In a derived class, if a virtual member function of a base
18902 // class subobject has more than one final overrider the
18903 // program is ill-formed.
18904 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
18905 << (const NamedDecl *)M->first << Record;
18906 Diag(M->first->getLocation(),
18907 diag::note_overridden_virtual_function);
18908 for (OverridingMethods::overriding_iterator
18909 OM = SO->second.begin(),
18910 OMEnd = SO->second.end();
18911 OM != OMEnd; ++OM)
18912 Diag(OM->Method->getLocation(), diag::note_final_overrider)
18913 << (const NamedDecl *)M->first << OM->Method->getParent();
18914
18915 Record->setInvalidDecl();
18916 }
18917 }
18918 CXXRecord->completeDefinition(&FinalOverriders);
18919 Completed = true;
18920 }
18921 }
18922 ComputeSelectedDestructor(*this, CXXRecord);
18923 ComputeSpecialMemberFunctionsEligiblity(*this, CXXRecord);
18924 }
18925 }
18926
18927 if (!Completed)
18928 Record->completeDefinition();
18929
18930 // Handle attributes before checking the layout.
18931 ProcessDeclAttributeList(S, Record, Attrs);
18932
18933 // Check to see if a FieldDecl is a pointer to a function.
18934 auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
18935 const FieldDecl *FD = dyn_cast<FieldDecl>(D);
18936 if (!FD) {
18937 // Check whether this is a forward declaration that was inserted by
18938 // Clang. This happens when a non-forward declared / defined type is
18939 // used, e.g.:
18940 //
18941 // struct foo {
18942 // struct bar *(*f)();
18943 // struct bar *(*g)();
18944 // };
18945 //
18946 // "struct bar" shows up in the decl AST as a "RecordDecl" with an
18947 // incomplete definition.
18948 if (const auto *TD = dyn_cast<TagDecl>(D))
18949 return !TD->isCompleteDefinition();
18950 return false;
18951 }
18952 QualType FieldType = FD->getType().getDesugaredType(Context);
18953 if (isa<PointerType>(FieldType)) {
18954 QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();
18955 return PointeeType.getDesugaredType(Context)->isFunctionType();
18956 }
18957 return false;
18958 };
18959
18960 // Maybe randomize the record's decls. We automatically randomize a record
18961 // of function pointers, unless it has the "no_randomize_layout" attribute.
18962 if (!getLangOpts().CPlusPlus &&
18963 (Record->hasAttr<RandomizeLayoutAttr>() ||
18964 (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
18965 llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl))) &&
18966 !Record->isUnion() && !getLangOpts().RandstructSeed.empty() &&
18967 !Record->isRandomized()) {
18968 SmallVector<Decl *, 32> NewDeclOrdering;
18969 if (randstruct::randomizeStructureLayout(Context, Record,
18970 NewDeclOrdering))
18971 Record->reorderDecls(NewDeclOrdering);
18972 }
18973
18974 // We may have deferred checking for a deleted destructor. Check now.
18975 if (CXXRecord) {
18976 auto *Dtor = CXXRecord->getDestructor();
18977 if (Dtor && Dtor->isImplicit() &&
18978 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
18979 CXXRecord->setImplicitDestructorIsDeleted();
18980 SetDeclDeleted(Dtor, CXXRecord->getLocation());
18981 }
18982 }
18983
18984 if (Record->hasAttrs()) {
18985 CheckAlignasUnderalignment(Record);
18986
18987 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
18988 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
18989 IA->getRange(), IA->getBestCase(),
18990 IA->getInheritanceModel());
18991 }
18992
18993 // Check if the structure/union declaration is a type that can have zero
18994 // size in C. For C this is a language extension, for C++ it may cause
18995 // compatibility problems.
18996 bool CheckForZeroSize;
18997 if (!getLangOpts().CPlusPlus) {
18998 CheckForZeroSize = true;
18999 } else {
19000 // For C++ filter out types that cannot be referenced in C code.
19001 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
19002 CheckForZeroSize =
19003 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
19004 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
19005 CXXRecord->isCLike();
19006 }
19007 if (CheckForZeroSize) {
19008 bool ZeroSize = true;
19009 bool IsEmpty = true;
19010 unsigned NonBitFields = 0;
19011 for (RecordDecl::field_iterator I = Record->field_begin(),
19012 E = Record->field_end();
19013 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
19014 IsEmpty = false;
19015 if (I->isUnnamedBitfield()) {
19016 if (!I->isZeroLengthBitField(Context))
19017 ZeroSize = false;
19018 } else {
19019 ++NonBitFields;
19020 QualType FieldType = I->getType();
19021 if (FieldType->isIncompleteType() ||
19022 !Context.getTypeSizeInChars(FieldType).isZero())
19023 ZeroSize = false;
19024 }
19025 }
19026
19027 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
19028 // allowed in C++, but warn if its declaration is inside
19029 // extern "C" block.
19030 if (ZeroSize) {
19031 Diag(RecLoc, getLangOpts().CPlusPlus ?
19032 diag::warn_zero_size_struct_union_in_extern_c :
19033 diag::warn_zero_size_struct_union_compat)
19034 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
19035 }
19036
19037 // Structs without named members are extension in C (C99 6.7.2.1p7),
19038 // but are accepted by GCC.
19039 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
19040 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
19041 diag::ext_no_named_members_in_struct_union)
19042 << Record->isUnion();
19043 }
19044 }
19045 } else {
19046 ObjCIvarDecl **ClsFields =
19047 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
19048 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
19049 ID->setEndOfDefinitionLoc(RBrac);
19050 // Add ivar's to class's DeclContext.
19051 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19052 ClsFields[i]->setLexicalDeclContext(ID);
19053 ID->addDecl(ClsFields[i]);
19054 }
19055 // Must enforce the rule that ivars in the base classes may not be
19056 // duplicates.
19057 if (ID->getSuperClass())
19058 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
19059 } else if (ObjCImplementationDecl *IMPDecl =
19060 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
19061 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl")(static_cast <bool> (IMPDecl && "ActOnFields - missing ObjCImplementationDecl"
) ? void (0) : __assert_fail ("IMPDecl && \"ActOnFields - missing ObjCImplementationDecl\""
, "clang/lib/Sema/SemaDecl.cpp", 19061, __extension__ __PRETTY_FUNCTION__
))
;
19062 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
19063 // Ivar declared in @implementation never belongs to the implementation.
19064 // Only it is in implementation's lexical context.
19065 ClsFields[I]->setLexicalDeclContext(IMPDecl);
19066 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
19067 IMPDecl->setIvarLBraceLoc(LBrac);
19068 IMPDecl->setIvarRBraceLoc(RBrac);
19069 } else if (ObjCCategoryDecl *CDecl =
19070 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
19071 // case of ivars in class extension; all other cases have been
19072 // reported as errors elsewhere.
19073 // FIXME. Class extension does not have a LocEnd field.
19074 // CDecl->setLocEnd(RBrac);
19075 // Add ivar's to class extension's DeclContext.
19076 // Diagnose redeclaration of private ivars.
19077 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
19078 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19079 if (IDecl) {
19080 if (const ObjCIvarDecl *ClsIvar =
19081 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
19082 Diag(ClsFields[i]->getLocation(),
19083 diag::err_duplicate_ivar_declaration);
19084 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
19085 continue;
19086 }
19087 for (const auto *Ext : IDecl->known_extensions()) {
19088 if (const ObjCIvarDecl *ClsExtIvar
19089 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
19090 Diag(ClsFields[i]->getLocation(),
19091 diag::err_duplicate_ivar_declaration);
19092 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
19093 continue;
19094 }
19095 }
19096 }
19097 ClsFields[i]->setLexicalDeclContext(CDecl);
19098 CDecl->addDecl(ClsFields[i]);
19099 }
19100 CDecl->setIvarLBraceLoc(LBrac);
19101 CDecl->setIvarRBraceLoc(RBrac);
19102 }
19103 }
19104}
19105
19106/// Determine whether the given integral value is representable within
19107/// the given type T.
19108static bool isRepresentableIntegerValue(ASTContext &Context,
19109 llvm::APSInt &Value,
19110 QualType T) {
19111 assert((T->isIntegralType(Context) || T->isEnumeralType()) &&(static_cast <bool> ((T->isIntegralType(Context) || T
->isEnumeralType()) && "Integral type required!") ?
void (0) : __assert_fail ("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\""
, "clang/lib/Sema/SemaDecl.cpp", 19112, __extension__ __PRETTY_FUNCTION__
))
19112 "Integral type required!")(static_cast <bool> ((T->isIntegralType(Context) || T
->isEnumeralType()) && "Integral type required!") ?
void (0) : __assert_fail ("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\""
, "clang/lib/Sema/SemaDecl.cpp", 19112, __extension__ __PRETTY_FUNCTION__
))
;
19113 unsigned BitWidth = Context.getIntWidth(T);
19114
19115 if (Value.isUnsigned() || Value.isNonNegative()) {
19116 if (T->isSignedIntegerOrEnumerationType())
19117 --BitWidth;
19118 return Value.getActiveBits() <= BitWidth;
19119 }
19120 return Value.getSignificantBits() <= BitWidth;
19121}
19122
19123// Given an integral type, return the next larger integral type
19124// (or a NULL type of no such type exists).
19125static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
19126 // FIXME: Int128/UInt128 support, which also needs to be introduced into
19127 // enum checking below.
19128 assert((T->isIntegralType(Context) ||(static_cast <bool> ((T->isIntegralType(Context) || T
->isEnumeralType()) && "Integral type required!") ?
void (0) : __assert_fail ("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\""
, "clang/lib/Sema/SemaDecl.cpp", 19129, __extension__ __PRETTY_FUNCTION__
))
19129 T->isEnumeralType()) && "Integral type required!")(static_cast <bool> ((T->isIntegralType(Context) || T
->isEnumeralType()) && "Integral type required!") ?
void (0) : __assert_fail ("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\""
, "clang/lib/Sema/SemaDecl.cpp", 19129, __extension__ __PRETTY_FUNCTION__
))
;
19130 const unsigned NumTypes = 4;
19131 QualType SignedIntegralTypes[NumTypes] = {
19132 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
19133 };
19134 QualType UnsignedIntegralTypes[NumTypes] = {
19135 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
19136 Context.UnsignedLongLongTy
19137 };
19138
19139 unsigned BitWidth = Context.getTypeSize(T);
19140 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
19141 : UnsignedIntegralTypes;
19142 for (unsigned I = 0; I != NumTypes; ++I)
19143 if (Context.getTypeSize(Types[I]) > BitWidth)
19144 return Types[I];
19145
19146 return QualType();
19147}
19148
19149EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
19150 EnumConstantDecl *LastEnumConst,
19151 SourceLocation IdLoc,
19152 IdentifierInfo *Id,
19153 Expr *Val) {
19154 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
19155 llvm::APSInt EnumVal(IntWidth);
19156 QualType EltTy;
19157
19158 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
19159 Val = nullptr;
19160
19161 if (Val)
19162 Val = DefaultLvalueConversion(Val).get();
19163
19164 if (Val) {
19165 if (Enum->isDependentType() || Val->isTypeDependent() ||
19166 Val->containsErrors())
19167 EltTy = Context.DependentTy;
19168 else {
19169 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
19170 // underlying type, but do allow it in all other contexts.
19171 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
19172 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
19173 // constant-expression in the enumerator-definition shall be a converted
19174 // constant expression of the underlying type.
19175 EltTy = Enum->getIntegerType();
19176 ExprResult Converted =
19177 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
19178 CCEK_Enumerator);
19179 if (Converted.isInvalid())
19180 Val = nullptr;
19181 else
19182 Val = Converted.get();
19183 } else if (!Val->isValueDependent() &&
19184 !(Val =
19185 VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
19186 .get())) {
19187 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
19188 } else {
19189 if (Enum->isComplete()) {
19190 EltTy = Enum->getIntegerType();
19191
19192 // In Obj-C and Microsoft mode, require the enumeration value to be
19193 // representable in the underlying type of the enumeration. In C++11,
19194 // we perform a non-narrowing conversion as part of converted constant
19195 // expression checking.
19196 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
19197 if (Context.getTargetInfo()
19198 .getTriple()
19199 .isWindowsMSVCEnvironment()) {
19200 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
19201 } else {
19202 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
19203 }
19204 }
19205
19206 // Cast to the underlying type.
19207 Val = ImpCastExprToType(Val, EltTy,
19208 EltTy->isBooleanType() ? CK_IntegralToBoolean
19209 : CK_IntegralCast)
19210 .get();
19211 } else if (getLangOpts().CPlusPlus) {
19212 // C++11 [dcl.enum]p5:
19213 // If the underlying type is not fixed, the type of each enumerator
19214 // is the type of its initializing value:
19215 // - If an initializer is specified for an enumerator, the
19216 // initializing value has the same type as the expression.
19217 EltTy = Val->getType();
19218 } else {
19219 // C99 6.7.2.2p2:
19220 // The expression that defines the value of an enumeration constant
19221 // shall be an integer constant expression that has a value
19222 // representable as an int.
19223
19224 // Complain if the value is not representable in an int.
19225 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
19226 Diag(IdLoc, diag::ext_enum_value_not_int)
19227 << toString(EnumVal, 10) << Val->getSourceRange()
19228 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
19229 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
19230 // Force the type of the expression to 'int'.
19231 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
19232 }
19233 EltTy = Val->getType();
19234 }
19235 }
19236 }
19237 }
19238
19239 if (!Val) {
19240 if (Enum->isDependentType())
19241 EltTy = Context.DependentTy;
19242 else if (!LastEnumConst) {
19243 // C++0x [dcl.enum]p5:
19244 // If the underlying type is not fixed, the type of each enumerator
19245 // is the type of its initializing value:
19246 // - If no initializer is specified for the first enumerator, the
19247 // initializing value has an unspecified integral type.
19248 //
19249 // GCC uses 'int' for its unspecified integral type, as does
19250 // C99 6.7.2.2p3.
19251 if (Enum->isFixed()) {
19252 EltTy = Enum->getIntegerType();
19253 }
19254 else {
19255 EltTy = Context.IntTy;
19256 }
19257 } else {
19258 // Assign the last value + 1.
19259 EnumVal = LastEnumConst->getInitVal();
19260 ++EnumVal;
19261 EltTy = LastEnumConst->getType();
19262
19263 // Check for overflow on increment.
19264 if (EnumVal < LastEnumConst->getInitVal()) {
19265 // C++0x [dcl.enum]p5:
19266 // If the underlying type is not fixed, the type of each enumerator
19267 // is the type of its initializing value:
19268 //
19269 // - Otherwise the type of the initializing value is the same as
19270 // the type of the initializing value of the preceding enumerator
19271 // unless the incremented value is not representable in that type,
19272 // in which case the type is an unspecified integral type
19273 // sufficient to contain the incremented value. If no such type
19274 // exists, the program is ill-formed.
19275 QualType T = getNextLargerIntegralType(Context, EltTy);
19276 if (T.isNull() || Enum->isFixed()) {
19277 // There is no integral type larger enough to represent this
19278 // value. Complain, then allow the value to wrap around.
19279 EnumVal = LastEnumConst->getInitVal();
19280 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
19281 ++EnumVal;
19282 if (Enum->isFixed())
19283 // When the underlying type is fixed, this is ill-formed.
19284 Diag(IdLoc, diag::err_enumerator_wrapped)
19285 << toString(EnumVal, 10)
19286 << EltTy;
19287 else
19288 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
19289 << toString(EnumVal, 10);
19290 } else {
19291 EltTy = T;
19292 }
19293
19294 // Retrieve the last enumerator's value, extent that type to the
19295 // type that is supposed to be large enough to represent the incremented
19296 // value, then increment.
19297 EnumVal = LastEnumConst->getInitVal();
19298 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
19299 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
19300 ++EnumVal;
19301
19302 // If we're not in C++, diagnose the overflow of enumerator values,
19303 // which in C99 means that the enumerator value is not representable in
19304 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
19305 // permits enumerator values that are representable in some larger
19306 // integral type.
19307 if (!getLangOpts().CPlusPlus && !T.isNull())
19308 Diag(IdLoc, diag::warn_enum_value_overflow);
19309 } else if (!getLangOpts().CPlusPlus &&
19310 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
19311 // Enforce C99 6.7.2.2p2 even when we compute the next value.
19312 Diag(IdLoc, diag::ext_enum_value_not_int)
19313 << toString(EnumVal, 10) << 1;
19314 }
19315 }
19316 }
19317
19318 if (!EltTy->isDependentType()) {
19319 // Make the enumerator value match the signedness and size of the
19320 // enumerator's type.
19321 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
19322 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
19323 }
19324
19325 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
19326 Val, EnumVal);
19327}
19328
19329Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
19330 SourceLocation IILoc) {
19331 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
19332 !getLangOpts().CPlusPlus)
19333 return SkipBodyInfo();
19334
19335 // We have an anonymous enum definition. Look up the first enumerator to
19336 // determine if we should merge the definition with an existing one and
19337 // skip the body.
19338 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
19339 forRedeclarationInCurContext());
19340 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
19341 if (!PrevECD)
19342 return SkipBodyInfo();
19343
19344 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
19345 NamedDecl *Hidden;
19346 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
19347 SkipBodyInfo Skip;
19348 Skip.Previous = Hidden;
19349 return Skip;
19350 }
19351
19352 return SkipBodyInfo();
19353}
19354
19355Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
19356 SourceLocation IdLoc, IdentifierInfo *Id,
19357 const ParsedAttributesView &Attrs,
19358 SourceLocation EqualLoc, Expr *Val) {
19359 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
19360 EnumConstantDecl *LastEnumConst =
19361 cast_or_null<EnumConstantDecl>(lastEnumConst);
19362
19363 // The scope passed in may not be a decl scope. Zip up the scope tree until
19364 // we find one that is.
19365 S = getNonFieldDeclScope(S);
19366
19367 // Verify that there isn't already something declared with this name in this
19368 // scope.
19369 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
19370 LookupName(R, S);
19371 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
19372
19373 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19374 // Maybe we will complain about the shadowed template parameter.
19375 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
19376 // Just pretend that we didn't see the previous declaration.
19377 PrevDecl = nullptr;
19378 }
19379
19380 // C++ [class.mem]p15:
19381 // If T is the name of a class, then each of the following shall have a name
19382 // different from T:
19383 // - every enumerator of every member of class T that is an unscoped
19384 // enumerated type
19385 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
19386 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
19387 DeclarationNameInfo(Id, IdLoc));
19388
19389 EnumConstantDecl *New =
19390 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
19391 if (!New)
19392 return nullptr;
19393
19394 if (PrevDecl) {
19395 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
19396 // Check for other kinds of shadowing not already handled.
19397 CheckShadow(New, PrevDecl, R);
19398 }
19399
19400 // When in C++, we may get a TagDecl with the same name; in this case the
19401 // enum constant will 'hide' the tag.
19402 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&(static_cast <bool> ((getLangOpts().CPlusPlus || !isa<
TagDecl>(PrevDecl)) && "Received TagDecl when not in C++!"
) ? void (0) : __assert_fail ("(getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && \"Received TagDecl when not in C++!\""
, "clang/lib/Sema/SemaDecl.cpp", 19403, __extension__ __PRETTY_FUNCTION__
))
19403 "Received TagDecl when not in C++!")(static_cast <bool> ((getLangOpts().CPlusPlus || !isa<
TagDecl>(PrevDecl)) && "Received TagDecl when not in C++!"
) ? void (0) : __assert_fail ("(getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && \"Received TagDecl when not in C++!\""
, "clang/lib/Sema/SemaDecl.cpp", 19403, __extension__ __PRETTY_FUNCTION__
))
;
19404 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
19405 if (isa<EnumConstantDecl>(PrevDecl))
19406 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
19407 else
19408 Diag(IdLoc, diag::err_redefinition) << Id;
19409 notePreviousDefinition(PrevDecl, IdLoc);
19410 return nullptr;
19411 }
19412 }
19413
19414 // Process attributes.
19415 ProcessDeclAttributeList(S, New, Attrs);
19416 AddPragmaAttributes(S, New);
19417
19418 // Register this decl in the current scope stack.
19419 New->setAccess(TheEnumDecl->getAccess());
19420 PushOnScopeChains(New, S);
19421
19422 ActOnDocumentableDecl(New);
19423
19424 return New;
19425}
19426
19427// Returns true when the enum initial expression does not trigger the
19428// duplicate enum warning. A few common cases are exempted as follows:
19429// Element2 = Element1
19430// Element2 = Element1 + 1
19431// Element2 = Element1 - 1
19432// Where Element2 and Element1 are from the same enum.
19433static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
19434 Expr *InitExpr = ECD->getInitExpr();
19435 if (!InitExpr)
19436 return true;
19437 InitExpr = InitExpr->IgnoreImpCasts();
19438
19439 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
19440 if (!BO->isAdditiveOp())
19441 return true;
19442 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
19443 if (!IL)
19444 return true;
19445 if (IL->getValue() != 1)
19446 return true;
19447
19448 InitExpr = BO->getLHS();
19449 }
19450
19451 // This checks if the elements are from the same enum.
19452 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
19453 if (!DRE)
19454 return true;
19455
19456 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
19457 if (!EnumConstant)
19458 return true;
19459
19460 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
19461 Enum)
19462 return true;
19463
19464 return false;
19465}
19466
19467// Emits a warning when an element is implicitly set a value that
19468// a previous element has already been set to.
19469static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
19470 EnumDecl *Enum, QualType EnumType) {
19471 // Avoid anonymous enums
19472 if (!Enum->getIdentifier())
19473 return;
19474
19475 // Only check for small enums.
19476 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
19477 return;
19478
19479 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
19480 return;
19481
19482 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
19483 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
19484
19485 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
19486
19487 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
19488 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
19489
19490 // Use int64_t as a key to avoid needing special handling for map keys.
19491 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
19492 llvm::APSInt Val = D->getInitVal();
19493 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
19494 };
19495
19496 DuplicatesVector DupVector;
19497 ValueToVectorMap EnumMap;
19498
19499 // Populate the EnumMap with all values represented by enum constants without
19500 // an initializer.
19501 for (auto *Element : Elements) {
19502 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
19503
19504 // Null EnumConstantDecl means a previous diagnostic has been emitted for
19505 // this constant. Skip this enum since it may be ill-formed.
19506 if (!ECD) {
19507 return;
19508 }
19509
19510 // Constants with initalizers are handled in the next loop.
19511 if (ECD->getInitExpr())
19512 continue;
19513
19514 // Duplicate values are handled in the next loop.
19515 EnumMap.insert({EnumConstantToKey(ECD), ECD});
19516 }
19517
19518 if (EnumMap.size() == 0)
19519 return;
19520
19521 // Create vectors for any values that has duplicates.
19522 for (auto *Element : Elements) {
19523 // The last loop returned if any constant was null.
19524 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
19525 if (!ValidDuplicateEnum(ECD, Enum))
19526 continue;
19527
19528 auto Iter = EnumMap.find(EnumConstantToKey(ECD));
19529 if (Iter == EnumMap.end())
19530 continue;
19531
19532 DeclOrVector& Entry = Iter->second;
19533 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
19534 // Ensure constants are different.
19535 if (D == ECD)
19536 continue;
19537
19538 // Create new vector and push values onto it.
19539 auto Vec = std::make_unique<ECDVector>();
19540 Vec->push_back(D);
19541 Vec->push_back(ECD);
19542
19543 // Update entry to point to the duplicates vector.
19544 Entry = Vec.get();
19545
19546 // Store the vector somewhere we can consult later for quick emission of
19547 // diagnostics.
19548 DupVector.emplace_back(std::move(Vec));
19549 continue;
19550 }
19551
19552 ECDVector *Vec = Entry.get<ECDVector*>();
19553 // Make sure constants are not added more than once.
19554 if (*Vec->begin() == ECD)
19555 continue;
19556
19557 Vec->push_back(ECD);
19558 }
19559
19560 // Emit diagnostics.
19561 for (const auto &Vec : DupVector) {
19562 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.")(static_cast <bool> (Vec->size() > 1 && "ECDVector should have at least 2 elements."
) ? void (0) : __assert_fail ("Vec->size() > 1 && \"ECDVector should have at least 2 elements.\""
, "clang/lib/Sema/SemaDecl.cpp", 19562, __extension__ __PRETTY_FUNCTION__
))
;
19563
19564 // Emit warning for one enum constant.
19565 auto *FirstECD = Vec->front();
19566 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
19567 << FirstECD << toString(FirstECD->getInitVal(), 10)
19568 << FirstECD->getSourceRange();
19569
19570 // Emit one note for each of the remaining enum constants with
19571 // the same value.
19572 for (auto *ECD : llvm::drop_begin(*Vec))
19573 S.Diag(ECD->getLocation(), diag::note_duplicate_element)
19574 << ECD << toString(ECD->getInitVal(), 10)
19575 << ECD->getSourceRange();
19576 }
19577}
19578
19579bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
19580 bool AllowMask) const {
19581 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum")(static_cast <bool> (ED->isClosedFlag() && "looking for value in non-flag or open enum"
) ? void (0) : __assert_fail ("ED->isClosedFlag() && \"looking for value in non-flag or open enum\""
, "clang/lib/Sema/SemaDecl.cpp", 19581, __extension__ __PRETTY_FUNCTION__
))
;
19582 assert(ED->isCompleteDefinition() && "expected enum definition")(static_cast <bool> (ED->isCompleteDefinition() &&
"expected enum definition") ? void (0) : __assert_fail ("ED->isCompleteDefinition() && \"expected enum definition\""
, "clang/lib/Sema/SemaDecl.cpp", 19582, __extension__ __PRETTY_FUNCTION__
))
;
19583
19584 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
19585 llvm::APInt &FlagBits = R.first->second;
19586
19587 if (R.second) {
19588 for (auto *E : ED->enumerators()) {
19589 const auto &EVal = E->getInitVal();
19590 // Only single-bit enumerators introduce new flag values.
19591 if (EVal.isPowerOf2())
19592 FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal;
19593 }
19594 }
19595
19596 // A value is in a flag enum if either its bits are a subset of the enum's
19597 // flag bits (the first condition) or we are allowing masks and the same is
19598 // true of its complement (the second condition). When masks are allowed, we
19599 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
19600 //
19601 // While it's true that any value could be used as a mask, the assumption is
19602 // that a mask will have all of the insignificant bits set. Anything else is
19603 // likely a logic error.
19604 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
19605 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
19606}
19607
19608void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
19609 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
19610 const ParsedAttributesView &Attrs) {
19611 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
19612 QualType EnumType = Context.getTypeDeclType(Enum);
19613
19614 ProcessDeclAttributeList(S, Enum, Attrs);
19615
19616 if (Enum->isDependentType()) {
19617 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
19618 EnumConstantDecl *ECD =
19619 cast_or_null<EnumConstantDecl>(Elements[i]);
19620 if (!ECD) continue;
19621
19622 ECD->setType(EnumType);
19623 }
19624
19625 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
19626 return;
19627 }
19628
19629 // TODO: If the result value doesn't fit in an int, it must be a long or long
19630 // long value. ISO C does not support this, but GCC does as an extension,
19631 // emit a warning.
19632 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
19633 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
19634 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
19635
19636 // Verify that all the values are okay, compute the size of the values, and
19637 // reverse the list.
19638 unsigned NumNegativeBits = 0;
19639 unsigned NumPositiveBits = 0;
19640
19641 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
19642 EnumConstantDecl *ECD =
19643 cast_or_null<EnumConstantDecl>(Elements[i]);
19644 if (!ECD) continue; // Already issued a diagnostic.
19645
19646 const llvm::APSInt &InitVal = ECD->getInitVal();
19647
19648 // Keep track of the size of positive and negative values.
19649 if (InitVal.isUnsigned() || InitVal.isNonNegative()) {
19650 // If the enumerator is zero that should still be counted as a positive
19651 // bit since we need a bit to store the value zero.
19652 unsigned ActiveBits = InitVal.getActiveBits();
19653 NumPositiveBits = std::max({NumPositiveBits, ActiveBits, 1u});
19654 } else {
19655 NumNegativeBits =
19656 std::max(NumNegativeBits, (unsigned)InitVal.getSignificantBits());
19657 }
19658 }
19659
19660 // If we have an empty set of enumerators we still need one bit.
19661 // From [dcl.enum]p8
19662 // If the enumerator-list is empty, the values of the enumeration are as if
19663 // the enumeration had a single enumerator with value 0
19664 if (!NumPositiveBits && !NumNegativeBits)
19665 NumPositiveBits = 1;
19666
19667 // Figure out the type that should be used for this enum.
19668 QualType BestType;
19669 unsigned BestWidth;
19670
19671 // C++0x N3000 [conv.prom]p3:
19672 // An rvalue of an unscoped enumeration type whose underlying
19673 // type is not fixed can be converted to an rvalue of the first
19674 // of the following types that can represent all the values of
19675 // the enumeration: int, unsigned int, long int, unsigned long
19676 // int, long long int, or unsigned long long int.
19677 // C99 6.4.4.3p2:
19678 // An identifier declared as an enumeration constant has type int.
19679 // The C99 rule is modified by a gcc extension
19680 QualType BestPromotionType;
19681
19682 bool Packed = Enum->hasAttr<PackedAttr>();
19683 // -fshort-enums is the equivalent to specifying the packed attribute on all
19684 // enum definitions.
19685 if (LangOpts.ShortEnums)
19686 Packed = true;
19687
19688 // If the enum already has a type because it is fixed or dictated by the
19689 // target, promote that type instead of analyzing the enumerators.
19690 if (Enum->isComplete()) {
19691 BestType = Enum->getIntegerType();
19692 if (Context.isPromotableIntegerType(BestType))
19693 BestPromotionType = Context.getPromotedIntegerType(BestType);
19694 else
19695 BestPromotionType = BestType;
19696
19697 BestWidth = Context.getIntWidth(BestType);
19698 }
19699 else if (NumNegativeBits) {
19700 // If there is a negative value, figure out the smallest integer type (of
19701 // int/long/longlong) that fits.
19702 // If it's packed, check also if it fits a char or a short.
19703 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
19704 BestType = Context.SignedCharTy;
19705 BestWidth = CharWidth;
19706 } else if (Packed && NumNegativeBits <= ShortWidth &&
19707 NumPositiveBits < ShortWidth) {
19708 BestType = Context.ShortTy;
19709 BestWidth = ShortWidth;
19710 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
19711 BestType = Context.IntTy;
19712 BestWidth = IntWidth;
19713 } else {
19714 BestWidth = Context.getTargetInfo().getLongWidth();
19715
19716 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
19717 BestType = Context.LongTy;
19718 } else {
19719 BestWidth = Context.getTargetInfo().getLongLongWidth();
19720
19721 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
19722 Diag(Enum->getLocation(), diag::ext_enum_too_large);
19723 BestType = Context.LongLongTy;
19724 }
19725 }
19726 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
19727 } else {
19728 // If there is no negative value, figure out the smallest type that fits
19729 // all of the enumerator values.
19730 // If it's packed, check also if it fits a char or a short.
19731 if (Packed && NumPositiveBits <= CharWidth) {
19732 BestType = Context.UnsignedCharTy;
19733 BestPromotionType = Context.IntTy;
19734 BestWidth = CharWidth;
19735 } else if (Packed && NumPositiveBits <= ShortWidth) {
19736 BestType = Context.UnsignedShortTy;
19737 BestPromotionType = Context.IntTy;
19738 BestWidth = ShortWidth;
19739 } else if (NumPositiveBits <= IntWidth) {
19740 BestType = Context.UnsignedIntTy;
19741 BestWidth = IntWidth;
19742 BestPromotionType
19743 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
19744 ? Context.UnsignedIntTy : Context.IntTy;
19745 } else if (NumPositiveBits <=
19746 (BestWidth = Context.getTargetInfo().getLongWidth())) {
19747 BestType = Context.UnsignedLongTy;
19748 BestPromotionType
19749 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
19750 ? Context.UnsignedLongTy : Context.LongTy;
19751 } else {
19752 BestWidth = Context.getTargetInfo().getLongLongWidth();
19753 assert(NumPositiveBits <= BestWidth &&(static_cast <bool> (NumPositiveBits <= BestWidth &&
"How could an initializer get larger than ULL?") ? void (0) :
__assert_fail ("NumPositiveBits <= BestWidth && \"How could an initializer get larger than ULL?\""
, "clang/lib/Sema/SemaDecl.cpp", 19754, __extension__ __PRETTY_FUNCTION__
))
19754 "How could an initializer get larger than ULL?")(static_cast <bool> (NumPositiveBits <= BestWidth &&
"How could an initializer get larger than ULL?") ? void (0) :
__assert_fail ("NumPositiveBits <= BestWidth && \"How could an initializer get larger than ULL?\""
, "clang/lib/Sema/SemaDecl.cpp", 19754, __extension__ __PRETTY_FUNCTION__
))
;
19755 BestType = Context.UnsignedLongLongTy;
19756 BestPromotionType
19757 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
19758 ? Context.UnsignedLongLongTy : Context.LongLongTy;
19759 }
19760 }
19761
19762 // Loop over all of the enumerator constants, changing their types to match
19763 // the type of the enum if needed.
19764 for (auto *D : Elements) {
19765 auto *ECD = cast_or_null<EnumConstantDecl>(D);
19766 if (!ECD) continue; // Already issued a diagnostic.
19767
19768 // Standard C says the enumerators have int type, but we allow, as an
19769 // extension, the enumerators to be larger than int size. If each
19770 // enumerator value fits in an int, type it as an int, otherwise type it the
19771 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
19772 // that X has type 'int', not 'unsigned'.
19773
19774 // Determine whether the value fits into an int.
19775 llvm::APSInt InitVal = ECD->getInitVal();
19776
19777 // If it fits into an integer type, force it. Otherwise force it to match
19778 // the enum decl type.
19779 QualType NewTy;
19780 unsigned NewWidth;
19781 bool NewSign;
19782 if (!getLangOpts().CPlusPlus &&
19783 !Enum->isFixed() &&
19784 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
19785 NewTy = Context.IntTy;
19786 NewWidth = IntWidth;
19787 NewSign = true;
19788 } else if (ECD->getType() == BestType) {
19789 // Already the right type!
19790 if (getLangOpts().CPlusPlus)
19791 // C++ [dcl.enum]p4: Following the closing brace of an
19792 // enum-specifier, each enumerator has the type of its
19793 // enumeration.
19794 ECD->setType(EnumType);
19795 continue;
19796 } else {
19797 NewTy = BestType;
19798 NewWidth = BestWidth;
19799 NewSign = BestType->isSignedIntegerOrEnumerationType();
19800 }
19801
19802 // Adjust the APSInt value.
19803 InitVal = InitVal.extOrTrunc(NewWidth);
19804 InitVal.setIsSigned(NewSign);
19805 ECD->setInitVal(InitVal);
19806
19807 // Adjust the Expr initializer and type.
19808 if (ECD->getInitExpr() &&
19809 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
19810 ECD->setInitExpr(ImplicitCastExpr::Create(
19811 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
19812 /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
19813 if (getLangOpts().CPlusPlus)
19814 // C++ [dcl.enum]p4: Following the closing brace of an
19815 // enum-specifier, each enumerator has the type of its
19816 // enumeration.
19817 ECD->setType(EnumType);
19818 else
19819 ECD->setType(NewTy);
19820 }
19821
19822 Enum->completeDefinition(BestType, BestPromotionType,
19823 NumPositiveBits, NumNegativeBits);
19824
19825 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
19826
19827 if (Enum->isClosedFlag()) {
19828 for (Decl *D : Elements) {
19829 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
19830 if (!ECD) continue; // Already issued a diagnostic.
19831
19832 llvm::APSInt InitVal = ECD->getInitVal();
19833 if (InitVal != 0 && !InitVal.isPowerOf2() &&
19834 !IsValueInFlagEnum(Enum, InitVal, true))
19835 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
19836 << ECD << Enum;
19837 }
19838 }
19839
19840 // Now that the enum type is defined, ensure it's not been underaligned.
19841 if (Enum->hasAttrs())
19842 CheckAlignasUnderalignment(Enum);
19843}
19844
19845Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
19846 SourceLocation StartLoc,
19847 SourceLocation EndLoc) {
19848 StringLiteral *AsmString = cast<StringLiteral>(expr);
19849
19850 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
19851 AsmString, StartLoc,
19852 EndLoc);
19853 CurContext->addDecl(New);
19854 return New;
19855}
19856
19857Decl *Sema::ActOnTopLevelStmtDecl(Stmt *Statement) {
19858 auto *New = TopLevelStmtDecl::Create(Context, Statement);
19859 Context.getTranslationUnitDecl()->addDecl(New);
19860 return New;
19861}
19862
19863void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
19864 IdentifierInfo* AliasName,
19865 SourceLocation PragmaLoc,
19866 SourceLocation NameLoc,
19867 SourceLocation AliasNameLoc) {
19868 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
19869 LookupOrdinaryName);
19870 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
19871 AttributeCommonInfo::Form::Pragma());
19872 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
19873 Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info);
19874
19875 // If a declaration that:
19876 // 1) declares a function or a variable
19877 // 2) has external linkage
19878 // already exists, add a label attribute to it.
19879 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
19880 if (isDeclExternC(PrevDecl))
19881 PrevDecl->addAttr(Attr);
19882 else
19883 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
19884 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
19885 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
19886 } else
19887 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
19888}
19889
19890void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
19891 SourceLocation PragmaLoc,
19892 SourceLocation NameLoc) {
19893 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
19894
19895 if (PrevDecl) {
19896 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
19897 } else {
19898 (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
19899 }
19900}
19901
19902void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
19903 IdentifierInfo* AliasName,
19904 SourceLocation PragmaLoc,
19905 SourceLocation NameLoc,
19906 SourceLocation AliasNameLoc) {
19907 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
19908 LookupOrdinaryName);
19909 WeakInfo W = WeakInfo(Name, NameLoc);
19910
19911 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
19912 if (!PrevDecl->hasAttr<AliasAttr>())
19913 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
19914 DeclApplyPragmaWeak(TUScope, ND, W);
19915 } else {
19916 (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
19917 }
19918}
19919
19920ObjCContainerDecl *Sema::getObjCDeclContext() const {
19921 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
19922}
19923
19924Sema::FunctionEmissionStatus Sema::getEmissionStatus(const FunctionDecl *FD,
19925 bool Final) {
19926 assert(FD && "Expected non-null FunctionDecl")(static_cast <bool> (FD && "Expected non-null FunctionDecl"
) ? void (0) : __assert_fail ("FD && \"Expected non-null FunctionDecl\""
, "clang/lib/Sema/SemaDecl.cpp", 19926, __extension__ __PRETTY_FUNCTION__
))
;
19927
19928 // SYCL functions can be template, so we check if they have appropriate
19929 // attribute prior to checking if it is a template.
19930 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
19931 return FunctionEmissionStatus::Emitted;
19932
19933 // Templates are emitted when they're instantiated.
19934 if (FD->isDependentContext())
19935 return FunctionEmissionStatus::TemplateDiscarded;
19936
19937 // Check whether this function is an externally visible definition.
19938 auto IsEmittedForExternalSymbol = [this, FD]() {
19939 // We have to check the GVA linkage of the function's *definition* -- if we
19940 // only have a declaration, we don't know whether or not the function will
19941 // be emitted, because (say) the definition could include "inline".
19942 const FunctionDecl *Def = FD->getDefinition();
19943
19944 return Def && !isDiscardableGVALinkage(
19945 getASTContext().GetGVALinkageForFunction(Def));
19946 };
19947
19948 if (LangOpts.OpenMPIsDevice) {
19949 // In OpenMP device mode we will not emit host only functions, or functions
19950 // we don't need due to their linkage.
19951 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
19952 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
19953 // DevTy may be changed later by
19954 // #pragma omp declare target to(*) device_type(*).
19955 // Therefore DevTy having no value does not imply host. The emission status
19956 // will be checked again at the end of compilation unit with Final = true.
19957 if (DevTy)
19958 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
19959 return FunctionEmissionStatus::OMPDiscarded;
19960 // If we have an explicit value for the device type, or we are in a target
19961 // declare context, we need to emit all extern and used symbols.
19962 if (isInOpenMPDeclareTargetContext() || DevTy)
19963 if (IsEmittedForExternalSymbol())
19964 return FunctionEmissionStatus::Emitted;
19965 // Device mode only emits what it must, if it wasn't tagged yet and needed,
19966 // we'll omit it.
19967 if (Final)
19968 return FunctionEmissionStatus::OMPDiscarded;
19969 } else if (LangOpts.OpenMP > 45) {
19970 // In OpenMP host compilation prior to 5.0 everything was an emitted host
19971 // function. In 5.0, no_host was introduced which might cause a function to
19972 // be ommitted.
19973 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
19974 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
19975 if (DevTy)
19976 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
19977 return FunctionEmissionStatus::OMPDiscarded;
19978 }
19979
19980 if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
19981 return FunctionEmissionStatus::Emitted;
19982
19983 if (LangOpts.CUDA) {
19984 // When compiling for device, host functions are never emitted. Similarly,
19985 // when compiling for host, device and global functions are never emitted.
19986 // (Technically, we do emit a host-side stub for global functions, but this
19987 // doesn't count for our purposes here.)
19988 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
19989 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
19990 return FunctionEmissionStatus::CUDADiscarded;
19991 if (!LangOpts.CUDAIsDevice &&
19992 (T == Sema::CFT_Device || T == Sema::CFT_Global))
19993 return FunctionEmissionStatus::CUDADiscarded;
19994
19995 if (IsEmittedForExternalSymbol())
19996 return FunctionEmissionStatus::Emitted;
19997 }
19998
19999 // Otherwise, the function is known-emitted if it's in our set of
20000 // known-emitted functions.
20001 return FunctionEmissionStatus::Unknown;
20002}
20003
20004bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
20005 // Host-side references to a __global__ function refer to the stub, so the
20006 // function itself is never emitted and therefore should not be marked.
20007 // If we have host fn calls kernel fn calls host+device, the HD function
20008 // does not get instantiated on the host. We model this by omitting at the
20009 // call to the kernel from the callgraph. This ensures that, when compiling
20010 // for host, only HD functions actually called from the host get marked as
20011 // known-emitted.
20012 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
20013 IdentifyCUDATarget(Callee) == CFT_Global;
20014}