Bug Summary

File:clang/lib/Sema/SemaDecl.cpp
Warning:line 3767, column 35
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 -disable-llvm-verifier -discard-value-names -main-file-name SemaDecl.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/build-llvm/tools/clang/lib/Sema -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D CLANG_ROUND_TRIP_CC1_ARGS=ON -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema -I /build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/include -I /build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/build-llvm/include -I /build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/llvm/include -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -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-2021-08-25-171901-26424-1 -x c++ /build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp

/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp

1//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for declarations.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TypeLocBuilder.h"
14#include "clang/AST/ASTConsumer.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/ASTLambda.h"
17#include "clang/AST/CXXInheritance.h"
18#include "clang/AST/CharUnits.h"
19#include "clang/AST/CommentDiagnostic.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclObjC.h"
22#include "clang/AST/DeclTemplate.h"
23#include "clang/AST/EvaluatedExprVisitor.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/NonTrivialTypeVisitor.h"
27#include "clang/AST/StmtCXX.h"
28#include "clang/Basic/Builtins.h"
29#include "clang/Basic/PartialDiagnostic.h"
30#include "clang/Basic/SourceManager.h"
31#include "clang/Basic/TargetInfo.h"
32#include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
33#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
34#include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
35#include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
36#include "clang/Sema/CXXFieldCollector.h"
37#include "clang/Sema/DeclSpec.h"
38#include "clang/Sema/DelayedDiagnostic.h"
39#include "clang/Sema/Initialization.h"
40#include "clang/Sema/Lookup.h"
41#include "clang/Sema/ParsedTemplate.h"
42#include "clang/Sema/Scope.h"
43#include "clang/Sema/ScopeInfo.h"
44#include "clang/Sema/SemaInternal.h"
45#include "clang/Sema/Template.h"
46#include "llvm/ADT/SmallString.h"
47#include "llvm/ADT/Triple.h"
48#include <algorithm>
49#include <cstring>
50#include <functional>
51#include <unordered_map>
52
53using namespace clang;
54using namespace sema;
55
56Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
57 if (OwnedType) {
58 Decl *Group[2] = { OwnedType, Ptr };
59 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
60 }
61
62 return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
63}
64
65namespace {
66
67class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
68 public:
69 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
70 bool AllowTemplates = false,
71 bool AllowNonTemplates = true)
72 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
73 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
74 WantExpressionKeywords = false;
75 WantCXXNamedCasts = false;
76 WantRemainingKeywords = false;
77 }
78
79 bool ValidateCandidate(const TypoCorrection &candidate) override {
80 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
81 if (!AllowInvalidDecl && ND->isInvalidDecl())
82 return false;
83
84 if (getAsTypeTemplateDecl(ND))
85 return AllowTemplates;
86
87 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
88 if (!IsType)
89 return false;
90
91 if (AllowNonTemplates)
92 return true;
93
94 // An injected-class-name of a class template (specialization) is valid
95 // as a template or as a non-template.
96 if (AllowTemplates) {
97 auto *RD = dyn_cast<CXXRecordDecl>(ND);
98 if (!RD || !RD->isInjectedClassName())
99 return false;
100 RD = cast<CXXRecordDecl>(RD->getDeclContext());
101 return RD->getDescribedClassTemplate() ||
102 isa<ClassTemplateSpecializationDecl>(RD);
103 }
104
105 return false;
106 }
107
108 return !WantClassName && candidate.isKeyword();
109 }
110
111 std::unique_ptr<CorrectionCandidateCallback> clone() override {
112 return std::make_unique<TypeNameValidatorCCC>(*this);
113 }
114
115 private:
116 bool AllowInvalidDecl;
117 bool WantClassName;
118 bool AllowTemplates;
119 bool AllowNonTemplates;
120};
121
122} // end anonymous namespace
123
124/// Determine whether the token kind starts a simple-type-specifier.
125bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
126 switch (Kind) {
127 // FIXME: Take into account the current language when deciding whether a
128 // token kind is a valid type specifier
129 case tok::kw_short:
130 case tok::kw_long:
131 case tok::kw___int64:
132 case tok::kw___int128:
133 case tok::kw_signed:
134 case tok::kw_unsigned:
135 case tok::kw_void:
136 case tok::kw_char:
137 case tok::kw_int:
138 case tok::kw_half:
139 case tok::kw_float:
140 case tok::kw_double:
141 case tok::kw___bf16:
142 case tok::kw__Float16:
143 case tok::kw___float128:
144 case tok::kw_wchar_t:
145 case tok::kw_bool:
146 case tok::kw___underlying_type:
147 case tok::kw___auto_type:
148 return true;
149
150 case tok::annot_typename:
151 case tok::kw_char16_t:
152 case tok::kw_char32_t:
153 case tok::kw_typeof:
154 case tok::annot_decltype:
155 case tok::kw_decltype:
156 return getLangOpts().CPlusPlus;
157
158 case tok::kw_char8_t:
159 return getLangOpts().Char8;
160
161 default:
162 break;
163 }
164
165 return false;
166}
167
168namespace {
169enum class UnqualifiedTypeNameLookupResult {
170 NotFound,
171 FoundNonType,
172 FoundType
173};
174} // end anonymous namespace
175
176/// Tries to perform unqualified lookup of the type decls in bases for
177/// dependent class.
178/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
179/// type decl, \a FoundType if only type decls are found.
180static UnqualifiedTypeNameLookupResult
181lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
182 SourceLocation NameLoc,
183 const CXXRecordDecl *RD) {
184 if (!RD->hasDefinition())
185 return UnqualifiedTypeNameLookupResult::NotFound;
186 // Look for type decls in base classes.
187 UnqualifiedTypeNameLookupResult FoundTypeDecl =
188 UnqualifiedTypeNameLookupResult::NotFound;
189 for (const auto &Base : RD->bases()) {
190 const CXXRecordDecl *BaseRD = nullptr;
191 if (auto *BaseTT = Base.getType()->getAs<TagType>())
192 BaseRD = BaseTT->getAsCXXRecordDecl();
193 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
194 // Look for type decls in dependent base classes that have known primary
195 // templates.
196 if (!TST || !TST->isDependentType())
197 continue;
198 auto *TD = TST->getTemplateName().getAsTemplateDecl();
199 if (!TD)
200 continue;
201 if (auto *BasePrimaryTemplate =
202 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
203 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
204 BaseRD = BasePrimaryTemplate;
205 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
206 if (const ClassTemplatePartialSpecializationDecl *PS =
207 CTD->findPartialSpecialization(Base.getType()))
208 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
209 BaseRD = PS;
210 }
211 }
212 }
213 if (BaseRD) {
214 for (NamedDecl *ND : BaseRD->lookup(&II)) {
215 if (!isa<TypeDecl>(ND))
216 return UnqualifiedTypeNameLookupResult::FoundNonType;
217 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
218 }
219 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
220 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
221 case UnqualifiedTypeNameLookupResult::FoundNonType:
222 return UnqualifiedTypeNameLookupResult::FoundNonType;
223 case UnqualifiedTypeNameLookupResult::FoundType:
224 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
225 break;
226 case UnqualifiedTypeNameLookupResult::NotFound:
227 break;
228 }
229 }
230 }
231 }
232
233 return FoundTypeDecl;
234}
235
236static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
237 const IdentifierInfo &II,
238 SourceLocation NameLoc) {
239 // Lookup in the parent class template context, if any.
240 const CXXRecordDecl *RD = nullptr;
241 UnqualifiedTypeNameLookupResult FoundTypeDecl =
242 UnqualifiedTypeNameLookupResult::NotFound;
243 for (DeclContext *DC = S.CurContext;
244 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
245 DC = DC->getParent()) {
246 // Look for type decls in dependent base classes that have known primary
247 // templates.
248 RD = dyn_cast<CXXRecordDecl>(DC);
249 if (RD && RD->getDescribedClassTemplate())
250 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
251 }
252 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
253 return nullptr;
254
255 // We found some types in dependent base classes. Recover as if the user
256 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
257 // lookup during template instantiation.
258 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
259
260 ASTContext &Context = S.Context;
261 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
262 cast<Type>(Context.getRecordType(RD)));
263 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
264
265 CXXScopeSpec SS;
266 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
267
268 TypeLocBuilder Builder;
269 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
270 DepTL.setNameLoc(NameLoc);
271 DepTL.setElaboratedKeywordLoc(SourceLocation());
272 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
273 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
274}
275
276/// If the identifier refers to a type name within this scope,
277/// return the declaration of that type.
278///
279/// This routine performs ordinary name lookup of the identifier II
280/// within the given scope, with optional C++ scope specifier SS, to
281/// determine whether the name refers to a type. If so, returns an
282/// opaque pointer (actually a QualType) corresponding to that
283/// type. Otherwise, returns NULL.
284ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
285 Scope *S, CXXScopeSpec *SS,
286 bool isClassName, bool HasTrailingDot,
287 ParsedType ObjectTypePtr,
288 bool IsCtorOrDtorName,
289 bool WantNontrivialTypeSourceInfo,
290 bool IsClassTemplateDeductionContext,
291 IdentifierInfo **CorrectedII) {
292 // FIXME: Consider allowing this outside C++1z mode as an extension.
293 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
294 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
295 !isClassName && !HasTrailingDot;
296
297 // Determine where we will perform name lookup.
298 DeclContext *LookupCtx = nullptr;
299 if (ObjectTypePtr) {
300 QualType ObjectType = ObjectTypePtr.get();
301 if (ObjectType->isRecordType())
302 LookupCtx = computeDeclContext(ObjectType);
303 } else if (SS && SS->isNotEmpty()) {
304 LookupCtx = computeDeclContext(*SS, false);
305
306 if (!LookupCtx) {
307 if (isDependentScopeSpecifier(*SS)) {
308 // C++ [temp.res]p3:
309 // A qualified-id that refers to a type and in which the
310 // nested-name-specifier depends on a template-parameter (14.6.2)
311 // shall be prefixed by the keyword typename to indicate that the
312 // qualified-id denotes a type, forming an
313 // elaborated-type-specifier (7.1.5.3).
314 //
315 // We therefore do not perform any name lookup if the result would
316 // refer to a member of an unknown specialization.
317 if (!isClassName && !IsCtorOrDtorName)
318 return nullptr;
319
320 // We know from the grammar that this name refers to a type,
321 // so build a dependent node to describe the type.
322 if (WantNontrivialTypeSourceInfo)
323 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
324
325 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
326 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
327 II, NameLoc);
328 return ParsedType::make(T);
329 }
330
331 return nullptr;
332 }
333
334 if (!LookupCtx->isDependentContext() &&
335 RequireCompleteDeclContext(*SS, LookupCtx))
336 return nullptr;
337 }
338
339 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
340 // lookup for class-names.
341 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
342 LookupOrdinaryName;
343 LookupResult Result(*this, &II, NameLoc, Kind);
344 if (LookupCtx) {
345 // Perform "qualified" name lookup into the declaration context we
346 // computed, which is either the type of the base of a member access
347 // expression or the declaration context associated with a prior
348 // nested-name-specifier.
349 LookupQualifiedName(Result, LookupCtx);
350
351 if (ObjectTypePtr && Result.empty()) {
352 // C++ [basic.lookup.classref]p3:
353 // If the unqualified-id is ~type-name, the type-name is looked up
354 // in the context of the entire postfix-expression. If the type T of
355 // the object expression is of a class type C, the type-name is also
356 // looked up in the scope of class C. At least one of the lookups shall
357 // find a name that refers to (possibly cv-qualified) T.
358 LookupName(Result, S);
359 }
360 } else {
361 // Perform unqualified name lookup.
362 LookupName(Result, S);
363
364 // For unqualified lookup in a class template in MSVC mode, look into
365 // dependent base classes where the primary class template is known.
366 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
367 if (ParsedType TypeInBase =
368 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
369 return TypeInBase;
370 }
371 }
372
373 NamedDecl *IIDecl = nullptr;
374 switch (Result.getResultKind()) {
375 case LookupResult::NotFound:
376 case LookupResult::NotFoundInCurrentInstantiation:
377 if (CorrectedII) {
378 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
379 AllowDeducedTemplate);
380 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
381 S, SS, CCC, CTK_ErrorRecovery);
382 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
383 TemplateTy Template;
384 bool MemberOfUnknownSpecialization;
385 UnqualifiedId TemplateName;
386 TemplateName.setIdentifier(NewII, NameLoc);
387 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
388 CXXScopeSpec NewSS, *NewSSPtr = SS;
389 if (SS && NNS) {
390 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
391 NewSSPtr = &NewSS;
392 }
393 if (Correction && (NNS || NewII != &II) &&
394 // Ignore a correction to a template type as the to-be-corrected
395 // identifier is not a template (typo correction for template names
396 // is handled elsewhere).
397 !(getLangOpts().CPlusPlus && NewSSPtr &&
398 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
399 Template, MemberOfUnknownSpecialization))) {
400 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
401 isClassName, HasTrailingDot, ObjectTypePtr,
402 IsCtorOrDtorName,
403 WantNontrivialTypeSourceInfo,
404 IsClassTemplateDeductionContext);
405 if (Ty) {
406 diagnoseTypo(Correction,
407 PDiag(diag::err_unknown_type_or_class_name_suggest)
408 << Result.getLookupName() << isClassName);
409 if (SS && NNS)
410 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
411 *CorrectedII = NewII;
412 return Ty;
413 }
414 }
415 }
416 // If typo correction failed or was not performed, fall through
417 LLVM_FALLTHROUGH[[gnu::fallthrough]];
418 case LookupResult::FoundOverloaded:
419 case LookupResult::FoundUnresolvedValue:
420 Result.suppressDiagnostics();
421 return nullptr;
422
423 case LookupResult::Ambiguous:
424 // Recover from type-hiding ambiguities by hiding the type. We'll
425 // do the lookup again when looking for an object, and we can
426 // diagnose the error then. If we don't do this, then the error
427 // about hiding the type will be immediately followed by an error
428 // that only makes sense if the identifier was treated like a type.
429 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
430 Result.suppressDiagnostics();
431 return nullptr;
432 }
433
434 // Look to see if we have a type anywhere in the list of results.
435 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
436 Res != ResEnd; ++Res) {
437 NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
438 if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
439 RealRes) ||
440 (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
441 if (!IIDecl ||
442 // Make the selection of the recovery decl deterministic.
443 RealRes->getLocation() < IIDecl->getLocation())
444 IIDecl = RealRes;
445 }
446 }
447
448 if (!IIDecl) {
449 // None of the entities we found is a type, so there is no way
450 // to even assume that the result is a type. In this case, don't
451 // complain about the ambiguity. The parser will either try to
452 // perform this lookup again (e.g., as an object name), which
453 // will produce the ambiguity, or will complain that it expected
454 // a type name.
455 Result.suppressDiagnostics();
456 return nullptr;
457 }
458
459 // We found a type within the ambiguous lookup; diagnose the
460 // ambiguity and then return that type. This might be the right
461 // answer, or it might not be, but it suppresses any attempt to
462 // perform the name lookup again.
463 break;
464
465 case LookupResult::Found:
466 IIDecl = Result.getFoundDecl();
467 break;
468 }
469
470 assert(IIDecl && "Didn't find decl")(static_cast <bool> (IIDecl && "Didn't find decl"
) ? void (0) : __assert_fail ("IIDecl && \"Didn't find decl\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 470, __extension__ __PRETTY_FUNCTION__))
;
471
472 QualType T;
473 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
474 // C++ [class.qual]p2: A lookup that would find the injected-class-name
475 // instead names the constructors of the class, except when naming a class.
476 // This is ill-formed when we're not actually forming a ctor or dtor name.
477 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
478 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
479 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
480 FoundRD->isInjectedClassName() &&
481 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
482 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
483 << &II << /*Type*/1;
484
485 DiagnoseUseOfDecl(IIDecl, NameLoc);
486
487 T = Context.getTypeDeclType(TD);
488 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
489 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
490 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
491 if (!HasTrailingDot)
492 T = Context.getObjCInterfaceType(IDecl);
493 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
494 (void)DiagnoseUseOfDecl(UD, NameLoc);
495 // Recover with 'int'
496 T = Context.IntTy;
497 } else if (AllowDeducedTemplate) {
498 if (auto *TD = getAsTypeTemplateDecl(IIDecl))
499 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
500 QualType(), false);
501 }
502
503 if (T.isNull()) {
504 // If it's not plausibly a type, suppress diagnostics.
505 Result.suppressDiagnostics();
506 return nullptr;
507 }
508
509 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
510 // constructor or destructor name (in such a case, the scope specifier
511 // will be attached to the enclosing Expr or Decl node).
512 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
513 !isa<ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(IIDecl)) {
514 if (WantNontrivialTypeSourceInfo) {
515 // Construct a type with type-source information.
516 TypeLocBuilder Builder;
517 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
518
519 T = getElaboratedType(ETK_None, *SS, T);
520 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
521 ElabTL.setElaboratedKeywordLoc(SourceLocation());
522 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
523 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
524 } else {
525 T = getElaboratedType(ETK_None, *SS, T);
526 }
527 }
528
529 return ParsedType::make(T);
530}
531
532// Builds a fake NNS for the given decl context.
533static NestedNameSpecifier *
534synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
535 for (;; DC = DC->getLookupParent()) {
536 DC = DC->getPrimaryContext();
537 auto *ND = dyn_cast<NamespaceDecl>(DC);
538 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
539 return NestedNameSpecifier::Create(Context, nullptr, ND);
540 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
541 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
542 RD->getTypeForDecl());
543 else if (isa<TranslationUnitDecl>(DC))
544 return NestedNameSpecifier::GlobalSpecifier(Context);
545 }
546 llvm_unreachable("something isn't in TU scope?")::llvm::llvm_unreachable_internal("something isn't in TU scope?"
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 546)
;
547}
548
549/// Find the parent class with dependent bases of the innermost enclosing method
550/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
551/// up allowing unqualified dependent type names at class-level, which MSVC
552/// correctly rejects.
553static const CXXRecordDecl *
554findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
555 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
556 DC = DC->getPrimaryContext();
557 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
558 if (MD->getParent()->hasAnyDependentBases())
559 return MD->getParent();
560 }
561 return nullptr;
562}
563
564ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
565 SourceLocation NameLoc,
566 bool IsTemplateTypeArg) {
567 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 567, __extension__ __PRETTY_FUNCTION__))
;
568
569 NestedNameSpecifier *NNS = nullptr;
570 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
571 // If we weren't able to parse a default template argument, delay lookup
572 // until instantiation time by making a non-dependent DependentTypeName. We
573 // pretend we saw a NestedNameSpecifier referring to the current scope, and
574 // lookup is retried.
575 // FIXME: This hurts our diagnostic quality, since we get errors like "no
576 // type named 'Foo' in 'current_namespace'" when the user didn't write any
577 // name specifiers.
578 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
579 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
580 } else if (const CXXRecordDecl *RD =
581 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
582 // Build a DependentNameType that will perform lookup into RD at
583 // instantiation time.
584 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
585 RD->getTypeForDecl());
586
587 // Diagnose that this identifier was undeclared, and retry the lookup during
588 // template instantiation.
589 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
590 << RD;
591 } else {
592 // This is not a situation that we should recover from.
593 return ParsedType();
594 }
595
596 QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
597
598 // Build type location information. We synthesized the qualifier, so we have
599 // to build a fake NestedNameSpecifierLoc.
600 NestedNameSpecifierLocBuilder NNSLocBuilder;
601 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
602 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
603
604 TypeLocBuilder Builder;
605 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
606 DepTL.setNameLoc(NameLoc);
607 DepTL.setElaboratedKeywordLoc(SourceLocation());
608 DepTL.setQualifierLoc(QualifierLoc);
609 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
610}
611
612/// isTagName() - This method is called *for error recovery purposes only*
613/// to determine if the specified name is a valid tag name ("struct foo"). If
614/// so, this returns the TST for the tag corresponding to it (TST_enum,
615/// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
616/// cases in C where the user forgot to specify the tag.
617DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
618 // Do a tag name lookup in this scope.
619 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
620 LookupName(R, S, false);
621 R.suppressDiagnostics();
622 if (R.getResultKind() == LookupResult::Found)
623 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
624 switch (TD->getTagKind()) {
625 case TTK_Struct: return DeclSpec::TST_struct;
626 case TTK_Interface: return DeclSpec::TST_interface;
627 case TTK_Union: return DeclSpec::TST_union;
628 case TTK_Class: return DeclSpec::TST_class;
629 case TTK_Enum: return DeclSpec::TST_enum;
630 }
631 }
632
633 return DeclSpec::TST_unspecified;
634}
635
636/// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
637/// if a CXXScopeSpec's type is equal to the type of one of the base classes
638/// then downgrade the missing typename error to a warning.
639/// This is needed for MSVC compatibility; Example:
640/// @code
641/// template<class T> class A {
642/// public:
643/// typedef int TYPE;
644/// };
645/// template<class T> class B : public A<T> {
646/// public:
647/// A<T>::TYPE a; // no typename required because A<T> is a base class.
648/// };
649/// @endcode
650bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
651 if (CurContext->isRecord()) {
652 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
653 return true;
654
655 const Type *Ty = SS->getScopeRep()->getAsType();
656
657 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
658 for (const auto &Base : RD->bases())
659 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
660 return true;
661 return S->isFunctionPrototypeScope();
662 }
663 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
664}
665
666void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
667 SourceLocation IILoc,
668 Scope *S,
669 CXXScopeSpec *SS,
670 ParsedType &SuggestedType,
671 bool IsTemplateName) {
672 // Don't report typename errors for editor placeholders.
673 if (II->isEditorPlaceholder())
674 return;
675 // We don't have anything to suggest (yet).
676 SuggestedType = nullptr;
677
678 // There may have been a typo in the name of the type. Look up typo
679 // results, in case we have something that we can suggest.
680 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
681 /*AllowTemplates=*/IsTemplateName,
682 /*AllowNonTemplates=*/!IsTemplateName);
683 if (TypoCorrection Corrected =
684 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
685 CCC, CTK_ErrorRecovery)) {
686 // FIXME: Support error recovery for the template-name case.
687 bool CanRecover = !IsTemplateName;
688 if (Corrected.isKeyword()) {
689 // We corrected to a keyword.
690 diagnoseTypo(Corrected,
691 PDiag(IsTemplateName ? diag::err_no_template_suggest
692 : diag::err_unknown_typename_suggest)
693 << II);
694 II = Corrected.getCorrectionAsIdentifierInfo();
695 } else {
696 // We found a similarly-named type or interface; suggest that.
697 if (!SS || !SS->isSet()) {
698 diagnoseTypo(Corrected,
699 PDiag(IsTemplateName ? diag::err_no_template_suggest
700 : diag::err_unknown_typename_suggest)
701 << II, CanRecover);
702 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
703 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
704 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
705 II->getName().equals(CorrectedStr);
706 diagnoseTypo(Corrected,
707 PDiag(IsTemplateName
708 ? diag::err_no_member_template_suggest
709 : diag::err_unknown_nested_typename_suggest)
710 << II << DC << DroppedSpecifier << SS->getRange(),
711 CanRecover);
712 } else {
713 llvm_unreachable("could not have corrected a typo here")::llvm::llvm_unreachable_internal("could not have corrected a typo here"
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 713)
;
714 }
715
716 if (!CanRecover)
717 return;
718
719 CXXScopeSpec tmpSS;
720 if (Corrected.getCorrectionSpecifier())
721 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
722 SourceRange(IILoc));
723 // FIXME: Support class template argument deduction here.
724 SuggestedType =
725 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
726 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
727 /*IsCtorOrDtorName=*/false,
728 /*WantNontrivialTypeSourceInfo=*/true);
729 }
730 return;
731 }
732
733 if (getLangOpts().CPlusPlus && !IsTemplateName) {
734 // See if II is a class template that the user forgot to pass arguments to.
735 UnqualifiedId Name;
736 Name.setIdentifier(II, IILoc);
737 CXXScopeSpec EmptySS;
738 TemplateTy TemplateResult;
739 bool MemberOfUnknownSpecialization;
740 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
741 Name, nullptr, true, TemplateResult,
742 MemberOfUnknownSpecialization) == TNK_Type_template) {
743 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
744 return;
745 }
746 }
747
748 // FIXME: Should we move the logic that tries to recover from a missing tag
749 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
750
751 if (!SS || (!SS->isSet() && !SS->isInvalid()))
752 Diag(IILoc, IsTemplateName ? diag::err_no_template
753 : diag::err_unknown_typename)
754 << II;
755 else if (DeclContext *DC = computeDeclContext(*SS, false))
756 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
757 : diag::err_typename_nested_not_found)
758 << II << DC << SS->getRange();
759 else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
760 SuggestedType =
761 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
762 } else if (isDependentScopeSpecifier(*SS)) {
763 unsigned DiagID = diag::err_typename_missing;
764 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
765 DiagID = diag::ext_typename_missing;
766
767 Diag(SS->getRange().getBegin(), DiagID)
768 << SS->getScopeRep() << II->getName()
769 << SourceRange(SS->getRange().getBegin(), IILoc)
770 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
771 SuggestedType = ActOnTypenameType(S, SourceLocation(),
772 *SS, *II, IILoc).get();
773 } else {
774 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 775, __extension__ __PRETTY_FUNCTION__))
775 "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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 775, __extension__ __PRETTY_FUNCTION__))
;
776 }
777}
778
779/// Determine whether the given result set contains either a type name
780/// or
781static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
782 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
783 NextToken.is(tok::less);
784
785 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
786 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
787 return true;
788
789 if (CheckTemplate && isa<TemplateDecl>(*I))
790 return true;
791 }
792
793 return false;
794}
795
796static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
797 Scope *S, CXXScopeSpec &SS,
798 IdentifierInfo *&Name,
799 SourceLocation NameLoc) {
800 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
801 SemaRef.LookupParsedName(R, S, &SS);
802 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
803 StringRef FixItTagName;
804 switch (Tag->getTagKind()) {
805 case TTK_Class:
806 FixItTagName = "class ";
807 break;
808
809 case TTK_Enum:
810 FixItTagName = "enum ";
811 break;
812
813 case TTK_Struct:
814 FixItTagName = "struct ";
815 break;
816
817 case TTK_Interface:
818 FixItTagName = "__interface ";
819 break;
820
821 case TTK_Union:
822 FixItTagName = "union ";
823 break;
824 }
825
826 StringRef TagName = FixItTagName.drop_back();
827 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
828 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
829 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
830
831 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
832 I != IEnd; ++I)
833 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
834 << Name << TagName;
835
836 // Replace lookup results with just the tag decl.
837 Result.clear(Sema::LookupTagName);
838 SemaRef.LookupParsedName(Result, S, &SS);
839 return true;
840 }
841
842 return false;
843}
844
845/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
846static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
847 QualType T, SourceLocation NameLoc) {
848 ASTContext &Context = S.Context;
849
850 TypeLocBuilder Builder;
851 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
852
853 T = S.getElaboratedType(ETK_None, SS, T);
854 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
855 ElabTL.setElaboratedKeywordLoc(SourceLocation());
856 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
857 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
858}
859
860Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
861 IdentifierInfo *&Name,
862 SourceLocation NameLoc,
863 const Token &NextToken,
864 CorrectionCandidateCallback *CCC) {
865 DeclarationNameInfo NameInfo(Name, NameLoc);
866 ObjCMethodDecl *CurMethod = getCurMethodDecl();
867
868 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 869, __extension__ __PRETTY_FUNCTION__))
869 "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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 869, __extension__ __PRETTY_FUNCTION__))
;
870 if (getLangOpts().CPlusPlus && SS.isSet() &&
871 isCurrentClassName(*Name, S, &SS)) {
872 // Per [class.qual]p2, this names the constructors of SS, not the
873 // injected-class-name. We don't have a classification for that.
874 // There's not much point caching this result, since the parser
875 // will reject it later.
876 return NameClassification::Unknown();
877 }
878
879 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
880 LookupParsedName(Result, S, &SS, !CurMethod);
881
882 if (SS.isInvalid())
883 return NameClassification::Error();
884
885 // For unqualified lookup in a class template in MSVC mode, look into
886 // dependent base classes where the primary class template is known.
887 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
888 if (ParsedType TypeInBase =
889 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
890 return TypeInBase;
891 }
892
893 // Perform lookup for Objective-C instance variables (including automatically
894 // synthesized instance variables), if we're in an Objective-C method.
895 // FIXME: This lookup really, really needs to be folded in to the normal
896 // unqualified lookup mechanism.
897 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
898 DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
899 if (Ivar.isInvalid())
900 return NameClassification::Error();
901 if (Ivar.isUsable())
902 return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
903
904 // We defer builtin creation until after ivar lookup inside ObjC methods.
905 if (Result.empty())
906 LookupBuiltin(Result);
907 }
908
909 bool SecondTry = false;
910 bool IsFilteredTemplateName = false;
911
912Corrected:
913 switch (Result.getResultKind()) {
914 case LookupResult::NotFound:
915 // If an unqualified-id is followed by a '(', then we have a function
916 // call.
917 if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
918 // In C++, this is an ADL-only call.
919 // FIXME: Reference?
920 if (getLangOpts().CPlusPlus)
921 return NameClassification::UndeclaredNonType();
922
923 // C90 6.3.2.2:
924 // If the expression that precedes the parenthesized argument list in a
925 // function call consists solely of an identifier, and if no
926 // declaration is visible for this identifier, the identifier is
927 // implicitly declared exactly as if, in the innermost block containing
928 // the function call, the declaration
929 //
930 // extern int identifier ();
931 //
932 // appeared.
933 //
934 // We also allow this in C99 as an extension.
935 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
936 return NameClassification::NonType(D);
937 }
938
939 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
940 // In C++20 onwards, this could be an ADL-only call to a function
941 // template, and we're required to assume that this is a template name.
942 //
943 // FIXME: Find a way to still do typo correction in this case.
944 TemplateName Template =
945 Context.getAssumedTemplateName(NameInfo.getName());
946 return NameClassification::UndeclaredTemplate(Template);
947 }
948
949 // In C, we first see whether there is a tag type by the same name, in
950 // which case it's likely that the user just forgot to write "enum",
951 // "struct", or "union".
952 if (!getLangOpts().CPlusPlus && !SecondTry &&
953 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
954 break;
955 }
956
957 // Perform typo correction to determine if there is another name that is
958 // close to this name.
959 if (!SecondTry && CCC) {
960 SecondTry = true;
961 if (TypoCorrection Corrected =
962 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
963 &SS, *CCC, CTK_ErrorRecovery)) {
964 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
965 unsigned QualifiedDiag = diag::err_no_member_suggest;
966
967 NamedDecl *FirstDecl = Corrected.getFoundDecl();
968 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
969 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
970 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
971 UnqualifiedDiag = diag::err_no_template_suggest;
972 QualifiedDiag = diag::err_no_member_template_suggest;
973 } else if (UnderlyingFirstDecl &&
974 (isa<TypeDecl>(UnderlyingFirstDecl) ||
975 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
976 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
977 UnqualifiedDiag = diag::err_unknown_typename_suggest;
978 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
979 }
980
981 if (SS.isEmpty()) {
982 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
983 } else {// FIXME: is this even reachable? Test it.
984 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
985 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
986 Name->getName().equals(CorrectedStr);
987 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
988 << Name << computeDeclContext(SS, false)
989 << DroppedSpecifier << SS.getRange());
990 }
991
992 // Update the name, so that the caller has the new name.
993 Name = Corrected.getCorrectionAsIdentifierInfo();
994
995 // Typo correction corrected to a keyword.
996 if (Corrected.isKeyword())
997 return Name;
998
999 // Also update the LookupResult...
1000 // FIXME: This should probably go away at some point
1001 Result.clear();
1002 Result.setLookupName(Corrected.getCorrection());
1003 if (FirstDecl)
1004 Result.addDecl(FirstDecl);
1005
1006 // If we found an Objective-C instance variable, let
1007 // LookupInObjCMethod build the appropriate expression to
1008 // reference the ivar.
1009 // FIXME: This is a gross hack.
1010 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1011 DeclResult R =
1012 LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1013 if (R.isInvalid())
1014 return NameClassification::Error();
1015 if (R.isUsable())
1016 return NameClassification::NonType(Ivar);
1017 }
1018
1019 goto Corrected;
1020 }
1021 }
1022
1023 // We failed to correct; just fall through and let the parser deal with it.
1024 Result.suppressDiagnostics();
1025 return NameClassification::Unknown();
1026
1027 case LookupResult::NotFoundInCurrentInstantiation: {
1028 // We performed name lookup into the current instantiation, and there were
1029 // dependent bases, so we treat this result the same way as any other
1030 // dependent nested-name-specifier.
1031
1032 // C++ [temp.res]p2:
1033 // A name used in a template declaration or definition and that is
1034 // dependent on a template-parameter is assumed not to name a type
1035 // unless the applicable name lookup finds a type name or the name is
1036 // qualified by the keyword typename.
1037 //
1038 // FIXME: If the next token is '<', we might want to ask the parser to
1039 // perform some heroics to see if we actually have a
1040 // template-argument-list, which would indicate a missing 'template'
1041 // keyword here.
1042 return NameClassification::DependentNonType();
1043 }
1044
1045 case LookupResult::Found:
1046 case LookupResult::FoundOverloaded:
1047 case LookupResult::FoundUnresolvedValue:
1048 break;
1049
1050 case LookupResult::Ambiguous:
1051 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1052 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1053 /*AllowDependent=*/false)) {
1054 // C++ [temp.local]p3:
1055 // A lookup that finds an injected-class-name (10.2) can result in an
1056 // ambiguity in certain cases (for example, if it is found in more than
1057 // one base class). If all of the injected-class-names that are found
1058 // refer to specializations of the same class template, and if the name
1059 // is followed by a template-argument-list, the reference refers to the
1060 // class template itself and not a specialization thereof, and is not
1061 // ambiguous.
1062 //
1063 // This filtering can make an ambiguous result into an unambiguous one,
1064 // so try again after filtering out template names.
1065 FilterAcceptableTemplateNames(Result);
1066 if (!Result.isAmbiguous()) {
1067 IsFilteredTemplateName = true;
1068 break;
1069 }
1070 }
1071
1072 // Diagnose the ambiguity and return an error.
1073 return NameClassification::Error();
1074 }
1075
1076 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1077 (IsFilteredTemplateName ||
1078 hasAnyAcceptableTemplateNames(
1079 Result, /*AllowFunctionTemplates=*/true,
1080 /*AllowDependent=*/false,
1081 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1082 getLangOpts().CPlusPlus20))) {
1083 // C++ [temp.names]p3:
1084 // After name lookup (3.4) finds that a name is a template-name or that
1085 // an operator-function-id or a literal- operator-id refers to a set of
1086 // overloaded functions any member of which is a function template if
1087 // this is followed by a <, the < is always taken as the delimiter of a
1088 // template-argument-list and never as the less-than operator.
1089 // C++2a [temp.names]p2:
1090 // A name is also considered to refer to a template if it is an
1091 // unqualified-id followed by a < and name lookup finds either one
1092 // or more functions or finds nothing.
1093 if (!IsFilteredTemplateName)
1094 FilterAcceptableTemplateNames(Result);
1095
1096 bool IsFunctionTemplate;
1097 bool IsVarTemplate;
1098 TemplateName Template;
1099 if (Result.end() - Result.begin() > 1) {
1100 IsFunctionTemplate = true;
1101 Template = Context.getOverloadedTemplateName(Result.begin(),
1102 Result.end());
1103 } else if (!Result.empty()) {
1104 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1105 *Result.begin(), /*AllowFunctionTemplates=*/true,
1106 /*AllowDependent=*/false));
1107 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1108 IsVarTemplate = isa<VarTemplateDecl>(TD);
1109
1110 if (SS.isNotEmpty())
1111 Template =
1112 Context.getQualifiedTemplateName(SS.getScopeRep(),
1113 /*TemplateKeyword=*/false, TD);
1114 else
1115 Template = TemplateName(TD);
1116 } else {
1117 // All results were non-template functions. This is a function template
1118 // name.
1119 IsFunctionTemplate = true;
1120 Template = Context.getAssumedTemplateName(NameInfo.getName());
1121 }
1122
1123 if (IsFunctionTemplate) {
1124 // Function templates always go through overload resolution, at which
1125 // point we'll perform the various checks (e.g., accessibility) we need
1126 // to based on which function we selected.
1127 Result.suppressDiagnostics();
1128
1129 return NameClassification::FunctionTemplate(Template);
1130 }
1131
1132 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1133 : NameClassification::TypeTemplate(Template);
1134 }
1135
1136 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1137 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1138 DiagnoseUseOfDecl(Type, NameLoc);
1139 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1140 QualType T = Context.getTypeDeclType(Type);
1141 if (SS.isNotEmpty())
1142 return buildNestedType(*this, SS, T, NameLoc);
1143 return ParsedType::make(T);
1144 }
1145
1146 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1147 if (!Class) {
1148 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1149 if (ObjCCompatibleAliasDecl *Alias =
1150 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1151 Class = Alias->getClassInterface();
1152 }
1153
1154 if (Class) {
1155 DiagnoseUseOfDecl(Class, NameLoc);
1156
1157 if (NextToken.is(tok::period)) {
1158 // Interface. <something> is parsed as a property reference expression.
1159 // Just return "unknown" as a fall-through for now.
1160 Result.suppressDiagnostics();
1161 return NameClassification::Unknown();
1162 }
1163
1164 QualType T = Context.getObjCInterfaceType(Class);
1165 return ParsedType::make(T);
1166 }
1167
1168 if (isa<ConceptDecl>(FirstDecl))
1169 return NameClassification::Concept(
1170 TemplateName(cast<TemplateDecl>(FirstDecl)));
1171
1172 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1173 (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1174 return NameClassification::Error();
1175 }
1176
1177 // We can have a type template here if we're classifying a template argument.
1178 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1179 !isa<VarTemplateDecl>(FirstDecl))
1180 return NameClassification::TypeTemplate(
1181 TemplateName(cast<TemplateDecl>(FirstDecl)));
1182
1183 // Check for a tag type hidden by a non-type decl in a few cases where it
1184 // seems likely a type is wanted instead of the non-type that was found.
1185 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1186 if ((NextToken.is(tok::identifier) ||
1187 (NextIsOp &&
1188 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1189 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1190 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1191 DiagnoseUseOfDecl(Type, NameLoc);
1192 QualType T = Context.getTypeDeclType(Type);
1193 if (SS.isNotEmpty())
1194 return buildNestedType(*this, SS, T, NameLoc);
1195 return ParsedType::make(T);
1196 }
1197
1198 // If we already know which single declaration is referenced, just annotate
1199 // that declaration directly. Defer resolving even non-overloaded class
1200 // member accesses, as we need to defer certain access checks until we know
1201 // the context.
1202 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1203 if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember())
1204 return NameClassification::NonType(Result.getRepresentativeDecl());
1205
1206 // Otherwise, this is an overload set that we will need to resolve later.
1207 Result.suppressDiagnostics();
1208 return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1209 Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1210 Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
1211 Result.begin(), Result.end()));
1212}
1213
1214ExprResult
1215Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1216 SourceLocation NameLoc) {
1217 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?\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 1217, __extension__ __PRETTY_FUNCTION__))
;
1218 CXXScopeSpec SS;
1219 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1220 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1221}
1222
1223ExprResult
1224Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1225 IdentifierInfo *Name,
1226 SourceLocation NameLoc,
1227 bool IsAddressOfOperand) {
1228 DeclarationNameInfo NameInfo(Name, NameLoc);
1229 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1230 NameInfo, IsAddressOfOperand,
1231 /*TemplateArgs=*/nullptr);
1232}
1233
1234ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1235 NamedDecl *Found,
1236 SourceLocation NameLoc,
1237 const Token &NextToken) {
1238 if (getCurMethodDecl() && SS.isEmpty())
1239 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1240 return BuildIvarRefExpr(S, NameLoc, Ivar);
1241
1242 // Reconstruct the lookup result.
1243 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1244 Result.addDecl(Found);
1245 Result.resolveKind();
1246
1247 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1248 return BuildDeclarationNameExpr(SS, Result, ADL);
1249}
1250
1251ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1252 // For an implicit class member access, transform the result into a member
1253 // access expression if necessary.
1254 auto *ULE = cast<UnresolvedLookupExpr>(E);
1255 if ((*ULE->decls_begin())->isCXXClassMember()) {
1256 CXXScopeSpec SS;
1257 SS.Adopt(ULE->getQualifierLoc());
1258
1259 // Reconstruct the lookup result.
1260 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1261 LookupOrdinaryName);
1262 Result.setNamingClass(ULE->getNamingClass());
1263 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1264 Result.addDecl(*I, I.getAccess());
1265 Result.resolveKind();
1266 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1267 nullptr, S);
1268 }
1269
1270 // Otherwise, this is already in the form we needed, and no further checks
1271 // are necessary.
1272 return ULE;
1273}
1274
1275Sema::TemplateNameKindForDiagnostics
1276Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1277 auto *TD = Name.getAsTemplateDecl();
1278 if (!TD)
1279 return TemplateNameKindForDiagnostics::DependentTemplate;
1280 if (isa<ClassTemplateDecl>(TD))
1281 return TemplateNameKindForDiagnostics::ClassTemplate;
1282 if (isa<FunctionTemplateDecl>(TD))
1283 return TemplateNameKindForDiagnostics::FunctionTemplate;
1284 if (isa<VarTemplateDecl>(TD))
1285 return TemplateNameKindForDiagnostics::VarTemplate;
1286 if (isa<TypeAliasTemplateDecl>(TD))
1287 return TemplateNameKindForDiagnostics::AliasTemplate;
1288 if (isa<TemplateTemplateParmDecl>(TD))
1289 return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1290 if (isa<ConceptDecl>(TD))
1291 return TemplateNameKindForDiagnostics::Concept;
1292 return TemplateNameKindForDiagnostics::DependentTemplate;
1293}
1294
1295void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1296 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.\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 1297, __extension__ __PRETTY_FUNCTION__))
1297 "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.\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 1297, __extension__ __PRETTY_FUNCTION__))
;
1298 CurContext = DC;
1299 S->setEntity(DC);
1300}
1301
1302void Sema::PopDeclContext() {
1303 assert(CurContext && "DeclContext imbalance!")(static_cast <bool> (CurContext && "DeclContext imbalance!"
) ? void (0) : __assert_fail ("CurContext && \"DeclContext imbalance!\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 1303, __extension__ __PRETTY_FUNCTION__))
;
1304
1305 CurContext = CurContext->getLexicalParent();
1306 assert(CurContext && "Popped translation unit!")(static_cast <bool> (CurContext && "Popped translation unit!"
) ? void (0) : __assert_fail ("CurContext && \"Popped translation unit!\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 1306, __extension__ __PRETTY_FUNCTION__))
;
1307}
1308
1309Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1310 Decl *D) {
1311 // Unlike PushDeclContext, the context to which we return is not necessarily
1312 // the containing DC of TD, because the new context will be some pre-existing
1313 // TagDecl definition instead of a fresh one.
1314 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1315 CurContext = cast<TagDecl>(D)->getDefinition();
1316 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 1316, __extension__ __PRETTY_FUNCTION__))
;
1317 // Start lookups from the parent of the current context; we don't want to look
1318 // into the pre-existing complete definition.
1319 S->setEntity(CurContext->getLookupParent());
1320 return Result;
1321}
1322
1323void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1324 CurContext = static_cast<decltype(CurContext)>(Context);
1325}
1326
1327/// EnterDeclaratorContext - Used when we must lookup names in the context
1328/// of a declarator's nested name specifier.
1329///
1330void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1331 // C++0x [basic.lookup.unqual]p13:
1332 // A name used in the definition of a static data member of class
1333 // X (after the qualified-id of the static member) is looked up as
1334 // if the name was used in a member function of X.
1335 // C++0x [basic.lookup.unqual]p14:
1336 // If a variable member of a namespace is defined outside of the
1337 // scope of its namespace then any name used in the definition of
1338 // the variable member (after the declarator-id) is looked up as
1339 // if the definition of the variable member occurred in its
1340 // namespace.
1341 // Both of these imply that we should push a scope whose context
1342 // is the semantic context of the declaration. We can't use
1343 // PushDeclContext here because that context is not necessarily
1344 // lexically contained in the current context. Fortunately,
1345 // the containing scope should have the appropriate information.
1346
1347 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 1347, __extension__ __PRETTY_FUNCTION__))
;
1348
1349#ifndef NDEBUG
1350 Scope *Ancestor = S->getParent();
1351 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1352 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 1352, __extension__ __PRETTY_FUNCTION__))
;
1353#endif
1354
1355 CurContext = DC;
1356 S->setEntity(DC);
1357
1358 if (S->getParent()->isTemplateParamScope()) {
1359 // Also set the corresponding entities for all immediately-enclosing
1360 // template parameter scopes.
1361 EnterTemplatedContext(S->getParent(), DC);
1362 }
1363}
1364
1365void Sema::ExitDeclaratorContext(Scope *S) {
1366 assert(S->getEntity() == CurContext && "Context imbalance!")(static_cast <bool> (S->getEntity() == CurContext &&
"Context imbalance!") ? void (0) : __assert_fail ("S->getEntity() == CurContext && \"Context imbalance!\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 1366, __extension__ __PRETTY_FUNCTION__))
;
1367
1368 // Switch back to the lexical context. The safety of this is
1369 // enforced by an assert in EnterDeclaratorContext.
1370 Scope *Ancestor = S->getParent();
1371 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1372 CurContext = Ancestor->getEntity();
1373
1374 // We don't need to do anything with the scope, which is going to
1375 // disappear.
1376}
1377
1378void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1379 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 1380, __extension__ __PRETTY_FUNCTION__))
1380 "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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 1380, __extension__ __PRETTY_FUNCTION__))
;
1381
1382 // C++20 [temp.local]p7:
1383 // In the definition of a member of a class template that appears outside
1384 // of the class template definition, the name of a member of the class
1385 // template hides the name of a template-parameter of any enclosing class
1386 // templates (but not a template-parameter of the member if the member is a
1387 // class or function template).
1388 // C++20 [temp.local]p9:
1389 // In the definition of a class template or in the definition of a member
1390 // of such a template that appears outside of the template definition, for
1391 // each non-dependent base class (13.8.2.1), if the name of the base class
1392 // or the name of a member of the base class is the same as the name of a
1393 // template-parameter, the base class name or member name hides the
1394 // template-parameter name (6.4.10).
1395 //
1396 // This means that a template parameter scope should be searched immediately
1397 // after searching the DeclContext for which it is a template parameter
1398 // scope. For example, for
1399 // template<typename T> template<typename U> template<typename V>
1400 // void N::A<T>::B<U>::f(...)
1401 // we search V then B<U> (and base classes) then U then A<T> (and base
1402 // classes) then T then N then ::.
1403 unsigned ScopeDepth = getTemplateDepth(S);
1404 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1405 DeclContext *SearchDCAfterScope = DC;
1406 for (; DC; DC = DC->getLookupParent()) {
1407 if (const TemplateParameterList *TPL =
1408 cast<Decl>(DC)->getDescribedTemplateParams()) {
1409 unsigned DCDepth = TPL->getDepth() + 1;
1410 if (DCDepth > ScopeDepth)
1411 continue;
1412 if (ScopeDepth == DCDepth)
1413 SearchDCAfterScope = DC = DC->getLookupParent();
1414 break;
1415 }
1416 }
1417 S->setLookupEntity(SearchDCAfterScope);
1418 }
1419}
1420
1421void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1422 // We assume that the caller has already called
1423 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1424 FunctionDecl *FD = D->getAsFunction();
1425 if (!FD)
1426 return;
1427
1428 // Same implementation as PushDeclContext, but enters the context
1429 // from the lexical parent, rather than the top-level class.
1430 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.\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 1431, __extension__ __PRETTY_FUNCTION__))
1431 "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.\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 1431, __extension__ __PRETTY_FUNCTION__))
;
1432 CurContext = FD;
1433 S->setEntity(CurContext);
1434
1435 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1436 ParmVarDecl *Param = FD->getParamDecl(P);
1437 // If the parameter has an identifier, then add it to the scope
1438 if (Param->getIdentifier()) {
1439 S->AddDecl(Param);
1440 IdResolver.AddDecl(Param);
1441 }
1442 }
1443}
1444
1445void Sema::ActOnExitFunctionContext() {
1446 // Same implementation as PopDeclContext, but returns to the lexical parent,
1447 // rather than the top-level class.
1448 assert(CurContext && "DeclContext imbalance!")(static_cast <bool> (CurContext && "DeclContext imbalance!"
) ? void (0) : __assert_fail ("CurContext && \"DeclContext imbalance!\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 1448, __extension__ __PRETTY_FUNCTION__))
;
1449 CurContext = CurContext->getLexicalParent();
1450 assert(CurContext && "Popped translation unit!")(static_cast <bool> (CurContext && "Popped translation unit!"
) ? void (0) : __assert_fail ("CurContext && \"Popped translation unit!\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 1450, __extension__ __PRETTY_FUNCTION__))
;
1451}
1452
1453/// Determine whether we allow overloading of the function
1454/// PrevDecl with another declaration.
1455///
1456/// This routine determines whether overloading is possible, not
1457/// whether some new function is actually an overload. It will return
1458/// true in C++ (where we can always provide overloads) or, as an
1459/// extension, in C when the previous function is already an
1460/// overloaded function declaration or has the "overloadable"
1461/// attribute.
1462static bool AllowOverloadingOfFunction(LookupResult &Previous,
1463 ASTContext &Context,
1464 const FunctionDecl *New) {
1465 if (Context.getLangOpts().CPlusPlus)
1466 return true;
1467
1468 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1469 return true;
1470
1471 return Previous.getResultKind() == LookupResult::Found &&
1472 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1473 New->hasAttr<OverloadableAttr>());
1474}
1475
1476/// Add this decl to the scope shadowed decl chains.
1477void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1478 // Move up the scope chain until we find the nearest enclosing
1479 // non-transparent context. The declaration will be introduced into this
1480 // scope.
1481 while (S->getEntity() && S->getEntity()->isTransparentContext())
1482 S = S->getParent();
1483
1484 // Add scoped declarations into their context, so that they can be
1485 // found later. Declarations without a context won't be inserted
1486 // into any context.
1487 if (AddToContext)
1488 CurContext->addDecl(D);
1489
1490 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1491 // are function-local declarations.
1492 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1493 return;
1494
1495 // Template instantiations should also not be pushed into scope.
1496 if (isa<FunctionDecl>(D) &&
1497 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1498 return;
1499
1500 // If this replaces anything in the current scope,
1501 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1502 IEnd = IdResolver.end();
1503 for (; I != IEnd; ++I) {
1504 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1505 S->RemoveDecl(*I);
1506 IdResolver.RemoveDecl(*I);
1507
1508 // Should only need to replace one decl.
1509 break;
1510 }
1511 }
1512
1513 S->AddDecl(D);
1514
1515 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1516 // Implicitly-generated labels may end up getting generated in an order that
1517 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1518 // the label at the appropriate place in the identifier chain.
1519 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1520 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1521 if (IDC == CurContext) {
1522 if (!S->isDeclScope(*I))
1523 continue;
1524 } else if (IDC->Encloses(CurContext))
1525 break;
1526 }
1527
1528 IdResolver.InsertDeclAfter(I, D);
1529 } else {
1530 IdResolver.AddDecl(D);
1531 }
1532 warnOnReservedIdentifier(D);
1533}
1534
1535bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1536 bool AllowInlineNamespace) {
1537 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1538}
1539
1540Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1541 DeclContext *TargetDC = DC->getPrimaryContext();
1542 do {
1543 if (DeclContext *ScopeDC = S->getEntity())
1544 if (ScopeDC->getPrimaryContext() == TargetDC)
1545 return S;
1546 } while ((S = S->getParent()));
1547
1548 return nullptr;
1549}
1550
1551static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1552 DeclContext*,
1553 ASTContext&);
1554
1555/// Filters out lookup results that don't fall within the given scope
1556/// as determined by isDeclInScope.
1557void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1558 bool ConsiderLinkage,
1559 bool AllowInlineNamespace) {
1560 LookupResult::Filter F = R.makeFilter();
1561 while (F.hasNext()) {
1562 NamedDecl *D = F.next();
1563
1564 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1565 continue;
1566
1567 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1568 continue;
1569
1570 F.erase();
1571 }
1572
1573 F.done();
1574}
1575
1576/// We've determined that \p New is a redeclaration of \p Old. Check that they
1577/// have compatible owning modules.
1578bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1579 // FIXME: The Modules TS is not clear about how friend declarations are
1580 // to be treated. It's not meaningful to have different owning modules for
1581 // linkage in redeclarations of the same entity, so for now allow the
1582 // redeclaration and change the owning modules to match.
1583 if (New->getFriendObjectKind() &&
16
Calling 'Decl::getFriendObjectKind'
22
Returning from 'Decl::getFriendObjectKind'
24
Taking false branch
1584 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
23
Assuming the condition is false
1585 New->setLocalOwningModule(Old->getOwningModule());
1586 makeMergedDefinitionVisible(New);
1587 return false;
1588 }
1589
1590 Module *NewM = New->getOwningModule();
1591 Module *OldM = Old->getOwningModule();
1592
1593 if (NewM
24.1
'NewM' is null
24.1
'NewM' is null
&& NewM->Kind == Module::PrivateModuleFragment)
1594 NewM = NewM->Parent;
1595 if (OldM
24.2
'OldM' is null
24.2
'OldM' is null
&& OldM->Kind == Module::PrivateModuleFragment)
1596 OldM = OldM->Parent;
1597
1598 if (NewM
24.3
'NewM' is equal to 'OldM'
24.3
'NewM' is equal to 'OldM'
== OldM)
25
Taking true branch
1599 return false;
26
Returning zero, which participates in a condition later
1600
1601 bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1602 bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1603 if (NewIsModuleInterface || OldIsModuleInterface) {
1604 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1605 // if a declaration of D [...] appears in the purview of a module, all
1606 // other such declarations shall appear in the purview of the same module
1607 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1608 << New
1609 << NewIsModuleInterface
1610 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1611 << OldIsModuleInterface
1612 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1613 Diag(Old->getLocation(), diag::note_previous_declaration);
1614 New->setInvalidDecl();
1615 return true;
1616 }
1617
1618 return false;
1619}
1620
1621static bool isUsingDecl(NamedDecl *D) {
1622 return isa<UsingShadowDecl>(D) ||
1623 isa<UnresolvedUsingTypenameDecl>(D) ||
1624 isa<UnresolvedUsingValueDecl>(D);
1625}
1626
1627/// Removes using shadow declarations from the lookup results.
1628static void RemoveUsingDecls(LookupResult &R) {
1629 LookupResult::Filter F = R.makeFilter();
1630 while (F.hasNext())
1631 if (isUsingDecl(F.next()))
1632 F.erase();
1633
1634 F.done();
1635}
1636
1637/// Check for this common pattern:
1638/// @code
1639/// class S {
1640/// S(const S&); // DO NOT IMPLEMENT
1641/// void operator=(const S&); // DO NOT IMPLEMENT
1642/// };
1643/// @endcode
1644static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1645 // FIXME: Should check for private access too but access is set after we get
1646 // the decl here.
1647 if (D->doesThisDeclarationHaveABody())
1648 return false;
1649
1650 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1651 return CD->isCopyConstructor();
1652 return D->isCopyAssignmentOperator();
1653}
1654
1655// We need this to handle
1656//
1657// typedef struct {
1658// void *foo() { return 0; }
1659// } A;
1660//
1661// When we see foo we don't know if after the typedef we will get 'A' or '*A'
1662// for example. If 'A', foo will have external linkage. If we have '*A',
1663// foo will have no linkage. Since we can't know until we get to the end
1664// of the typedef, this function finds out if D might have non-external linkage.
1665// Callers should verify at the end of the TU if it D has external linkage or
1666// not.
1667bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1668 const DeclContext *DC = D->getDeclContext();
1669 while (!DC->isTranslationUnit()) {
1670 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1671 if (!RD->hasNameForLinkage())
1672 return true;
1673 }
1674 DC = DC->getParent();
1675 }
1676
1677 return !D->isExternallyVisible();
1678}
1679
1680// FIXME: This needs to be refactored; some other isInMainFile users want
1681// these semantics.
1682static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1683 if (S.TUKind != TU_Complete)
1684 return false;
1685 return S.SourceMgr.isInMainFile(Loc);
1686}
1687
1688bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1689 assert(D)(static_cast <bool> (D) ? void (0) : __assert_fail ("D"
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 1689, __extension__ __PRETTY_FUNCTION__))
;
1690
1691 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1692 return false;
1693
1694 // Ignore all entities declared within templates, and out-of-line definitions
1695 // of members of class templates.
1696 if (D->getDeclContext()->isDependentContext() ||
1697 D->getLexicalDeclContext()->isDependentContext())
1698 return false;
1699
1700 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1701 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1702 return false;
1703 // A non-out-of-line declaration of a member specialization was implicitly
1704 // instantiated; it's the out-of-line declaration that we're interested in.
1705 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1706 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1707 return false;
1708
1709 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1710 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1711 return false;
1712 } else {
1713 // 'static inline' functions are defined in headers; don't warn.
1714 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1715 return false;
1716 }
1717
1718 if (FD->doesThisDeclarationHaveABody() &&
1719 Context.DeclMustBeEmitted(FD))
1720 return false;
1721 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1722 // Constants and utility variables are defined in headers with internal
1723 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1724 // like "inline".)
1725 if (!isMainFileLoc(*this, VD->getLocation()))
1726 return false;
1727
1728 if (Context.DeclMustBeEmitted(VD))
1729 return false;
1730
1731 if (VD->isStaticDataMember() &&
1732 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1733 return false;
1734 if (VD->isStaticDataMember() &&
1735 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1736 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1737 return false;
1738
1739 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1740 return false;
1741 } else {
1742 return false;
1743 }
1744
1745 // Only warn for unused decls internal to the translation unit.
1746 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1747 // for inline functions defined in the main source file, for instance.
1748 return mightHaveNonExternalLinkage(D);
1749}
1750
1751void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1752 if (!D)
1753 return;
1754
1755 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1756 const FunctionDecl *First = FD->getFirstDecl();
1757 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1758 return; // First should already be in the vector.
1759 }
1760
1761 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1762 const VarDecl *First = VD->getFirstDecl();
1763 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1764 return; // First should already be in the vector.
1765 }
1766
1767 if (ShouldWarnIfUnusedFileScopedDecl(D))
1768 UnusedFileScopedDecls.push_back(D);
1769}
1770
1771static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1772 if (D->isInvalidDecl())
1773 return false;
1774
1775 if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1776 // For a decomposition declaration, warn if none of the bindings are
1777 // referenced, instead of if the variable itself is referenced (which
1778 // it is, by the bindings' expressions).
1779 for (auto *BD : DD->bindings())
1780 if (BD->isReferenced())
1781 return false;
1782 } else if (!D->getDeclName()) {
1783 return false;
1784 } else if (D->isReferenced() || D->isUsed()) {
1785 return false;
1786 }
1787
1788 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>())
1789 return false;
1790
1791 if (isa<LabelDecl>(D))
1792 return true;
1793
1794 // Except for labels, we only care about unused decls that are local to
1795 // functions.
1796 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1797 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1798 // For dependent types, the diagnostic is deferred.
1799 WithinFunction =
1800 WithinFunction || (R->isLocalClass() && !R->isDependentType());
1801 if (!WithinFunction)
1802 return false;
1803
1804 if (isa<TypedefNameDecl>(D))
1805 return true;
1806
1807 // White-list anything that isn't a local variable.
1808 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1809 return false;
1810
1811 // Types of valid local variables should be complete, so this should succeed.
1812 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1813
1814 // White-list anything with an __attribute__((unused)) type.
1815 const auto *Ty = VD->getType().getTypePtr();
1816
1817 // Only look at the outermost level of typedef.
1818 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1819 if (TT->getDecl()->hasAttr<UnusedAttr>())
1820 return false;
1821 }
1822
1823 // If we failed to complete the type for some reason, or if the type is
1824 // dependent, don't diagnose the variable.
1825 if (Ty->isIncompleteType() || Ty->isDependentType())
1826 return false;
1827
1828 // Look at the element type to ensure that the warning behaviour is
1829 // consistent for both scalars and arrays.
1830 Ty = Ty->getBaseElementTypeUnsafe();
1831
1832 if (const TagType *TT = Ty->getAs<TagType>()) {
1833 const TagDecl *Tag = TT->getDecl();
1834 if (Tag->hasAttr<UnusedAttr>())
1835 return false;
1836
1837 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1838 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1839 return false;
1840
1841 if (const Expr *Init = VD->getInit()) {
1842 if (const ExprWithCleanups *Cleanups =
1843 dyn_cast<ExprWithCleanups>(Init))
1844 Init = Cleanups->getSubExpr();
1845 const CXXConstructExpr *Construct =
1846 dyn_cast<CXXConstructExpr>(Init);
1847 if (Construct && !Construct->isElidable()) {
1848 CXXConstructorDecl *CD = Construct->getConstructor();
1849 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1850 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1851 return false;
1852 }
1853
1854 // Suppress the warning if we don't know how this is constructed, and
1855 // it could possibly be non-trivial constructor.
1856 if (Init->isTypeDependent())
1857 for (const CXXConstructorDecl *Ctor : RD->ctors())
1858 if (!Ctor->isTrivial())
1859 return false;
1860 }
1861 }
1862 }
1863
1864 // TODO: __attribute__((unused)) templates?
1865 }
1866
1867 return true;
1868}
1869
1870static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1871 FixItHint &Hint) {
1872 if (isa<LabelDecl>(D)) {
1873 SourceLocation AfterColon = Lexer::findLocationAfterToken(
1874 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1875 true);
1876 if (AfterColon.isInvalid())
1877 return;
1878 Hint = FixItHint::CreateRemoval(
1879 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1880 }
1881}
1882
1883void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1884 if (D->getTypeForDecl()->isDependentType())
1885 return;
1886
1887 for (auto *TmpD : D->decls()) {
1888 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1889 DiagnoseUnusedDecl(T);
1890 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1891 DiagnoseUnusedNestedTypedefs(R);
1892 }
1893}
1894
1895/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1896/// unless they are marked attr(unused).
1897void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1898 if (!ShouldDiagnoseUnusedDecl(D))
1899 return;
1900
1901 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1902 // typedefs can be referenced later on, so the diagnostics are emitted
1903 // at end-of-translation-unit.
1904 UnusedLocalTypedefNameCandidates.insert(TD);
1905 return;
1906 }
1907
1908 FixItHint Hint;
1909 GenerateFixForUnusedDecl(D, Context, Hint);
1910
1911 unsigned DiagID;
1912 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1913 DiagID = diag::warn_unused_exception_param;
1914 else if (isa<LabelDecl>(D))
1915 DiagID = diag::warn_unused_label;
1916 else
1917 DiagID = diag::warn_unused_variable;
1918
1919 Diag(D->getLocation(), DiagID) << D << Hint;
1920}
1921
1922void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD) {
1923 // If it's not referenced, it can't be set.
1924 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>())
1925 return;
1926
1927 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
1928
1929 if (Ty->isReferenceType() || Ty->isDependentType())
1930 return;
1931
1932 if (const TagType *TT = Ty->getAs<TagType>()) {
1933 const TagDecl *Tag = TT->getDecl();
1934 if (Tag->hasAttr<UnusedAttr>())
1935 return;
1936 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
1937 // mimic gcc's behavior.
1938 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1939 if (!RD->hasAttr<WarnUnusedAttr>())
1940 return;
1941 }
1942 }
1943
1944 auto iter = RefsMinusAssignments.find(VD);
1945 if (iter == RefsMinusAssignments.end())
1946 return;
1947
1948 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 1949, __extension__ __PRETTY_FUNCTION__))
1949 "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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 1949, __extension__ __PRETTY_FUNCTION__))
;
1950 if (iter->getSecond() != 0)
1951 return;
1952 unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
1953 : diag::warn_unused_but_set_variable;
1954 Diag(VD->getLocation(), DiagID) << VD;
1955}
1956
1957static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1958 // Verify that we have no forward references left. If so, there was a goto
1959 // or address of a label taken, but no definition of it. Label fwd
1960 // definitions are indicated with a null substmt which is also not a resolved
1961 // MS inline assembly label name.
1962 bool Diagnose = false;
1963 if (L->isMSAsmLabel())
1964 Diagnose = !L->isResolvedMSAsmLabel();
1965 else
1966 Diagnose = L->getStmt() == nullptr;
1967 if (Diagnose)
1968 S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L;
1969}
1970
1971void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1972 S->mergeNRVOIntoParent();
1973
1974 if (S->decl_empty()) return;
1975 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!\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 1976, __extension__ __PRETTY_FUNCTION__))
1976 "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!\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 1976, __extension__ __PRETTY_FUNCTION__))
;
1977
1978 for (auto *TmpD : S->decls()) {
1979 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??\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 1979, __extension__ __PRETTY_FUNCTION__))
;
1980
1981 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?\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 1981, __extension__ __PRETTY_FUNCTION__))
;
1982 NamedDecl *D = cast<NamedDecl>(TmpD);
1983
1984 // Diagnose unused variables in this scope.
1985 if (!S->hasUnrecoverableErrorOccurred()) {
1986 DiagnoseUnusedDecl(D);
1987 if (const auto *RD = dyn_cast<RecordDecl>(D))
1988 DiagnoseUnusedNestedTypedefs(RD);
1989 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1990 DiagnoseUnusedButSetDecl(VD);
1991 RefsMinusAssignments.erase(VD);
1992 }
1993 }
1994
1995 if (!D->getDeclName()) continue;
1996
1997 // If this was a forward reference to a label, verify it was defined.
1998 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1999 CheckPoppedLabel(LD, *this);
2000
2001 // Remove this name from our lexical scope, and warn on it if we haven't
2002 // already.
2003 IdResolver.RemoveDecl(D);
2004 auto ShadowI = ShadowingDecls.find(D);
2005 if (ShadowI != ShadowingDecls.end()) {
2006 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2007 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
2008 << D << FD << FD->getParent();
2009 Diag(FD->getLocation(), diag::note_previous_declaration);
2010 }
2011 ShadowingDecls.erase(ShadowI);
2012 }
2013 }
2014}
2015
2016/// Look for an Objective-C class in the translation unit.
2017///
2018/// \param Id The name of the Objective-C class we're looking for. If
2019/// typo-correction fixes this name, the Id will be updated
2020/// to the fixed name.
2021///
2022/// \param IdLoc The location of the name in the translation unit.
2023///
2024/// \param DoTypoCorrection If true, this routine will attempt typo correction
2025/// if there is no class with the given name.
2026///
2027/// \returns The declaration of the named Objective-C class, or NULL if the
2028/// class could not be found.
2029ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
2030 SourceLocation IdLoc,
2031 bool DoTypoCorrection) {
2032 // The third "scope" argument is 0 since we aren't enabling lazy built-in
2033 // creation from this context.
2034 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
2035
2036 if (!IDecl && DoTypoCorrection) {
2037 // Perform typo correction at the given location, but only if we
2038 // find an Objective-C class name.
2039 DeclFilterCCC<ObjCInterfaceDecl> CCC{};
2040 if (TypoCorrection C =
2041 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
2042 TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
2043 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
2044 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
2045 Id = IDecl->getIdentifier();
2046 }
2047 }
2048 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
2049 // This routine must always return a class definition, if any.
2050 if (Def && Def->getDefinition())
2051 Def = Def->getDefinition();
2052 return Def;
2053}
2054
2055/// getNonFieldDeclScope - Retrieves the innermost scope, starting
2056/// from S, where a non-field would be declared. This routine copes
2057/// with the difference between C and C++ scoping rules in structs and
2058/// unions. For example, the following code is well-formed in C but
2059/// ill-formed in C++:
2060/// @code
2061/// struct S6 {
2062/// enum { BAR } e;
2063/// };
2064///
2065/// void test_S6() {
2066/// struct S6 a;
2067/// a.e = BAR;
2068/// }
2069/// @endcode
2070/// For the declaration of BAR, this routine will return a different
2071/// scope. The scope S will be the scope of the unnamed enumeration
2072/// within S6. In C++, this routine will return the scope associated
2073/// with S6, because the enumeration's scope is a transparent
2074/// context but structures can contain non-field names. In C, this
2075/// routine will return the translation unit scope, since the
2076/// enumeration's scope is a transparent context and structures cannot
2077/// contain non-field names.
2078Scope *Sema::getNonFieldDeclScope(Scope *S) {
2079 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2080 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2081 (S->isClassScope() && !getLangOpts().CPlusPlus))
2082 S = S->getParent();
2083 return S;
2084}
2085
2086static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2087 ASTContext::GetBuiltinTypeError Error) {
2088 switch (Error) {
2089 case ASTContext::GE_None:
2090 return "";
2091 case ASTContext::GE_Missing_type:
2092 return BuiltinInfo.getHeaderName(ID);
2093 case ASTContext::GE_Missing_stdio:
2094 return "stdio.h";
2095 case ASTContext::GE_Missing_setjmp:
2096 return "setjmp.h";
2097 case ASTContext::GE_Missing_ucontext:
2098 return "ucontext.h";
2099 }
2100 llvm_unreachable("unhandled error kind")::llvm::llvm_unreachable_internal("unhandled error kind", "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 2100)
;
2101}
2102
2103FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2104 unsigned ID, SourceLocation Loc) {
2105 DeclContext *Parent = Context.getTranslationUnitDecl();
2106
2107 if (getLangOpts().CPlusPlus) {
2108 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2109 Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
2110 CLinkageDecl->setImplicit();
2111 Parent->addDecl(CLinkageDecl);
2112 Parent = CLinkageDecl;
2113 }
2114
2115 FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2116 /*TInfo=*/nullptr, SC_Extern,
2117 getCurFPFeatures().isFPConstrained(),
2118 false, Type->isFunctionProtoType());
2119 New->setImplicit();
2120 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2121
2122 // Create Decl objects for each parameter, adding them to the
2123 // FunctionDecl.
2124 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2125 SmallVector<ParmVarDecl *, 16> Params;
2126 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2127 ParmVarDecl *parm = ParmVarDecl::Create(
2128 Context, New, SourceLocation(), SourceLocation(), nullptr,
2129 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2130 parm->setScopeInfo(0, i);
2131 Params.push_back(parm);
2132 }
2133 New->setParams(Params);
2134 }
2135
2136 AddKnownFunctionAttributes(New);
2137 return New;
2138}
2139
2140/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2141/// file scope. lazily create a decl for it. ForRedeclaration is true
2142/// if we're creating this built-in in anticipation of redeclaring the
2143/// built-in.
2144NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2145 Scope *S, bool ForRedeclaration,
2146 SourceLocation Loc) {
2147 LookupNecessaryTypesForBuiltin(S, ID);
2148
2149 ASTContext::GetBuiltinTypeError Error;
2150 QualType R = Context.GetBuiltinType(ID, Error);
2151 if (Error) {
2152 if (!ForRedeclaration)
2153 return nullptr;
2154
2155 // If we have a builtin without an associated type we should not emit a
2156 // warning when we were not able to find a type for it.
2157 if (Error == ASTContext::GE_Missing_type ||
2158 Context.BuiltinInfo.allowTypeMismatch(ID))
2159 return nullptr;
2160
2161 // If we could not find a type for setjmp it is because the jmp_buf type was
2162 // not defined prior to the setjmp declaration.
2163 if (Error == ASTContext::GE_Missing_setjmp) {
2164 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2165 << Context.BuiltinInfo.getName(ID);
2166 return nullptr;
2167 }
2168
2169 // Generally, we emit a warning that the declaration requires the
2170 // appropriate header.
2171 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2172 << getHeaderName(Context.BuiltinInfo, ID, Error)
2173 << Context.BuiltinInfo.getName(ID);
2174 return nullptr;
2175 }
2176
2177 if (!ForRedeclaration &&
2178 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2179 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2180 Diag(Loc, diag::ext_implicit_lib_function_decl)
2181 << Context.BuiltinInfo.getName(ID) << R;
2182 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2183 Diag(Loc, diag::note_include_header_or_declare)
2184 << Header << Context.BuiltinInfo.getName(ID);
2185 }
2186
2187 if (R.isNull())
2188 return nullptr;
2189
2190 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2191 RegisterLocallyScopedExternCDecl(New, S);
2192
2193 // TUScope is the translation-unit scope to insert this function into.
2194 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2195 // relate Scopes to DeclContexts, and probably eliminate CurContext
2196 // entirely, but we're not there yet.
2197 DeclContext *SavedContext = CurContext;
2198 CurContext = New->getDeclContext();
2199 PushOnScopeChains(New, TUScope);
2200 CurContext = SavedContext;
2201 return New;
2202}
2203
2204/// Typedef declarations don't have linkage, but they still denote the same
2205/// entity if their types are the same.
2206/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2207/// isSameEntity.
2208static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2209 TypedefNameDecl *Decl,
2210 LookupResult &Previous) {
2211 // This is only interesting when modules are enabled.
2212 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2213 return;
2214
2215 // Empty sets are uninteresting.
2216 if (Previous.empty())
2217 return;
2218
2219 LookupResult::Filter Filter = Previous.makeFilter();
2220 while (Filter.hasNext()) {
2221 NamedDecl *Old = Filter.next();
2222
2223 // Non-hidden declarations are never ignored.
2224 if (S.isVisible(Old))
2225 continue;
2226
2227 // Declarations of the same entity are not ignored, even if they have
2228 // different linkages.
2229 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2230 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2231 Decl->getUnderlyingType()))
2232 continue;
2233
2234 // If both declarations give a tag declaration a typedef name for linkage
2235 // purposes, then they declare the same entity.
2236 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2237 Decl->getAnonDeclWithTypedefName())
2238 continue;
2239 }
2240
2241 Filter.erase();
2242 }
2243
2244 Filter.done();
2245}
2246
2247bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2248 QualType OldType;
2249 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2250 OldType = OldTypedef->getUnderlyingType();
2251 else
2252 OldType = Context.getTypeDeclType(Old);
2253 QualType NewType = New->getUnderlyingType();
2254
2255 if (NewType->isVariablyModifiedType()) {
2256 // Must not redefine a typedef with a variably-modified type.
2257 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2258 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2259 << Kind << NewType;
2260 if (Old->getLocation().isValid())
2261 notePreviousDefinition(Old, New->getLocation());
2262 New->setInvalidDecl();
2263 return true;
2264 }
2265
2266 if (OldType != NewType &&
2267 !OldType->isDependentType() &&
2268 !NewType->isDependentType() &&
2269 !Context.hasSameType(OldType, NewType)) {
2270 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2271 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2272 << Kind << NewType << OldType;
2273 if (Old->getLocation().isValid())
2274 notePreviousDefinition(Old, New->getLocation());
2275 New->setInvalidDecl();
2276 return true;
2277 }
2278 return false;
2279}
2280
2281/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2282/// same name and scope as a previous declaration 'Old'. Figure out
2283/// how to resolve this situation, merging decls or emitting
2284/// diagnostics as appropriate. If there was an error, set New to be invalid.
2285///
2286void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2287 LookupResult &OldDecls) {
2288 // If the new decl is known invalid already, don't bother doing any
2289 // merging checks.
2290 if (New->isInvalidDecl()) return;
2291
2292 // Allow multiple definitions for ObjC built-in typedefs.
2293 // FIXME: Verify the underlying types are equivalent!
2294 if (getLangOpts().ObjC) {
2295 const IdentifierInfo *TypeID = New->getIdentifier();
2296 switch (TypeID->getLength()) {
2297 default: break;
2298 case 2:
2299 {
2300 if (!TypeID->isStr("id"))
2301 break;
2302 QualType T = New->getUnderlyingType();
2303 if (!T->isPointerType())
2304 break;
2305 if (!T->isVoidPointerType()) {
2306 QualType PT = T->castAs<PointerType>()->getPointeeType();
2307 if (!PT->isStructureType())
2308 break;
2309 }
2310 Context.setObjCIdRedefinitionType(T);
2311 // Install the built-in type for 'id', ignoring the current definition.
2312 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2313 return;
2314 }
2315 case 5:
2316 if (!TypeID->isStr("Class"))
2317 break;
2318 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2319 // Install the built-in type for 'Class', ignoring the current definition.
2320 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2321 return;
2322 case 3:
2323 if (!TypeID->isStr("SEL"))
2324 break;
2325 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2326 // Install the built-in type for 'SEL', ignoring the current definition.
2327 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2328 return;
2329 }
2330 // Fall through - the typedef name was not a builtin type.
2331 }
2332
2333 // Verify the old decl was also a type.
2334 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2335 if (!Old) {
2336 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2337 << New->getDeclName();
2338
2339 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2340 if (OldD->getLocation().isValid())
2341 notePreviousDefinition(OldD, New->getLocation());
2342
2343 return New->setInvalidDecl();
2344 }
2345
2346 // If the old declaration is invalid, just give up here.
2347 if (Old->isInvalidDecl())
2348 return New->setInvalidDecl();
2349
2350 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2351 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2352 auto *NewTag = New->getAnonDeclWithTypedefName();
2353 NamedDecl *Hidden = nullptr;
2354 if (OldTag && NewTag &&
2355 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2356 !hasVisibleDefinition(OldTag, &Hidden)) {
2357 // There is a definition of this tag, but it is not visible. Use it
2358 // instead of our tag.
2359 New->setTypeForDecl(OldTD->getTypeForDecl());
2360 if (OldTD->isModed())
2361 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2362 OldTD->getUnderlyingType());
2363 else
2364 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2365
2366 // Make the old tag definition visible.
2367 makeMergedDefinitionVisible(Hidden);
2368
2369 // If this was an unscoped enumeration, yank all of its enumerators
2370 // out of the scope.
2371 if (isa<EnumDecl>(NewTag)) {
2372 Scope *EnumScope = getNonFieldDeclScope(S);
2373 for (auto *D : NewTag->decls()) {
2374 auto *ED = cast<EnumConstantDecl>(D);
2375 assert(EnumScope->isDeclScope(ED))(static_cast <bool> (EnumScope->isDeclScope(ED)) ? void
(0) : __assert_fail ("EnumScope->isDeclScope(ED)", "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 2375, __extension__ __PRETTY_FUNCTION__))
;
2376 EnumScope->RemoveDecl(ED);
2377 IdResolver.RemoveDecl(ED);
2378 ED->getLexicalDeclContext()->removeDecl(ED);
2379 }
2380 }
2381 }
2382 }
2383
2384 // If the typedef types are not identical, reject them in all languages and
2385 // with any extensions enabled.
2386 if (isIncompatibleTypedef(Old, New))
2387 return;
2388
2389 // The types match. Link up the redeclaration chain and merge attributes if
2390 // the old declaration was a typedef.
2391 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2392 New->setPreviousDecl(Typedef);
2393 mergeDeclAttributes(New, Old);
2394 }
2395
2396 if (getLangOpts().MicrosoftExt)
2397 return;
2398
2399 if (getLangOpts().CPlusPlus) {
2400 // C++ [dcl.typedef]p2:
2401 // In a given non-class scope, a typedef specifier can be used to
2402 // redefine the name of any type declared in that scope to refer
2403 // to the type to which it already refers.
2404 if (!isa<CXXRecordDecl>(CurContext))
2405 return;
2406
2407 // C++0x [dcl.typedef]p4:
2408 // In a given class scope, a typedef specifier can be used to redefine
2409 // any class-name declared in that scope that is not also a typedef-name
2410 // to refer to the type to which it already refers.
2411 //
2412 // This wording came in via DR424, which was a correction to the
2413 // wording in DR56, which accidentally banned code like:
2414 //
2415 // struct S {
2416 // typedef struct A { } A;
2417 // };
2418 //
2419 // in the C++03 standard. We implement the C++0x semantics, which
2420 // allow the above but disallow
2421 //
2422 // struct S {
2423 // typedef int I;
2424 // typedef int I;
2425 // };
2426 //
2427 // since that was the intent of DR56.
2428 if (!isa<TypedefNameDecl>(Old))
2429 return;
2430
2431 Diag(New->getLocation(), diag::err_redefinition)
2432 << New->getDeclName();
2433 notePreviousDefinition(Old, New->getLocation());
2434 return New->setInvalidDecl();
2435 }
2436
2437 // Modules always permit redefinition of typedefs, as does C11.
2438 if (getLangOpts().Modules || getLangOpts().C11)
2439 return;
2440
2441 // If we have a redefinition of a typedef in C, emit a warning. This warning
2442 // is normally mapped to an error, but can be controlled with
2443 // -Wtypedef-redefinition. If either the original or the redefinition is
2444 // in a system header, don't emit this for compatibility with GCC.
2445 if (getDiagnostics().getSuppressSystemWarnings() &&
2446 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2447 (Old->isImplicit() ||
2448 Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2449 Context.getSourceManager().isInSystemHeader(New->getLocation())))
2450 return;
2451
2452 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2453 << New->getDeclName();
2454 notePreviousDefinition(Old, New->getLocation());
2455}
2456
2457/// DeclhasAttr - returns true if decl Declaration already has the target
2458/// attribute.
2459static bool DeclHasAttr(const Decl *D, const Attr *A) {
2460 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2461 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2462 for (const auto *i : D->attrs())
2463 if (i->getKind() == A->getKind()) {
2464 if (Ann) {
2465 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2466 return true;
2467 continue;
2468 }
2469 // FIXME: Don't hardcode this check
2470 if (OA && isa<OwnershipAttr>(i))
2471 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2472 return true;
2473 }
2474
2475 return false;
2476}
2477
2478static bool isAttributeTargetADefinition(Decl *D) {
2479 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2480 return VD->isThisDeclarationADefinition();
2481 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2482 return TD->isCompleteDefinition() || TD->isBeingDefined();
2483 return true;
2484}
2485
2486/// Merge alignment attributes from \p Old to \p New, taking into account the
2487/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2488///
2489/// \return \c true if any attributes were added to \p New.
2490static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2491 // Look for alignas attributes on Old, and pick out whichever attribute
2492 // specifies the strictest alignment requirement.
2493 AlignedAttr *OldAlignasAttr = nullptr;
2494 AlignedAttr *OldStrictestAlignAttr = nullptr;
2495 unsigned OldAlign = 0;
2496 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2497 // FIXME: We have no way of representing inherited dependent alignments
2498 // in a case like:
2499 // template<int A, int B> struct alignas(A) X;
2500 // template<int A, int B> struct alignas(B) X {};
2501 // For now, we just ignore any alignas attributes which are not on the
2502 // definition in such a case.
2503 if (I->isAlignmentDependent())
2504 return false;
2505
2506 if (I->isAlignas())
2507 OldAlignasAttr = I;
2508
2509 unsigned Align = I->getAlignment(S.Context);
2510 if (Align > OldAlign) {
2511 OldAlign = Align;
2512 OldStrictestAlignAttr = I;
2513 }
2514 }
2515
2516 // Look for alignas attributes on New.
2517 AlignedAttr *NewAlignasAttr = nullptr;
2518 unsigned NewAlign = 0;
2519 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2520 if (I->isAlignmentDependent())
2521 return false;
2522
2523 if (I->isAlignas())
2524 NewAlignasAttr = I;
2525
2526 unsigned Align = I->getAlignment(S.Context);
2527 if (Align > NewAlign)
2528 NewAlign = Align;
2529 }
2530
2531 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2532 // Both declarations have 'alignas' attributes. We require them to match.
2533 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2534 // fall short. (If two declarations both have alignas, they must both match
2535 // every definition, and so must match each other if there is a definition.)
2536
2537 // If either declaration only contains 'alignas(0)' specifiers, then it
2538 // specifies the natural alignment for the type.
2539 if (OldAlign == 0 || NewAlign == 0) {
2540 QualType Ty;
2541 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2542 Ty = VD->getType();
2543 else
2544 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2545
2546 if (OldAlign == 0)
2547 OldAlign = S.Context.getTypeAlign(Ty);
2548 if (NewAlign == 0)
2549 NewAlign = S.Context.getTypeAlign(Ty);
2550 }
2551
2552 if (OldAlign != NewAlign) {
2553 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2554 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2555 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2556 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2557 }
2558 }
2559
2560 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2561 // C++11 [dcl.align]p6:
2562 // if any declaration of an entity has an alignment-specifier,
2563 // every defining declaration of that entity shall specify an
2564 // equivalent alignment.
2565 // C11 6.7.5/7:
2566 // If the definition of an object does not have an alignment
2567 // specifier, any other declaration of that object shall also
2568 // have no alignment specifier.
2569 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2570 << OldAlignasAttr;
2571 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2572 << OldAlignasAttr;
2573 }
2574
2575 bool AnyAdded = false;
2576
2577 // Ensure we have an attribute representing the strictest alignment.
2578 if (OldAlign > NewAlign) {
2579 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2580 Clone->setInherited(true);
2581 New->addAttr(Clone);
2582 AnyAdded = true;
2583 }
2584
2585 // Ensure we have an alignas attribute if the old declaration had one.
2586 if (OldAlignasAttr && !NewAlignasAttr &&
2587 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2588 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2589 Clone->setInherited(true);
2590 New->addAttr(Clone);
2591 AnyAdded = true;
2592 }
2593
2594 return AnyAdded;
2595}
2596
2597#define WANT_DECL_MERGE_LOGIC
2598#include "clang/Sema/AttrParsedAttrImpl.inc"
2599#undef WANT_DECL_MERGE_LOGIC
2600
2601static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2602 const InheritableAttr *Attr,
2603 Sema::AvailabilityMergeKind AMK) {
2604 // Diagnose any mutual exclusions between the attribute that we want to add
2605 // and attributes that already exist on the declaration.
2606 if (!DiagnoseMutualExclusions(S, D, Attr))
2607 return false;
2608
2609 // This function copies an attribute Attr from a previous declaration to the
2610 // new declaration D if the new declaration doesn't itself have that attribute
2611 // yet or if that attribute allows duplicates.
2612 // If you're adding a new attribute that requires logic different from
2613 // "use explicit attribute on decl if present, else use attribute from
2614 // previous decl", for example if the attribute needs to be consistent
2615 // between redeclarations, you need to call a custom merge function here.
2616 InheritableAttr *NewAttr = nullptr;
2617 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2618 NewAttr = S.mergeAvailabilityAttr(
2619 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2620 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2621 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2622 AA->getPriority());
2623 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2624 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2625 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2626 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2627 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2628 NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2629 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2630 NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2631 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2632 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2633 FA->getFirstArg());
2634 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2635 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2636 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2637 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2638 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2639 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2640 IA->getInheritanceModel());
2641 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2642 NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2643 &S.Context.Idents.get(AA->getSpelling()));
2644 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2645 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2646 isa<CUDAGlobalAttr>(Attr))) {
2647 // CUDA target attributes are part of function signature for
2648 // overloading purposes and must not be merged.
2649 return false;
2650 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2651 NewAttr = S.mergeMinSizeAttr(D, *MA);
2652 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2653 NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2654 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2655 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2656 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2657 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2658 else if (isa<AlignedAttr>(Attr))
2659 // AlignedAttrs are handled separately, because we need to handle all
2660 // such attributes on a declaration at the same time.
2661 NewAttr = nullptr;
2662 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2663 (AMK == Sema::AMK_Override ||
2664 AMK == Sema::AMK_ProtocolImplementation ||
2665 AMK == Sema::AMK_OptionalProtocolImplementation))
2666 NewAttr = nullptr;
2667 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2668 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2669 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2670 NewAttr = S.mergeImportModuleAttr(D, *IMA);
2671 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2672 NewAttr = S.mergeImportNameAttr(D, *INA);
2673 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2674 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2675 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2676 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2677 else if (const auto *BTFA = dyn_cast<BTFTagAttr>(Attr))
2678 NewAttr = S.mergeBTFTagAttr(D, *BTFA);
2679 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2680 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2681
2682 if (NewAttr) {
2683 NewAttr->setInherited(true);
2684 D->addAttr(NewAttr);
2685 if (isa<MSInheritanceAttr>(NewAttr))
2686 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2687 return true;
2688 }
2689
2690 return false;
2691}
2692
2693static const NamedDecl *getDefinition(const Decl *D) {
2694 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2695 return TD->getDefinition();
2696 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2697 const VarDecl *Def = VD->getDefinition();
2698 if (Def)
2699 return Def;
2700 return VD->getActingDefinition();
2701 }
2702 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2703 const FunctionDecl *Def = nullptr;
2704 if (FD->isDefined(Def, true))
2705 return Def;
2706 }
2707 return nullptr;
2708}
2709
2710static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2711 for (const auto *Attribute : D->attrs())
2712 if (Attribute->getKind() == Kind)
2713 return true;
2714 return false;
2715}
2716
2717/// checkNewAttributesAfterDef - If we already have a definition, check that
2718/// there are no new attributes in this declaration.
2719static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2720 if (!New->hasAttrs())
2721 return;
2722
2723 const NamedDecl *Def = getDefinition(Old);
2724 if (!Def || Def == New)
2725 return;
2726
2727 AttrVec &NewAttributes = New->getAttrs();
2728 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2729 const Attr *NewAttribute = NewAttributes[I];
2730
2731 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2732 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2733 Sema::SkipBodyInfo SkipBody;
2734 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2735
2736 // If we're skipping this definition, drop the "alias" attribute.
2737 if (SkipBody.ShouldSkip) {
2738 NewAttributes.erase(NewAttributes.begin() + I);
2739 --E;
2740 continue;
2741 }
2742 } else {
2743 VarDecl *VD = cast<VarDecl>(New);
2744 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2745 VarDecl::TentativeDefinition
2746 ? diag::err_alias_after_tentative
2747 : diag::err_redefinition;
2748 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2749 if (Diag == diag::err_redefinition)
2750 S.notePreviousDefinition(Def, VD->getLocation());
2751 else
2752 S.Diag(Def->getLocation(), diag::note_previous_definition);
2753 VD->setInvalidDecl();
2754 }
2755 ++I;
2756 continue;
2757 }
2758
2759 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2760 // Tentative definitions are only interesting for the alias check above.
2761 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2762 ++I;
2763 continue;
2764 }
2765 }
2766
2767 if (hasAttribute(Def, NewAttribute->getKind())) {
2768 ++I;
2769 continue; // regular attr merging will take care of validating this.
2770 }
2771
2772 if (isa<C11NoReturnAttr>(NewAttribute)) {
2773 // C's _Noreturn is allowed to be added to a function after it is defined.
2774 ++I;
2775 continue;
2776 } else if (isa<UuidAttr>(NewAttribute)) {
2777 // msvc will allow a subsequent definition to add an uuid to a class
2778 ++I;
2779 continue;
2780 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2781 if (AA->isAlignas()) {
2782 // C++11 [dcl.align]p6:
2783 // if any declaration of an entity has an alignment-specifier,
2784 // every defining declaration of that entity shall specify an
2785 // equivalent alignment.
2786 // C11 6.7.5/7:
2787 // If the definition of an object does not have an alignment
2788 // specifier, any other declaration of that object shall also
2789 // have no alignment specifier.
2790 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2791 << AA;
2792 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2793 << AA;
2794 NewAttributes.erase(NewAttributes.begin() + I);
2795 --E;
2796 continue;
2797 }
2798 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2799 // If there is a C definition followed by a redeclaration with this
2800 // attribute then there are two different definitions. In C++, prefer the
2801 // standard diagnostics.
2802 if (!S.getLangOpts().CPlusPlus) {
2803 S.Diag(NewAttribute->getLocation(),
2804 diag::err_loader_uninitialized_redeclaration);
2805 S.Diag(Def->getLocation(), diag::note_previous_definition);
2806 NewAttributes.erase(NewAttributes.begin() + I);
2807 --E;
2808 continue;
2809 }
2810 } else if (isa<SelectAnyAttr>(NewAttribute) &&
2811 cast<VarDecl>(New)->isInline() &&
2812 !cast<VarDecl>(New)->isInlineSpecified()) {
2813 // Don't warn about applying selectany to implicitly inline variables.
2814 // Older compilers and language modes would require the use of selectany
2815 // to make such variables inline, and it would have no effect if we
2816 // honored it.
2817 ++I;
2818 continue;
2819 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
2820 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
2821 // declarations after defintions.
2822 ++I;
2823 continue;
2824 }
2825
2826 S.Diag(NewAttribute->getLocation(),
2827 diag::warn_attribute_precede_definition);
2828 S.Diag(Def->getLocation(), diag::note_previous_definition);
2829 NewAttributes.erase(NewAttributes.begin() + I);
2830 --E;
2831 }
2832}
2833
2834static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2835 const ConstInitAttr *CIAttr,
2836 bool AttrBeforeInit) {
2837 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2838
2839 // Figure out a good way to write this specifier on the old declaration.
2840 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2841 // enough of the attribute list spelling information to extract that without
2842 // heroics.
2843 std::string SuitableSpelling;
2844 if (S.getLangOpts().CPlusPlus20)
2845 SuitableSpelling = std::string(
2846 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2847 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2848 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2849 InsertLoc, {tok::l_square, tok::l_square,
2850 S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2851 S.PP.getIdentifierInfo("require_constant_initialization"),
2852 tok::r_square, tok::r_square}));
2853 if (SuitableSpelling.empty())
2854 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2855 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2856 S.PP.getIdentifierInfo("require_constant_initialization"),
2857 tok::r_paren, tok::r_paren}));
2858 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
2859 SuitableSpelling = "constinit";
2860 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2861 SuitableSpelling = "[[clang::require_constant_initialization]]";
2862 if (SuitableSpelling.empty())
2863 SuitableSpelling = "__attribute__((require_constant_initialization))";
2864 SuitableSpelling += " ";
2865
2866 if (AttrBeforeInit) {
2867 // extern constinit int a;
2868 // int a = 0; // error (missing 'constinit'), accepted as extension
2869 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 2869, __extension__ __PRETTY_FUNCTION__))
;
2870 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2871 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2872 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2873 } else {
2874 // int a = 0;
2875 // constinit extern int a; // error (missing 'constinit')
2876 S.Diag(CIAttr->getLocation(),
2877 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2878 : diag::warn_require_const_init_added_too_late)
2879 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2880 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2881 << CIAttr->isConstinit()
2882 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2883 }
2884}
2885
2886/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2887void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2888 AvailabilityMergeKind AMK) {
2889 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2890 UsedAttr *NewAttr = OldAttr->clone(Context);
2891 NewAttr->setInherited(true);
2892 New->addAttr(NewAttr);
2893 }
2894 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
2895 RetainAttr *NewAttr = OldAttr->clone(Context);
2896 NewAttr->setInherited(true);
2897 New->addAttr(NewAttr);
2898 }
2899
2900 if (!Old->hasAttrs() && !New->hasAttrs())
2901 return;
2902
2903 // [dcl.constinit]p1:
2904 // If the [constinit] specifier is applied to any declaration of a
2905 // variable, it shall be applied to the initializing declaration.
2906 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
2907 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
2908 if (bool(OldConstInit) != bool(NewConstInit)) {
2909 const auto *OldVD = cast<VarDecl>(Old);
2910 auto *NewVD = cast<VarDecl>(New);
2911
2912 // Find the initializing declaration. Note that we might not have linked
2913 // the new declaration into the redeclaration chain yet.
2914 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
2915 if (!InitDecl &&
2916 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
2917 InitDecl = NewVD;
2918
2919 if (InitDecl == NewVD) {
2920 // This is the initializing declaration. If it would inherit 'constinit',
2921 // that's ill-formed. (Note that we do not apply this to the attribute
2922 // form).
2923 if (OldConstInit && OldConstInit->isConstinit())
2924 diagnoseMissingConstinit(*this, NewVD, OldConstInit,
2925 /*AttrBeforeInit=*/true);
2926 } else if (NewConstInit) {
2927 // This is the first time we've been told that this declaration should
2928 // have a constant initializer. If we already saw the initializing
2929 // declaration, this is too late.
2930 if (InitDecl && InitDecl != NewVD) {
2931 diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
2932 /*AttrBeforeInit=*/false);
2933 NewVD->dropAttr<ConstInitAttr>();
2934 }
2935 }
2936 }
2937
2938 // Attributes declared post-definition are currently ignored.
2939 checkNewAttributesAfterDef(*this, New, Old);
2940
2941 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2942 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2943 if (!OldA->isEquivalent(NewA)) {
2944 // This redeclaration changes __asm__ label.
2945 Diag(New->getLocation(), diag::err_different_asm_label);
2946 Diag(OldA->getLocation(), diag::note_previous_declaration);
2947 }
2948 } else if (Old->isUsed()) {
2949 // This redeclaration adds an __asm__ label to a declaration that has
2950 // already been ODR-used.
2951 Diag(New->getLocation(), diag::err_late_asm_label_name)
2952 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2953 }
2954 }
2955
2956 // Re-declaration cannot add abi_tag's.
2957 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2958 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2959 for (const auto &NewTag : NewAbiTagAttr->tags()) {
2960 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2961 NewTag) == OldAbiTagAttr->tags_end()) {
2962 Diag(NewAbiTagAttr->getLocation(),
2963 diag::err_new_abi_tag_on_redeclaration)
2964 << NewTag;
2965 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2966 }
2967 }
2968 } else {
2969 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2970 Diag(Old->getLocation(), diag::note_previous_declaration);
2971 }
2972 }
2973
2974 // This redeclaration adds a section attribute.
2975 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2976 if (auto *VD = dyn_cast<VarDecl>(New)) {
2977 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2978 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2979 Diag(Old->getLocation(), diag::note_previous_declaration);
2980 }
2981 }
2982 }
2983
2984 // Redeclaration adds code-seg attribute.
2985 const auto *NewCSA = New->getAttr<CodeSegAttr>();
2986 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2987 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2988 Diag(New->getLocation(), diag::warn_mismatched_section)
2989 << 0 /*codeseg*/;
2990 Diag(Old->getLocation(), diag::note_previous_declaration);
2991 }
2992
2993 if (!Old->hasAttrs())
2994 return;
2995
2996 bool foundAny = New->hasAttrs();
2997
2998 // Ensure that any moving of objects within the allocated map is done before
2999 // we process them.
3000 if (!foundAny) New->setAttrs(AttrVec());
3001
3002 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3003 // Ignore deprecated/unavailable/availability attributes if requested.
3004 AvailabilityMergeKind LocalAMK = AMK_None;
3005 if (isa<DeprecatedAttr>(I) ||
3006 isa<UnavailableAttr>(I) ||
3007 isa<AvailabilityAttr>(I)) {
3008 switch (AMK) {
3009 case AMK_None:
3010 continue;
3011
3012 case AMK_Redeclaration:
3013 case AMK_Override:
3014 case AMK_ProtocolImplementation:
3015 case AMK_OptionalProtocolImplementation:
3016 LocalAMK = AMK;
3017 break;
3018 }
3019 }
3020
3021 // Already handled.
3022 if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3023 continue;
3024
3025 if (mergeDeclAttribute(*this, New, I, LocalAMK))
3026 foundAny = true;
3027 }
3028
3029 if (mergeAlignedAttrs(*this, New, Old))
3030 foundAny = true;
3031
3032 if (!foundAny) New->dropAttrs();
3033}
3034
3035/// mergeParamDeclAttributes - Copy attributes from the old parameter
3036/// to the new one.
3037static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3038 const ParmVarDecl *oldDecl,
3039 Sema &S) {
3040 // C++11 [dcl.attr.depend]p2:
3041 // The first declaration of a function shall specify the
3042 // carries_dependency attribute for its declarator-id if any declaration
3043 // of the function specifies the carries_dependency attribute.
3044 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3045 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3046 S.Diag(CDA->getLocation(),
3047 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3048 // Find the first declaration of the parameter.
3049 // FIXME: Should we build redeclaration chains for function parameters?
3050 const FunctionDecl *FirstFD =
3051 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3052 const ParmVarDecl *FirstVD =
3053 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3054 S.Diag(FirstVD->getLocation(),
3055 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3056 }
3057
3058 if (!oldDecl->hasAttrs())
3059 return;
3060
3061 bool foundAny = newDecl->hasAttrs();
3062
3063 // Ensure that any moving of objects within the allocated map is
3064 // done before we process them.
3065 if (!foundAny) newDecl->setAttrs(AttrVec());
3066
3067 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3068 if (!DeclHasAttr(newDecl, I)) {
3069 InheritableAttr *newAttr =
3070 cast<InheritableParamAttr>(I->clone(S.Context));
3071 newAttr->setInherited(true);
3072 newDecl->addAttr(newAttr);
3073 foundAny = true;
3074 }
3075 }
3076
3077 if (!foundAny) newDecl->dropAttrs();
3078}
3079
3080static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3081 const ParmVarDecl *OldParam,
3082 Sema &S) {
3083 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3084 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3085 if (*Oldnullability != *Newnullability) {
3086 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3087 << DiagNullabilityKind(
3088 *Newnullability,
3089 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3090 != 0))
3091 << DiagNullabilityKind(
3092 *Oldnullability,
3093 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3094 != 0));
3095 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3096 }
3097 } else {
3098 QualType NewT = NewParam->getType();
3099 NewT = S.Context.getAttributedType(
3100 AttributedType::getNullabilityAttrKind(*Oldnullability),
3101 NewT, NewT);
3102 NewParam->setType(NewT);
3103 }
3104 }
3105}
3106
3107namespace {
3108
3109/// Used in MergeFunctionDecl to keep track of function parameters in
3110/// C.
3111struct GNUCompatibleParamWarning {
3112 ParmVarDecl *OldParm;
3113 ParmVarDecl *NewParm;
3114 QualType PromotedType;
3115};
3116
3117} // end anonymous namespace
3118
3119// Determine whether the previous declaration was a definition, implicit
3120// declaration, or a declaration.
3121template <typename T>
3122static std::pair<diag::kind, SourceLocation>
3123getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3124 diag::kind PrevDiag;
3125 SourceLocation OldLocation = Old->getLocation();
3126 if (Old->isThisDeclarationADefinition())
3127 PrevDiag = diag::note_previous_definition;
3128 else if (Old->isImplicit()) {
3129 PrevDiag = diag::note_previous_implicit_declaration;
3130 if (OldLocation.isInvalid())
3131 OldLocation = New->getLocation();
3132 } else
3133 PrevDiag = diag::note_previous_declaration;
3134 return std::make_pair(PrevDiag, OldLocation);
3135}
3136
3137/// canRedefineFunction - checks if a function can be redefined. Currently,
3138/// only extern inline functions can be redefined, and even then only in
3139/// GNU89 mode.
3140static bool canRedefineFunction(const FunctionDecl *FD,
3141 const LangOptions& LangOpts) {
3142 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3143 !LangOpts.CPlusPlus &&
3144 FD->isInlineSpecified() &&
3145 FD->getStorageClass() == SC_Extern);
3146}
3147
3148const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3149 const AttributedType *AT = T->getAs<AttributedType>();
3150 while (AT && !AT->isCallingConv())
3151 AT = AT->getModifiedType()->getAs<AttributedType>();
3152 return AT;
3153}
3154
3155template <typename T>
3156static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3157 const DeclContext *DC = Old->getDeclContext();
3158 if (DC->isRecord())
51
Calling 'DeclContext::isRecord'
54
Returning from 'DeclContext::isRecord'
55
Taking false branch
3159 return false;
3160
3161 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3162 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
56
Assuming 'OldLinkage' is not equal to CXXLanguageLinkage
3163 return true;
3164 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
57
Assuming 'OldLinkage' is not equal to CLanguageLinkage
3165 return true;
3166 return false;
58
Returning zero, which participates in a condition later
3167}
3168
3169template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3170static bool isExternC(VarTemplateDecl *) { return false; }
3171static bool isExternC(FunctionTemplateDecl *) { return false; }
3172
3173/// Check whether a redeclaration of an entity introduced by a
3174/// using-declaration is valid, given that we know it's not an overload
3175/// (nor a hidden tag declaration).
3176template<typename ExpectedDecl>
3177static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3178 ExpectedDecl *New) {
3179 // C++11 [basic.scope.declarative]p4:
3180 // Given a set of declarations in a single declarative region, each of
3181 // which specifies the same unqualified name,
3182 // -- they shall all refer to the same entity, or all refer to functions
3183 // and function templates; or
3184 // -- exactly one declaration shall declare a class name or enumeration
3185 // name that is not a typedef name and the other declarations shall all
3186 // refer to the same variable or enumerator, or all refer to functions
3187 // and function templates; in this case the class name or enumeration
3188 // name is hidden (3.3.10).
3189
3190 // C++11 [namespace.udecl]p14:
3191 // If a function declaration in namespace scope or block scope has the
3192 // same name and the same parameter-type-list as a function introduced
3193 // by a using-declaration, and the declarations do not declare the same
3194 // function, the program is ill-formed.
3195
3196 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3197 if (Old &&
3198 !Old->getDeclContext()->getRedeclContext()->Equals(
3199 New->getDeclContext()->getRedeclContext()) &&
3200 !(isExternC(Old) && isExternC(New)))
3201 Old = nullptr;
3202
3203 if (!Old) {
3204 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3205 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3206 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3207 return true;
3208 }
3209 return false;
3210}
3211
3212static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3213 const FunctionDecl *B) {
3214 assert(A->getNumParams() == B->getNumParams())(static_cast <bool> (A->getNumParams() == B->getNumParams
()) ? void (0) : __assert_fail ("A->getNumParams() == B->getNumParams()"
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 3214, __extension__ __PRETTY_FUNCTION__))
;
3215
3216 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3217 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3218 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3219 if (AttrA == AttrB)
3220 return true;
3221 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3222 AttrA->isDynamic() == AttrB->isDynamic();
3223 };
3224
3225 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3226}
3227
3228/// If necessary, adjust the semantic declaration context for a qualified
3229/// declaration to name the correct inline namespace within the qualifier.
3230static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3231 DeclaratorDecl *OldD) {
3232 // The only case where we need to update the DeclContext is when
3233 // redeclaration lookup for a qualified name finds a declaration
3234 // in an inline namespace within the context named by the qualifier:
3235 //
3236 // inline namespace N { int f(); }
3237 // int ::f(); // Sema DC needs adjusting from :: to N::.
3238 //
3239 // For unqualified declarations, the semantic context *can* change
3240 // along the redeclaration chain (for local extern declarations,
3241 // extern "C" declarations, and friend declarations in particular).
3242 if (!NewD->getQualifier())
4
Taking true branch
3243 return;
5
Returning without writing to 'OldD->InvalidDecl', which participates in a condition later
3244
3245 // NewD is probably already in the right context.
3246 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3247 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3248 if (NamedDC->Equals(SemaDC))
3249 return;
3250
3251 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 3253, __extension__ __PRETTY_FUNCTION__))
3252 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 3253, __extension__ __PRETTY_FUNCTION__))
3253 "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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 3253, __extension__ __PRETTY_FUNCTION__))
;
3254
3255 auto *LexDC = NewD->getLexicalDeclContext();
3256 auto FixSemaDC = [=](NamedDecl *D) {
3257 if (!D)
3258 return;
3259 D->setDeclContext(SemaDC);
3260 D->setLexicalDeclContext(LexDC);
3261 };
3262
3263 FixSemaDC(NewD);
3264 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3265 FixSemaDC(FD->getDescribedFunctionTemplate());
3266 else if (auto *VD = dyn_cast<VarDecl>(NewD))
3267 FixSemaDC(VD->getDescribedVarTemplate());
3268}
3269
3270/// MergeFunctionDecl - We just parsed a function 'New' from
3271/// declarator D which has the same name and scope as a previous
3272/// declaration 'Old'. Figure out how to resolve this situation,
3273/// merging decls or emitting diagnostics as appropriate.
3274///
3275/// In C++, New and Old must be declarations that are not
3276/// overloaded. Use IsOverload to determine whether New and Old are
3277/// overloaded, and to select the Old declaration that New should be
3278/// merged with.
3279///
3280/// Returns true if there was an error, false otherwise.
3281bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3282 Scope *S, bool MergeTypeWithOld) {
3283 // Verify the old decl was also a function.
3284 FunctionDecl *Old = OldD->getAsFunction();
3285 if (!Old) {
1
Assuming 'Old' is non-null
2
Taking false branch
3286 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3287 if (New->getFriendObjectKind()) {
3288 Diag(New->getLocation(), diag::err_using_decl_friend);
3289 Diag(Shadow->getTargetDecl()->getLocation(),
3290 diag::note_using_decl_target);
3291 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3292 << 0;
3293 return true;
3294 }
3295
3296 // Check whether the two declarations might declare the same function or
3297 // function template.
3298 if (FunctionTemplateDecl *NewTemplate =
3299 New->getDescribedFunctionTemplate()) {
3300 if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3301 NewTemplate))
3302 return true;
3303 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3304 ->getAsFunction();
3305 } else {
3306 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3307 return true;
3308 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3309 }
3310 } else {
3311 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3312 << New->getDeclName();
3313 notePreviousDefinition(OldD, New->getLocation());
3314 return true;
3315 }
3316 }
3317
3318 // If the old declaration was found in an inline namespace and the new
3319 // declaration was qualified, update the DeclContext to match.
3320 adjustDeclContextForDeclaratorDecl(New, Old);
3
Calling 'adjustDeclContextForDeclaratorDecl'
6
Returning from 'adjustDeclContextForDeclaratorDecl'
3321
3322 // If the old declaration is invalid, just give up here.
3323 if (Old->isInvalidDecl())
7
Assuming the condition is false
8
Taking false branch
3324 return true;
3325
3326 // Disallow redeclaration of some builtins.
3327 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
9
Assuming the condition is false
10
Taking false branch
3328 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3329 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3330 << Old << Old->getType();
3331 return true;
3332 }
3333
3334 diag::kind PrevDiag;
3335 SourceLocation OldLocation;
3336 std::tie(PrevDiag, OldLocation) =
3337 getNoteDiagForInvalidRedeclaration(Old, New);
3338
3339 // Don't complain about this if we're in GNU89 mode and the old function
3340 // is an extern inline function.
3341 // Don't complain about specializations. They are not supposed to have
3342 // storage classes.
3343 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
11
Assuming 'New' is not a 'CXXMethodDecl'
12
Assuming 'Old' is not a 'CXXMethodDecl'
3344 New->getStorageClass() == SC_Static &&
13
Assuming the condition is false
3345 Old->hasExternalFormalLinkage() &&
3346 !New->getTemplateSpecializationInfo() &&
3347 !canRedefineFunction(Old, getLangOpts())) {
3348 if (getLangOpts().MicrosoftExt) {
3349 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3350 Diag(OldLocation, PrevDiag);
3351 } else {
3352 Diag(New->getLocation(), diag::err_static_non_static) << New;
3353 Diag(OldLocation, PrevDiag);
3354 return true;
3355 }
3356 }
3357
3358 if (const auto *ILA
13.1
'ILA' is null
13.1
'ILA' is null
= New->getAttr<InternalLinkageAttr>())
14
Taking false branch
3359 if (!Old->hasAttr<InternalLinkageAttr>()) {
3360 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3361 << ILA;
3362 Diag(Old->getLocation(), diag::note_previous_declaration);
3363 New->dropAttr<InternalLinkageAttr>();
3364 }
3365
3366 if (CheckRedeclarationModuleOwnership(New, Old))
15
Calling 'Sema::CheckRedeclarationModuleOwnership'
27
Returning from 'Sema::CheckRedeclarationModuleOwnership'
28
Taking false branch
3367 return true;
3368
3369 if (!getLangOpts().CPlusPlus) {
29
Assuming field 'CPlusPlus' is not equal to 0
30
Taking false branch
3370 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3371 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3372 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3373 << New << OldOvl;
3374
3375 // Try our best to find a decl that actually has the overloadable
3376 // attribute for the note. In most cases (e.g. programs with only one
3377 // broken declaration/definition), this won't matter.
3378 //
3379 // FIXME: We could do this if we juggled some extra state in
3380 // OverloadableAttr, rather than just removing it.
3381 const Decl *DiagOld = Old;
3382 if (OldOvl) {
3383 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3384 const auto *A = D->getAttr<OverloadableAttr>();
3385 return A && !A->isImplicit();
3386 });
3387 // If we've implicitly added *all* of the overloadable attrs to this
3388 // chain, emitting a "previous redecl" note is pointless.
3389 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3390 }
3391
3392 if (DiagOld)
3393 Diag(DiagOld->getLocation(),
3394 diag::note_attribute_overloadable_prev_overload)
3395 << OldOvl;
3396
3397 if (OldOvl)
3398 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3399 else
3400 New->dropAttr<OverloadableAttr>();
3401 }
3402 }
3403
3404 // If a function is first declared with a calling convention, but is later
3405 // declared or defined without one, all following decls assume the calling
3406 // convention of the first.
3407 //
3408 // It's OK if a function is first declared without a calling convention,
3409 // but is later declared or defined with the default calling convention.
3410 //
3411 // To test if either decl has an explicit calling convention, we look for
3412 // AttributedType sugar nodes on the type as written. If they are missing or
3413 // were canonicalized away, we assume the calling convention was implicit.
3414 //
3415 // Note also that we DO NOT return at this point, because we still have
3416 // other tests to run.
3417 QualType OldQType = Context.getCanonicalType(Old->getType());
3418 QualType NewQType = Context.getCanonicalType(New->getType());
3419 const FunctionType *OldType = cast<FunctionType>(OldQType);
3420 const FunctionType *NewType = cast<FunctionType>(NewQType);
3421 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3422 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3423 bool RequiresAdjustment = false;
3424
3425 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
31
Assuming the condition is false
3426 FunctionDecl *First = Old->getFirstDecl();
3427 const FunctionType *FT =
3428 First->getType().getCanonicalType()->castAs<FunctionType>();
3429 FunctionType::ExtInfo FI = FT->getExtInfo();
3430 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3431 if (!NewCCExplicit) {
3432 // Inherit the CC from the previous declaration if it was specified
3433 // there but not here.
3434 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3435 RequiresAdjustment = true;
3436 } else if (Old->getBuiltinID()) {
3437 // Builtin attribute isn't propagated to the new one yet at this point,
3438 // so we check if the old one is a builtin.
3439
3440 // Calling Conventions on a Builtin aren't really useful and setting a
3441 // default calling convention and cdecl'ing some builtin redeclarations is
3442 // common, so warn and ignore the calling convention on the redeclaration.
3443 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3444 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3445 << (int)CallingConventionIgnoredReason::BuiltinFunction;
3446 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3447 RequiresAdjustment = true;
3448 } else {
3449 // Calling conventions aren't compatible, so complain.
3450 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3451 Diag(New->getLocation(), diag::err_cconv_change)
3452 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3453 << !FirstCCExplicit
3454 << (!FirstCCExplicit ? "" :
3455 FunctionType::getNameForCallConv(FI.getCC()));
3456
3457 // Put the note on the first decl, since it is the one that matters.
3458 Diag(First->getLocation(), diag::note_previous_declaration);
3459 return true;
3460 }
3461 }
3462
3463 // FIXME: diagnose the other way around?
3464 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
32
Assuming the condition is false
3465 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3466 RequiresAdjustment = true;
3467 }
3468
3469 // Merge regparm attribute.
3470 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
33
Taking false branch
3471 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3472 if (NewTypeInfo.getHasRegParm()) {
3473 Diag(New->getLocation(), diag::err_regparm_mismatch)
3474 << NewType->getRegParmType()
3475 << OldType->getRegParmType();
3476 Diag(OldLocation, diag::note_previous_declaration);
3477 return true;
3478 }
3479
3480 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3481 RequiresAdjustment = true;
3482 }
3483
3484 // Merge ns_returns_retained attribute.
3485 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
34
Assuming the condition is false
35
Taking false branch
3486 if (NewTypeInfo.getProducesResult()) {
3487 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3488 << "'ns_returns_retained'";
3489 Diag(OldLocation, diag::note_previous_declaration);
3490 return true;
3491 }
3492
3493 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3494 RequiresAdjustment = true;
3495 }
3496
3497 if (OldTypeInfo.getNoCallerSavedRegs() !=
36
Assuming the condition is false
37
Taking false branch
3498 NewTypeInfo.getNoCallerSavedRegs()) {
3499 if (NewTypeInfo.getNoCallerSavedRegs()) {
3500 AnyX86NoCallerSavedRegistersAttr *Attr =
3501 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3502 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3503 Diag(OldLocation, diag::note_previous_declaration);
3504 return true;
3505 }
3506
3507 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3508 RequiresAdjustment = true;
3509 }
3510
3511 if (RequiresAdjustment
37.1
'RequiresAdjustment' is false
37.1
'RequiresAdjustment' is false
) {
3512 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3513 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3514 New->setType(QualType(AdjustedType, 0));
3515 NewQType = Context.getCanonicalType(New->getType());
3516 }
3517
3518 // If this redeclaration makes the function inline, we may need to add it to
3519 // UndefinedButUsed.
3520 if (!Old->isInlined() && New->isInlined() &&
38
Assuming the condition is false
3521 !New->hasAttr<GNUInlineAttr>() &&
3522 !getLangOpts().GNUInline &&
3523 Old->isUsed(false) &&
3524 !Old->isDefined() && !New->isThisDeclarationADefinition())
3525 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3526 SourceLocation()));
3527
3528 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3529 // about it.
3530 if (New->hasAttr<GNUInlineAttr>() &&
3531 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3532 UndefinedButUsed.erase(Old->getCanonicalDecl());
3533 }
3534
3535 // If pass_object_size params don't match up perfectly, this isn't a valid
3536 // redeclaration.
3537 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
39
Assuming the condition is false
3538 !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3539 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3540 << New->getDeclName();
3541 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3542 return true;
3543 }
3544
3545 if (getLangOpts().CPlusPlus
39.1
Field 'CPlusPlus' is not equal to 0
39.1
Field 'CPlusPlus' is not equal to 0
) {
40
Taking true branch
3546 // C++1z [over.load]p2
3547 // Certain function declarations cannot be overloaded:
3548 // -- Function declarations that differ only in the return type,
3549 // the exception specification, or both cannot be overloaded.
3550
3551 // Check the exception specifications match. This may recompute the type of
3552 // both Old and New if it resolved exception specifications, so grab the
3553 // types again after this. Because this updates the type, we do this before
3554 // any of the other checks below, which may update the "de facto" NewQType
3555 // but do not necessarily update the type of New.
3556 if (CheckEquivalentExceptionSpec(Old, New))
41
Assuming the condition is false
42
Taking false branch
3557 return true;
3558 OldQType = Context.getCanonicalType(Old->getType());
3559 NewQType = Context.getCanonicalType(New->getType());
3560
3561 // Go back to the type source info to compare the declared return types,
3562 // per C++1y [dcl.type.auto]p13:
3563 // Redeclarations or specializations of a function or function template
3564 // with a declared return type that uses a placeholder type shall also
3565 // use that placeholder, not a deduced type.
3566 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3567 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3568 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
43
Assuming the condition is false
3569 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3570 OldDeclaredReturnType)) {
3571 QualType ResQT;
3572 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3573 OldDeclaredReturnType->isObjCObjectPointerType())
3574 // FIXME: This does the wrong thing for a deduced return type.
3575 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3576 if (ResQT.isNull()) {
3577 if (New->isCXXClassMember() && New->isOutOfLine())
3578 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3579 << New << New->getReturnTypeSourceRange();
3580 else
3581 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3582 << New->getReturnTypeSourceRange();
3583 Diag(OldLocation, PrevDiag) << Old << Old->getType()
3584 << Old->getReturnTypeSourceRange();
3585 return true;
3586 }
3587 else
3588 NewQType = ResQT;
3589 }
3590
3591 QualType OldReturnType = OldType->getReturnType();
3592 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3593 if (OldReturnType != NewReturnType) {
44
Taking false branch
3594 // If this function has a deduced return type and has already been
3595 // defined, copy the deduced value from the old declaration.
3596 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3597 if (OldAT && OldAT->isDeduced()) {
3598 New->setType(
3599 SubstAutoType(New->getType(),
3600 OldAT->isDependentType() ? Context.DependentTy
3601 : OldAT->getDeducedType()));
3602 NewQType = Context.getCanonicalType(
3603 SubstAutoType(NewQType,
3604 OldAT->isDependentType() ? Context.DependentTy
3605 : OldAT->getDeducedType()));
3606 }
3607 }
3608
3609 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
45
Assuming 'Old' is not a 'CXXMethodDecl'
3610 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
46
Assuming 'New' is not a 'CXXMethodDecl'
3611 if (OldMethod
46.1
'OldMethod' is null
46.1
'OldMethod' is null
&& NewMethod) {
3612 // Preserve triviality.
3613 NewMethod->setTrivial(OldMethod->isTrivial());
3614
3615 // MSVC allows explicit template specialization at class scope:
3616 // 2 CXXMethodDecls referring to the same function will be injected.
3617 // We don't want a redeclaration error.
3618 bool IsClassScopeExplicitSpecialization =
3619 OldMethod->isFunctionTemplateSpecialization() &&
3620 NewMethod->isFunctionTemplateSpecialization();
3621 bool isFriend = NewMethod->getFriendObjectKind();
3622
3623 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3624 !IsClassScopeExplicitSpecialization) {
3625 // -- Member function declarations with the same name and the
3626 // same parameter types cannot be overloaded if any of them
3627 // is a static member function declaration.
3628 if (OldMethod->isStatic() != NewMethod->isStatic()) {
3629 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3630 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3631 return true;
3632 }
3633
3634 // C++ [class.mem]p1:
3635 // [...] A member shall not be declared twice in the
3636 // member-specification, except that a nested class or member
3637 // class template can be declared and then later defined.
3638 if (!inTemplateInstantiation()) {
3639 unsigned NewDiag;
3640 if (isa<CXXConstructorDecl>(OldMethod))
3641 NewDiag = diag::err_constructor_redeclared;
3642 else if (isa<CXXDestructorDecl>(NewMethod))
3643 NewDiag = diag::err_destructor_redeclared;
3644 else if (isa<CXXConversionDecl>(NewMethod))
3645 NewDiag = diag::err_conv_function_redeclared;
3646 else
3647 NewDiag = diag::err_member_redeclared;
3648
3649 Diag(New->getLocation(), NewDiag);
3650 } else {
3651 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3652 << New << New->getType();
3653 }
3654 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3655 return true;
3656
3657 // Complain if this is an explicit declaration of a special
3658 // member that was initially declared implicitly.
3659 //
3660 // As an exception, it's okay to befriend such methods in order
3661 // to permit the implicit constructor/destructor/operator calls.
3662 } else if (OldMethod->isImplicit()) {
3663 if (isFriend) {
3664 NewMethod->setImplicit();
3665 } else {
3666 Diag(NewMethod->getLocation(),
3667 diag::err_definition_of_implicitly_declared_member)
3668 << New << getSpecialMember(OldMethod);
3669 return true;
3670 }
3671 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3672 Diag(NewMethod->getLocation(),
3673 diag::err_definition_of_explicitly_defaulted_member)
3674 << getSpecialMember(OldMethod);
3675 return true;
3676 }
3677 }
3678
3679 // C++11 [dcl.attr.noreturn]p1:
3680 // The first declaration of a function shall specify the noreturn
3681 // attribute if any declaration of that function specifies the noreturn
3682 // attribute.
3683 if (const auto *NRA
46.2
'NRA' is null
46.2
'NRA' is null
= New->getAttr<CXX11NoReturnAttr>())
47
Taking false branch
3684 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
3685 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
3686 << NRA;
3687 Diag(Old->getLocation(), diag::note_previous_declaration);
3688 }
3689
3690 // C++11 [dcl.attr.depend]p2:
3691 // The first declaration of a function shall specify the
3692 // carries_dependency attribute for its declarator-id if any declaration
3693 // of the function specifies the carries_dependency attribute.
3694 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3695 if (CDA
47.1
'CDA' is null
47.1
'CDA' is null
&& !Old->hasAttr<CarriesDependencyAttr>()) {
3696 Diag(CDA->getLocation(),
3697 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3698 Diag(Old->getFirstDecl()->getLocation(),
3699 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3700 }
3701
3702 // (C++98 8.3.5p3):
3703 // All declarations for a function shall agree exactly in both the
3704 // return type and the parameter-type-list.
3705 // We also want to respect all the extended bits except noreturn.
3706
3707 // noreturn should now match unless the old type info didn't have it.
3708 QualType OldQTypeForComparison = OldQType;
3709 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
48
Assuming the condition is false
49
Taking false branch
3710 auto *OldType = OldQType->castAs<FunctionProtoType>();
3711 const FunctionType *OldTypeForComparison
3712 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3713 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3714 assert(OldQTypeForComparison.isCanonical())(static_cast <bool> (OldQTypeForComparison.isCanonical(
)) ? void (0) : __assert_fail ("OldQTypeForComparison.isCanonical()"
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 3714, __extension__ __PRETTY_FUNCTION__))
;
3715 }
3716
3717 if (haveIncompatibleLanguageLinkages(Old, New)) {
50
Calling 'haveIncompatibleLanguageLinkages<clang::FunctionDecl>'
59
Returning from 'haveIncompatibleLanguageLinkages<clang::FunctionDecl>'
60
Taking false branch
3718 // As a special case, retain the language linkage from previous
3719 // declarations of a friend function as an extension.
3720 //
3721 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3722 // and is useful because there's otherwise no way to specify language
3723 // linkage within class scope.
3724 //
3725 // Check cautiously as the friend object kind isn't yet complete.
3726 if (New->getFriendObjectKind() != Decl::FOK_None) {
3727 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3728 Diag(OldLocation, PrevDiag);
3729 } else {
3730 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3731 Diag(OldLocation, PrevDiag);
3732 return true;
3733 }
3734 }
3735
3736 // If the function types are compatible, merge the declarations. Ignore the
3737 // exception specifier because it was already checked above in
3738 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3739 // about incompatible types under -fms-compatibility.
3740 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
61
Assuming the condition is false
62
Taking false branch
3741 NewQType))
3742 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3743
3744 // If the types are imprecise (due to dependent constructs in friends or
3745 // local extern declarations), it's OK if they differ. We'll check again
3746 // during instantiation.
3747 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
63
Calling 'Sema::canFullyTypeCheckRedeclaration'
67
Returning from 'Sema::canFullyTypeCheckRedeclaration'
3748 return false;
3749
3750 // Fall through for conflicting redeclarations and redefinitions.
3751 }
3752
3753 // C: Function types need to be compatible, not identical. This handles
3754 // duplicate function decls like "void f(int); void f(enum X);" properly.
3755 if (!getLangOpts().CPlusPlus &&
68
Assuming field 'CPlusPlus' is 0
70
Taking true branch
3756 Context.typesAreCompatible(OldQType, NewQType)) {
69
Assuming the condition is true
3757 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
71
Assuming the object is not a 'FunctionType'
3758 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
72
Assuming the object is not a 'FunctionType'
73
'NewFuncType' initialized to a null pointer value
3759 const FunctionProtoType *OldProto = nullptr;
3760 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
74
Assuming 'MergeTypeWithOld' is true
75
Assuming 'NewFuncType' is a 'FunctionNoProtoType'
3761 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
76
Assuming 'OldProto' is non-null
3762 // The old declaration provided a function prototype, but the
3763 // new declaration does not. Merge in the prototype.
3764 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 3764, __extension__ __PRETTY_FUNCTION__))
;
77
Taking true branch
78
'?' condition is true
3765 SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3766 NewQType =
3767 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
79
Called C++ object pointer is null
3768 OldProto->getExtProtoInfo());
3769 New->setType(NewQType);
3770 New->setHasInheritedPrototype();
3771
3772 // Synthesize parameters with the same types.
3773 SmallVector<ParmVarDecl*, 16> Params;
3774 for (const auto &ParamType : OldProto->param_types()) {
3775 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3776 SourceLocation(), nullptr,
3777 ParamType, /*TInfo=*/nullptr,
3778 SC_None, nullptr);
3779 Param->setScopeInfo(0, Params.size());
3780 Param->setImplicit();
3781 Params.push_back(Param);
3782 }
3783
3784 New->setParams(Params);
3785 }
3786
3787 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3788 }
3789
3790 // Check if the function types are compatible when pointer size address
3791 // spaces are ignored.
3792 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
3793 return false;
3794
3795 // GNU C permits a K&R definition to follow a prototype declaration
3796 // if the declared types of the parameters in the K&R definition
3797 // match the types in the prototype declaration, even when the
3798 // promoted types of the parameters from the K&R definition differ
3799 // from the types in the prototype. GCC then keeps the types from
3800 // the prototype.
3801 //
3802 // If a variadic prototype is followed by a non-variadic K&R definition,
3803 // the K&R definition becomes variadic. This is sort of an edge case, but
3804 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3805 // C99 6.9.1p8.
3806 if (!getLangOpts().CPlusPlus &&
3807 Old->hasPrototype() && !New->hasPrototype() &&
3808 New->getType()->getAs<FunctionProtoType>() &&
3809 Old->getNumParams() == New->getNumParams()) {
3810 SmallVector<QualType, 16> ArgTypes;
3811 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3812 const FunctionProtoType *OldProto
3813 = Old->getType()->getAs<FunctionProtoType>();
3814 const FunctionProtoType *NewProto
3815 = New->getType()->getAs<FunctionProtoType>();
3816
3817 // Determine whether this is the GNU C extension.
3818 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3819 NewProto->getReturnType());
3820 bool LooseCompatible = !MergedReturn.isNull();
3821 for (unsigned Idx = 0, End = Old->getNumParams();
3822 LooseCompatible && Idx != End; ++Idx) {
3823 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3824 ParmVarDecl *NewParm = New->getParamDecl(Idx);
3825 if (Context.typesAreCompatible(OldParm->getType(),
3826 NewProto->getParamType(Idx))) {
3827 ArgTypes.push_back(NewParm->getType());
3828 } else if (Context.typesAreCompatible(OldParm->getType(),
3829 NewParm->getType(),
3830 /*CompareUnqualified=*/true)) {
3831 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3832 NewProto->getParamType(Idx) };
3833 Warnings.push_back(Warn);
3834 ArgTypes.push_back(NewParm->getType());
3835 } else
3836 LooseCompatible = false;
3837 }
3838
3839 if (LooseCompatible) {
3840 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3841 Diag(Warnings[Warn].NewParm->getLocation(),
3842 diag::ext_param_promoted_not_compatible_with_prototype)
3843 << Warnings[Warn].PromotedType
3844 << Warnings[Warn].OldParm->getType();
3845 if (Warnings[Warn].OldParm->getLocation().isValid())
3846 Diag(Warnings[Warn].OldParm->getLocation(),
3847 diag::note_previous_declaration);
3848 }
3849
3850 if (MergeTypeWithOld)
3851 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3852 OldProto->getExtProtoInfo()));
3853 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3854 }
3855
3856 // Fall through to diagnose conflicting types.
3857 }
3858
3859 // A function that has already been declared has been redeclared or
3860 // defined with a different type; show an appropriate diagnostic.
3861
3862 // If the previous declaration was an implicitly-generated builtin
3863 // declaration, then at the very least we should use a specialized note.
3864 unsigned BuiltinID;
3865 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3866 // If it's actually a library-defined builtin function like 'malloc'
3867 // or 'printf', just warn about the incompatible redeclaration.
3868 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3869 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3870 Diag(OldLocation, diag::note_previous_builtin_declaration)
3871 << Old << Old->getType();
3872 return false;
3873 }
3874
3875 PrevDiag = diag::note_previous_builtin_declaration;
3876 }
3877
3878 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3879 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3880 return true;
3881}
3882
3883/// Completes the merge of two function declarations that are
3884/// known to be compatible.
3885///
3886/// This routine handles the merging of attributes and other
3887/// properties of function declarations from the old declaration to
3888/// the new declaration, once we know that New is in fact a
3889/// redeclaration of Old.
3890///
3891/// \returns false
3892bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3893 Scope *S, bool MergeTypeWithOld) {
3894 // Merge the attributes
3895 mergeDeclAttributes(New, Old);
3896
3897 // Merge "pure" flag.
3898 if (Old->isPure())
3899 New->setPure();
3900
3901 // Merge "used" flag.
3902 if (Old->getMostRecentDecl()->isUsed(false))
3903 New->setIsUsed();
3904
3905 // Merge attributes from the parameters. These can mismatch with K&R
3906 // declarations.
3907 if (New->getNumParams() == Old->getNumParams())
3908 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3909 ParmVarDecl *NewParam = New->getParamDecl(i);
3910 ParmVarDecl *OldParam = Old->getParamDecl(i);
3911 mergeParamDeclAttributes(NewParam, OldParam, *this);
3912 mergeParamDeclTypes(NewParam, OldParam, *this);
3913 }
3914
3915 if (getLangOpts().CPlusPlus)
3916 return MergeCXXFunctionDecl(New, Old, S);
3917
3918 // Merge the function types so the we get the composite types for the return
3919 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3920 // was visible.
3921 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3922 if (!Merged.isNull() && MergeTypeWithOld)
3923 New->setType(Merged);
3924
3925 return false;
3926}
3927
3928void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3929 ObjCMethodDecl *oldMethod) {
3930 // Merge the attributes, including deprecated/unavailable
3931 AvailabilityMergeKind MergeKind =
3932 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3933 ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
3934 : AMK_ProtocolImplementation)
3935 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3936 : AMK_Override;
3937
3938 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3939
3940 // Merge attributes from the parameters.
3941 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3942 oe = oldMethod->param_end();
3943 for (ObjCMethodDecl::param_iterator
3944 ni = newMethod->param_begin(), ne = newMethod->param_end();
3945 ni != ne && oi != oe; ++ni, ++oi)
3946 mergeParamDeclAttributes(*ni, *oi, *this);
3947
3948 CheckObjCMethodOverride(newMethod, oldMethod);
3949}
3950
3951static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3952 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())"
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 3952, __extension__ __PRETTY_FUNCTION__))
;
3953
3954 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3955 ? diag::err_redefinition_different_type
3956 : diag::err_redeclaration_different_type)
3957 << New->getDeclName() << New->getType() << Old->getType();
3958
3959 diag::kind PrevDiag;
3960 SourceLocation OldLocation;
3961 std::tie(PrevDiag, OldLocation)
3962 = getNoteDiagForInvalidRedeclaration(Old, New);
3963 S.Diag(OldLocation, PrevDiag);
3964 New->setInvalidDecl();
3965}
3966
3967/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3968/// scope as a previous declaration 'Old'. Figure out how to merge their types,
3969/// emitting diagnostics as appropriate.
3970///
3971/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3972/// to here in AddInitializerToDecl. We can't check them before the initializer
3973/// is attached.
3974void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3975 bool MergeTypeWithOld) {
3976 if (New->isInvalidDecl() || Old->isInvalidDecl())
3977 return;
3978
3979 QualType MergedT;
3980 if (getLangOpts().CPlusPlus) {
3981 if (New->getType()->isUndeducedType()) {
3982 // We don't know what the new type is until the initializer is attached.
3983 return;
3984 } else if (Context.hasSameType(New->getType(), Old->getType())) {
3985 // These could still be something that needs exception specs checked.
3986 return MergeVarDeclExceptionSpecs(New, Old);
3987 }
3988 // C++ [basic.link]p10:
3989 // [...] the types specified by all declarations referring to a given
3990 // object or function shall be identical, except that declarations for an
3991 // array object can specify array types that differ by the presence or
3992 // absence of a major array bound (8.3.4).
3993 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3994 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3995 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3996
3997 // We are merging a variable declaration New into Old. If it has an array
3998 // bound, and that bound differs from Old's bound, we should diagnose the
3999 // mismatch.
4000 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4001 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4002 PrevVD = PrevVD->getPreviousDecl()) {
4003 QualType PrevVDTy = PrevVD->getType();
4004 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4005 continue;
4006
4007 if (!Context.hasSameType(New->getType(), PrevVDTy))
4008 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4009 }
4010 }
4011
4012 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4013 if (Context.hasSameType(OldArray->getElementType(),
4014 NewArray->getElementType()))
4015 MergedT = New->getType();
4016 }
4017 // FIXME: Check visibility. New is hidden but has a complete type. If New
4018 // has no array bound, it should not inherit one from Old, if Old is not
4019 // visible.
4020 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4021 if (Context.hasSameType(OldArray->getElementType(),
4022 NewArray->getElementType()))
4023 MergedT = Old->getType();
4024 }
4025 }
4026 else if (New->getType()->isObjCObjectPointerType() &&
4027 Old->getType()->isObjCObjectPointerType()) {
4028 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4029 Old->getType());
4030 }
4031 } else {
4032 // C 6.2.7p2:
4033 // All declarations that refer to the same object or function shall have
4034 // compatible type.
4035 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4036 }
4037 if (MergedT.isNull()) {
4038 // It's OK if we couldn't merge types if either type is dependent, for a
4039 // block-scope variable. In other cases (static data members of class
4040 // templates, variable templates, ...), we require the types to be
4041 // equivalent.
4042 // FIXME: The C++ standard doesn't say anything about this.
4043 if ((New->getType()->isDependentType() ||
4044 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4045 // If the old type was dependent, we can't merge with it, so the new type
4046 // becomes dependent for now. We'll reproduce the original type when we
4047 // instantiate the TypeSourceInfo for the variable.
4048 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4049 New->setType(Context.DependentTy);
4050 return;
4051 }
4052 return diagnoseVarDeclTypeMismatch(*this, New, Old);
4053 }
4054
4055 // Don't actually update the type on the new declaration if the old
4056 // declaration was an extern declaration in a different scope.
4057 if (MergeTypeWithOld)
4058 New->setType(MergedT);
4059}
4060
4061static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4062 LookupResult &Previous) {
4063 // C11 6.2.7p4:
4064 // For an identifier with internal or external linkage declared
4065 // in a scope in which a prior declaration of that identifier is
4066 // visible, if the prior declaration specifies internal or
4067 // external linkage, the type of the identifier at the later
4068 // declaration becomes the composite type.
4069 //
4070 // If the variable isn't visible, we do not merge with its type.
4071 if (Previous.isShadowed())
4072 return false;
4073
4074 if (S.getLangOpts().CPlusPlus) {
4075 // C++11 [dcl.array]p3:
4076 // If there is a preceding declaration of the entity in the same
4077 // scope in which the bound was specified, an omitted array bound
4078 // is taken to be the same as in that earlier declaration.
4079 return NewVD->isPreviousDeclInSameBlockScope() ||
4080 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4081 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4082 } else {
4083 // If the old declaration was function-local, don't merge with its
4084 // type unless we're in the same function.
4085 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4086 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4087 }
4088}
4089
4090/// MergeVarDecl - We just parsed a variable 'New' which has the same name
4091/// and scope as a previous declaration 'Old'. Figure out how to resolve this
4092/// situation, merging decls or emitting diagnostics as appropriate.
4093///
4094/// Tentative definition rules (C99 6.9.2p2) are checked by
4095/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4096/// definitions here, since the initializer hasn't been attached.
4097///
4098void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4099 // If the new decl is already invalid, don't do any other checking.
4100 if (New->isInvalidDecl())
4101 return;
4102
4103 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4104 return;
4105
4106 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4107
4108 // Verify the old decl was also a variable or variable template.
4109 VarDecl *Old = nullptr;
4110 VarTemplateDecl *OldTemplate = nullptr;
4111 if (Previous.isSingleResult()) {
4112 if (NewTemplate) {
4113 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4114 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4115
4116 if (auto *Shadow =
4117 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4118 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4119 return New->setInvalidDecl();
4120 } else {
4121 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4122
4123 if (auto *Shadow =
4124 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4125 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4126 return New->setInvalidDecl();
4127 }
4128 }
4129 if (!Old) {
4130 Diag(New->getLocation(), diag::err_redefinition_different_kind)
4131 << New->getDeclName();
4132 notePreviousDefinition(Previous.getRepresentativeDecl(),
4133 New->getLocation());
4134 return New->setInvalidDecl();
4135 }
4136
4137 // If the old declaration was found in an inline namespace and the new
4138 // declaration was qualified, update the DeclContext to match.
4139 adjustDeclContextForDeclaratorDecl(New, Old);
4140
4141 // Ensure the template parameters are compatible.
4142 if (NewTemplate &&
4143 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4144 OldTemplate->getTemplateParameters(),
4145 /*Complain=*/true, TPL_TemplateMatch))
4146 return New->setInvalidDecl();
4147
4148 // C++ [class.mem]p1:
4149 // A member shall not be declared twice in the member-specification [...]
4150 //
4151 // Here, we need only consider static data members.
4152 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4153 Diag(New->getLocation(), diag::err_duplicate_member)
4154 << New->getIdentifier();
4155 Diag(Old->getLocation(), diag::note_previous_declaration);
4156 New->setInvalidDecl();
4157 }
4158
4159 mergeDeclAttributes(New, Old);
4160 // Warn if an already-declared variable is made a weak_import in a subsequent
4161 // declaration
4162 if (New->hasAttr<WeakImportAttr>() &&
4163 Old->getStorageClass() == SC_None &&
4164 !Old->hasAttr<WeakImportAttr>()) {
4165 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4166 Diag(Old->getLocation(), diag::note_previous_declaration);
4167 // Remove weak_import attribute on new declaration.
4168 New->dropAttr<WeakImportAttr>();
4169 }
4170
4171 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4172 if (!Old->hasAttr<InternalLinkageAttr>()) {
4173 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4174 << ILA;
4175 Diag(Old->getLocation(), diag::note_previous_declaration);
4176 New->dropAttr<InternalLinkageAttr>();
4177 }
4178
4179 // Merge the types.
4180 VarDecl *MostRecent = Old->getMostRecentDecl();
4181 if (MostRecent != Old) {
4182 MergeVarDeclTypes(New, MostRecent,
4183 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4184 if (New->isInvalidDecl())
4185 return;
4186 }
4187
4188 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4189 if (New->isInvalidDecl())
4190 return;
4191
4192 diag::kind PrevDiag;
4193 SourceLocation OldLocation;
4194 std::tie(PrevDiag, OldLocation) =
4195 getNoteDiagForInvalidRedeclaration(Old, New);
4196
4197 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4198 if (New->getStorageClass() == SC_Static &&
4199 !New->isStaticDataMember() &&
4200 Old->hasExternalFormalLinkage()) {
4201 if (getLangOpts().MicrosoftExt) {
4202 Diag(New->getLocation(), diag::ext_static_non_static)
4203 << New->getDeclName();
4204 Diag(OldLocation, PrevDiag);
4205 } else {
4206 Diag(New->getLocation(), diag::err_static_non_static)
4207 << New->getDeclName();
4208 Diag(OldLocation, PrevDiag);
4209 return New->setInvalidDecl();
4210 }
4211 }
4212 // C99 6.2.2p4:
4213 // For an identifier declared with the storage-class specifier
4214 // extern in a scope in which a prior declaration of that
4215 // identifier is visible,23) if the prior declaration specifies
4216 // internal or external linkage, the linkage of the identifier at
4217 // the later declaration is the same as the linkage specified at
4218 // the prior declaration. If no prior declaration is visible, or
4219 // if the prior declaration specifies no linkage, then the
4220 // identifier has external linkage.
4221 if (New->hasExternalStorage() && Old->hasLinkage())
4222 /* Okay */;
4223 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4224 !New->isStaticDataMember() &&
4225 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4226 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4227 Diag(OldLocation, PrevDiag);
4228 return New->setInvalidDecl();
4229 }
4230
4231 // Check if extern is followed by non-extern and vice-versa.
4232 if (New->hasExternalStorage() &&
4233 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4234 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4235 Diag(OldLocation, PrevDiag);
4236 return New->setInvalidDecl();
4237 }
4238 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4239 !New->hasExternalStorage()) {
4240 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4241 Diag(OldLocation, PrevDiag);
4242 return New->setInvalidDecl();
4243 }
4244
4245 if (CheckRedeclarationModuleOwnership(New, Old))
4246 return;
4247
4248 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4249
4250 // FIXME: The test for external storage here seems wrong? We still
4251 // need to check for mismatches.
4252 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4253 // Don't complain about out-of-line definitions of static members.
4254 !(Old->getLexicalDeclContext()->isRecord() &&
4255 !New->getLexicalDeclContext()->isRecord())) {
4256 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4257 Diag(OldLocation, PrevDiag);
4258 return New->setInvalidDecl();
4259 }
4260
4261 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4262 if (VarDecl *Def = Old->getDefinition()) {
4263 // C++1z [dcl.fcn.spec]p4:
4264 // If the definition of a variable appears in a translation unit before
4265 // its first declaration as inline, the program is ill-formed.
4266 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4267 Diag(Def->getLocation(), diag::note_previous_definition);
4268 }
4269 }
4270
4271 // If this redeclaration makes the variable inline, we may need to add it to
4272 // UndefinedButUsed.
4273 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4274 !Old->getDefinition() && !New->isThisDeclarationADefinition())
4275 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4276 SourceLocation()));
4277
4278 if (New->getTLSKind() != Old->getTLSKind()) {
4279 if (!Old->getTLSKind()) {
4280 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4281 Diag(OldLocation, PrevDiag);
4282 } else if (!New->getTLSKind()) {
4283 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4284 Diag(OldLocation, PrevDiag);
4285 } else {
4286 // Do not allow redeclaration to change the variable between requiring
4287 // static and dynamic initialization.
4288 // FIXME: GCC allows this, but uses the TLS keyword on the first
4289 // declaration to determine the kind. Do we need to be compatible here?
4290 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4291 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4292 Diag(OldLocation, PrevDiag);
4293 }
4294 }
4295
4296 // C++ doesn't have tentative definitions, so go right ahead and check here.
4297 if (getLangOpts().CPlusPlus &&
4298 New->isThisDeclarationADefinition() == VarDecl::Definition) {
4299 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4300 Old->getCanonicalDecl()->isConstexpr()) {
4301 // This definition won't be a definition any more once it's been merged.
4302 Diag(New->getLocation(),
4303 diag::warn_deprecated_redundant_constexpr_static_def);
4304 } else if (VarDecl *Def = Old->getDefinition()) {
4305 if (checkVarDeclRedefinition(Def, New))
4306 return;
4307 }
4308 }
4309
4310 if (haveIncompatibleLanguageLinkages(Old, New)) {
4311 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4312 Diag(OldLocation, PrevDiag);
4313 New->setInvalidDecl();
4314 return;
4315 }
4316
4317 // Merge "used" flag.
4318 if (Old->getMostRecentDecl()->isUsed(false))
4319 New->setIsUsed();
4320
4321 // Keep a chain of previous declarations.
4322 New->setPreviousDecl(Old);
4323 if (NewTemplate)
4324 NewTemplate->setPreviousDecl(OldTemplate);
4325
4326 // Inherit access appropriately.
4327 New->setAccess(Old->getAccess());
4328 if (NewTemplate)
4329 NewTemplate->setAccess(New->getAccess());
4330
4331 if (Old->isInline())
4332 New->setImplicitlyInline();
4333}
4334
4335void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4336 SourceManager &SrcMgr = getSourceManager();
4337 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4338 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4339 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4340 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4341 auto &HSI = PP.getHeaderSearchInfo();
4342 StringRef HdrFilename =
4343 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4344
4345 auto noteFromModuleOrInclude = [&](Module *Mod,
4346 SourceLocation IncLoc) -> bool {
4347 // Redefinition errors with modules are common with non modular mapped
4348 // headers, example: a non-modular header H in module A that also gets
4349 // included directly in a TU. Pointing twice to the same header/definition
4350 // is confusing, try to get better diagnostics when modules is on.
4351 if (IncLoc.isValid()) {
4352 if (Mod) {
4353 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4354 << HdrFilename.str() << Mod->getFullModuleName();
4355 if (!Mod->DefinitionLoc.isInvalid())
4356 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4357 << Mod->getFullModuleName();
4358 } else {
4359 Diag(IncLoc, diag::note_redefinition_include_same_file)
4360 << HdrFilename.str();
4361 }
4362 return true;
4363 }
4364
4365 return false;
4366 };
4367
4368 // Is it the same file and same offset? Provide more information on why
4369 // this leads to a redefinition error.
4370 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4371 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4372 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4373 bool EmittedDiag =
4374 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4375 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4376
4377 // If the header has no guards, emit a note suggesting one.
4378 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4379 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4380
4381 if (EmittedDiag)
4382 return;
4383 }
4384
4385 // Redefinition coming from different files or couldn't do better above.
4386 if (Old->getLocation().isValid())
4387 Diag(Old->getLocation(), diag::note_previous_definition);
4388}
4389
4390/// We've just determined that \p Old and \p New both appear to be definitions
4391/// of the same variable. Either diagnose or fix the problem.
4392bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4393 if (!hasVisibleDefinition(Old) &&
4394 (New->getFormalLinkage() == InternalLinkage ||
4395 New->isInline() ||
4396 New->getDescribedVarTemplate() ||
4397 New->getNumTemplateParameterLists() ||
4398 New->getDeclContext()->isDependentContext())) {
4399 // The previous definition is hidden, and multiple definitions are
4400 // permitted (in separate TUs). Demote this to a declaration.
4401 New->demoteThisDefinitionToDeclaration();
4402
4403 // Make the canonical definition visible.
4404 if (auto *OldTD = Old->getDescribedVarTemplate())
4405 makeMergedDefinitionVisible(OldTD);
4406 makeMergedDefinitionVisible(Old);
4407 return false;
4408 } else {
4409 Diag(New->getLocation(), diag::err_redefinition) << New;
4410 notePreviousDefinition(Old, New->getLocation());
4411 New->setInvalidDecl();
4412 return true;
4413 }
4414}
4415
4416/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4417/// no declarator (e.g. "struct foo;") is parsed.
4418Decl *
4419Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4420 RecordDecl *&AnonRecord) {
4421 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4422 AnonRecord);
4423}
4424
4425// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4426// disambiguate entities defined in different scopes.
4427// While the VS2015 ABI fixes potential miscompiles, it is also breaks
4428// compatibility.
4429// We will pick our mangling number depending on which version of MSVC is being
4430// targeted.
4431static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4432 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4433 ? S->getMSCurManglingNumber()
4434 : S->getMSLastManglingNumber();
4435}
4436
4437void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4438 if (!Context.getLangOpts().CPlusPlus)
4439 return;
4440
4441 if (isa<CXXRecordDecl>(Tag->getParent())) {
4442 // If this tag is the direct child of a class, number it if
4443 // it is anonymous.
4444 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4445 return;
4446 MangleNumberingContext &MCtx =
4447 Context.getManglingNumberContext(Tag->getParent());
4448 Context.setManglingNumber(
4449 Tag, MCtx.getManglingNumber(
4450 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4451 return;
4452 }
4453
4454 // If this tag isn't a direct child of a class, number it if it is local.
4455 MangleNumberingContext *MCtx;
4456 Decl *ManglingContextDecl;
4457 std::tie(MCtx, ManglingContextDecl) =
4458 getCurrentMangleNumberContext(Tag->getDeclContext());
4459 if (MCtx) {
4460 Context.setManglingNumber(
4461 Tag, MCtx->getManglingNumber(
4462 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4463 }
4464}
4465
4466namespace {
4467struct NonCLikeKind {
4468 enum {
4469 None,
4470 BaseClass,
4471 DefaultMemberInit,
4472 Lambda,
4473 Friend,
4474 OtherMember,
4475 Invalid,
4476 } Kind = None;
4477 SourceRange Range;
4478
4479 explicit operator bool() { return Kind != None; }
4480};
4481}
4482
4483/// Determine whether a class is C-like, according to the rules of C++
4484/// [dcl.typedef] for anonymous classes with typedef names for linkage.
4485static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4486 if (RD->isInvalidDecl())
4487 return {NonCLikeKind::Invalid, {}};
4488
4489 // C++ [dcl.typedef]p9: [P1766R1]
4490 // An unnamed class with a typedef name for linkage purposes shall not
4491 //
4492 // -- have any base classes
4493 if (RD->getNumBases())
4494 return {NonCLikeKind::BaseClass,
4495 SourceRange(RD->bases_begin()->getBeginLoc(),
4496 RD->bases_end()[-1].getEndLoc())};
4497 bool Invalid = false;
4498 for (Decl *D : RD->decls()) {
4499 // Don't complain about things we already diagnosed.
4500 if (D->isInvalidDecl()) {
4501 Invalid = true;
4502 continue;
4503 }
4504
4505 // -- have any [...] default member initializers
4506 if (auto *FD = dyn_cast<FieldDecl>(D)) {
4507 if (FD->hasInClassInitializer()) {
4508 auto *Init = FD->getInClassInitializer();
4509 return {NonCLikeKind::DefaultMemberInit,
4510 Init ? Init->getSourceRange() : D->getSourceRange()};
4511 }
4512 continue;
4513 }
4514
4515 // FIXME: We don't allow friend declarations. This violates the wording of
4516 // P1766, but not the intent.
4517 if (isa<FriendDecl>(D))
4518 return {NonCLikeKind::Friend, D->getSourceRange()};
4519
4520 // -- declare any members other than non-static data members, member
4521 // enumerations, or member classes,
4522 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4523 isa<EnumDecl>(D))
4524 continue;
4525 auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4526 if (!MemberRD) {
4527 if (D->isImplicit())
4528 continue;
4529 return {NonCLikeKind::OtherMember, D->getSourceRange()};
4530 }
4531
4532 // -- contain a lambda-expression,
4533 if (MemberRD->isLambda())
4534 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4535
4536 // and all member classes shall also satisfy these requirements
4537 // (recursively).
4538 if (MemberRD->isThisDeclarationADefinition()) {
4539 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4540 return Kind;
4541 }
4542 }
4543
4544 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4545}
4546
4547void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4548 TypedefNameDecl *NewTD) {
4549 if (TagFromDeclSpec->isInvalidDecl())
4550 return;
4551
4552 // Do nothing if the tag already has a name for linkage purposes.
4553 if (TagFromDeclSpec->hasNameForLinkage())
4554 return;
4555
4556 // A well-formed anonymous tag must always be a TUK_Definition.
4557 assert(TagFromDeclSpec->isThisDeclarationADefinition())(static_cast <bool> (TagFromDeclSpec->isThisDeclarationADefinition
()) ? void (0) : __assert_fail ("TagFromDeclSpec->isThisDeclarationADefinition()"
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 4557, __extension__ __PRETTY_FUNCTION__))
;
4558
4559 // The type must match the tag exactly; no qualifiers allowed.
4560 if (!Context.hasSameType(NewTD->getUnderlyingType(),
4561 Context.getTagDeclType(TagFromDeclSpec))) {
4562 if (getLangOpts().CPlusPlus)
4563 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4564 return;
4565 }
4566
4567 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4568 // An unnamed class with a typedef name for linkage purposes shall [be
4569 // C-like].
4570 //
4571 // FIXME: Also diagnose if we've already computed the linkage. That ideally
4572 // shouldn't happen, but there are constructs that the language rule doesn't
4573 // disallow for which we can't reasonably avoid computing linkage early.
4574 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4575 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4576 : NonCLikeKind();
4577 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4578 if (NonCLike || ChangesLinkage) {
4579 if (NonCLike.Kind == NonCLikeKind::Invalid)
4580 return;
4581
4582 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4583 if (ChangesLinkage) {
4584 // If the linkage changes, we can't accept this as an extension.
4585 if (NonCLike.Kind == NonCLikeKind::None)
4586 DiagID = diag::err_typedef_changes_linkage;
4587 else
4588 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4589 }
4590
4591 SourceLocation FixitLoc =
4592 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4593 llvm::SmallString<40> TextToInsert;
4594 TextToInsert += ' ';
4595 TextToInsert += NewTD->getIdentifier()->getName();
4596
4597 Diag(FixitLoc, DiagID)
4598 << isa<TypeAliasDecl>(NewTD)
4599 << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4600 if (NonCLike.Kind != NonCLikeKind::None) {
4601 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4602 << NonCLike.Kind - 1 << NonCLike.Range;
4603 }
4604 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4605 << NewTD << isa<TypeAliasDecl>(NewTD);
4606
4607 if (ChangesLinkage)
4608 return;
4609 }
4610
4611 // Otherwise, set this as the anon-decl typedef for the tag.
4612 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4613}
4614
4615static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4616 switch (T) {
4617 case DeclSpec::TST_class:
4618 return 0;
4619 case DeclSpec::TST_struct:
4620 return 1;
4621 case DeclSpec::TST_interface:
4622 return 2;
4623 case DeclSpec::TST_union:
4624 return 3;
4625 case DeclSpec::TST_enum:
4626 return 4;
4627 default:
4628 llvm_unreachable("unexpected type specifier")::llvm::llvm_unreachable_internal("unexpected type specifier"
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 4628)
;
4629 }
4630}
4631
4632/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4633/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4634/// parameters to cope with template friend declarations.
4635Decl *
4636Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4637 MultiTemplateParamsArg TemplateParams,
4638 bool IsExplicitInstantiation,
4639 RecordDecl *&AnonRecord) {
4640 Decl *TagD = nullptr;
4641 TagDecl *Tag = nullptr;
4642 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4643 DS.getTypeSpecType() == DeclSpec::TST_struct ||
4644 DS.getTypeSpecType() == DeclSpec::TST_interface ||
4645 DS.getTypeSpecType() == DeclSpec::TST_union ||
4646 DS.getTypeSpecType() == DeclSpec::TST_enum) {
4647 TagD = DS.getRepAsDecl();
4648
4649 if (!TagD) // We probably had an error
4650 return nullptr;
4651
4652 // Note that the above type specs guarantee that the
4653 // type rep is a Decl, whereas in many of the others
4654 // it's a Type.
4655 if (isa<TagDecl>(TagD))
4656 Tag = cast<TagDecl>(TagD);
4657 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4658 Tag = CTD->getTemplatedDecl();
4659 }
4660
4661 if (Tag) {
4662 handleTagNumbering(Tag, S);
4663 Tag->setFreeStanding();
4664 if (Tag->isInvalidDecl())
4665 return Tag;
4666 }
4667
4668 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4669 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4670 // or incomplete types shall not be restrict-qualified."
4671 if (TypeQuals & DeclSpec::TQ_restrict)
4672 Diag(DS.getRestrictSpecLoc(),
4673 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4674 << DS.getSourceRange();
4675 }
4676
4677 if (DS.isInlineSpecified())
4678 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4679 << getLangOpts().CPlusPlus17;
4680
4681 if (DS.hasConstexprSpecifier()) {
4682 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4683 // and definitions of functions and variables.
4684 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4685 // the declaration of a function or function template
4686 if (Tag)
4687 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4688 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4689 << static_cast<int>(DS.getConstexprSpecifier());
4690 else
4691 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4692 << static_cast<int>(DS.getConstexprSpecifier());
4693 // Don't emit warnings after this error.
4694 return TagD;
4695 }
4696
4697 DiagnoseFunctionSpecifiers(DS);
4698
4699 if (DS.isFriendSpecified()) {
4700 // If we're dealing with a decl but not a TagDecl, assume that
4701 // whatever routines created it handled the friendship aspect.
4702 if (TagD && !Tag)
4703 return nullptr;
4704 return ActOnFriendTypeDecl(S, DS, TemplateParams);
4705 }
4706
4707 const CXXScopeSpec &SS = DS.getTypeSpecScope();
4708 bool IsExplicitSpecialization =
4709 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4710 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4711 !IsExplicitInstantiation && !IsExplicitSpecialization &&
4712 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4713 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4714 // nested-name-specifier unless it is an explicit instantiation
4715 // or an explicit specialization.
4716 //
4717 // FIXME: We allow class template partial specializations here too, per the
4718 // obvious intent of DR1819.
4719 //
4720 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4721 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4722 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4723 return nullptr;
4724 }
4725
4726 // Track whether this decl-specifier declares anything.
4727 bool DeclaresAnything = true;
4728
4729 // Handle anonymous struct definitions.
4730 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4731 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4732 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4733 if (getLangOpts().CPlusPlus ||
4734 Record->getDeclContext()->isRecord()) {
4735 // If CurContext is a DeclContext that can contain statements,
4736 // RecursiveASTVisitor won't visit the decls that
4737 // BuildAnonymousStructOrUnion() will put into CurContext.
4738 // Also store them here so that they can be part of the
4739 // DeclStmt that gets created in this case.
4740 // FIXME: Also return the IndirectFieldDecls created by
4741 // BuildAnonymousStructOr union, for the same reason?
4742 if (CurContext->isFunctionOrMethod())
4743 AnonRecord = Record;
4744 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4745 Context.getPrintingPolicy());
4746 }
4747
4748 DeclaresAnything = false;
4749 }
4750 }
4751
4752 // C11 6.7.2.1p2:
4753 // A struct-declaration that does not declare an anonymous structure or
4754 // anonymous union shall contain a struct-declarator-list.
4755 //
4756 // This rule also existed in C89 and C99; the grammar for struct-declaration
4757 // did not permit a struct-declaration without a struct-declarator-list.
4758 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4759 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4760 // Check for Microsoft C extension: anonymous struct/union member.
4761 // Handle 2 kinds of anonymous struct/union:
4762 // struct STRUCT;
4763 // union UNION;
4764 // and
4765 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
4766 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
4767 if ((Tag && Tag->getDeclName()) ||
4768 DS.getTypeSpecType() == DeclSpec::TST_typename) {
4769 RecordDecl *Record = nullptr;
4770 if (Tag)
4771 Record = dyn_cast<RecordDecl>(Tag);
4772 else if (const RecordType *RT =
4773 DS.getRepAsType().get()->getAsStructureType())
4774 Record = RT->getDecl();
4775 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4776 Record = UT->getDecl();
4777
4778 if (Record && getLangOpts().MicrosoftExt) {
4779 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4780 << Record->isUnion() << DS.getSourceRange();
4781 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4782 }
4783
4784 DeclaresAnything = false;
4785 }
4786 }
4787
4788 // Skip all the checks below if we have a type error.
4789 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4790 (TagD && TagD->isInvalidDecl()))
4791 return TagD;
4792
4793 if (getLangOpts().CPlusPlus &&
4794 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4795 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4796 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4797 !Enum->getIdentifier() && !Enum->isInvalidDecl())
4798 DeclaresAnything = false;
4799
4800 if (!DS.isMissingDeclaratorOk()) {
4801 // Customize diagnostic for a typedef missing a name.
4802 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4803 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4804 << DS.getSourceRange();
4805 else
4806 DeclaresAnything = false;
4807 }
4808
4809 if (DS.isModulePrivateSpecified() &&
4810 Tag && Tag->getDeclContext()->isFunctionOrMethod())
4811 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4812 << Tag->getTagKind()
4813 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4814
4815 ActOnDocumentableDecl(TagD);
4816
4817 // C 6.7/2:
4818 // A declaration [...] shall declare at least a declarator [...], a tag,
4819 // or the members of an enumeration.
4820 // C++ [dcl.dcl]p3:
4821 // [If there are no declarators], and except for the declaration of an
4822 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
4823 // names into the program, or shall redeclare a name introduced by a
4824 // previous declaration.
4825 if (!DeclaresAnything) {
4826 // In C, we allow this as a (popular) extension / bug. Don't bother
4827 // producing further diagnostics for redundant qualifiers after this.
4828 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
4829 ? diag::err_no_declarators
4830 : diag::ext_no_declarators)
4831 << DS.getSourceRange();
4832 return TagD;
4833 }
4834
4835 // C++ [dcl.stc]p1:
4836 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4837 // init-declarator-list of the declaration shall not be empty.
4838 // C++ [dcl.fct.spec]p1:
4839 // If a cv-qualifier appears in a decl-specifier-seq, the
4840 // init-declarator-list of the declaration shall not be empty.
4841 //
4842 // Spurious qualifiers here appear to be valid in C.
4843 unsigned DiagID = diag::warn_standalone_specifier;
4844 if (getLangOpts().CPlusPlus)
4845 DiagID = diag::ext_standalone_specifier;
4846
4847 // Note that a linkage-specification sets a storage class, but
4848 // 'extern "C" struct foo;' is actually valid and not theoretically
4849 // useless.
4850 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4851 if (SCS == DeclSpec::SCS_mutable)
4852 // Since mutable is not a viable storage class specifier in C, there is
4853 // no reason to treat it as an extension. Instead, diagnose as an error.
4854 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4855 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4856 Diag(DS.getStorageClassSpecLoc(), DiagID)
4857 << DeclSpec::getSpecifierName(SCS);
4858 }
4859
4860 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4861 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4862 << DeclSpec::getSpecifierName(TSCS);
4863 if (DS.getTypeQualifiers()) {
4864 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4865 Diag(DS.getConstSpecLoc(), DiagID) << "const";
4866 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4867 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4868 // Restrict is covered above.
4869 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4870 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4871 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4872 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4873 }
4874
4875 // Warn about ignored type attributes, for example:
4876 // __attribute__((aligned)) struct A;
4877 // Attributes should be placed after tag to apply to type declaration.
4878 if (!DS.getAttributes().empty()) {
4879 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4880 if (TypeSpecType == DeclSpec::TST_class ||
4881 TypeSpecType == DeclSpec::TST_struct ||
4882 TypeSpecType == DeclSpec::TST_interface ||
4883 TypeSpecType == DeclSpec::TST_union ||
4884 TypeSpecType == DeclSpec::TST_enum) {
4885 for (const ParsedAttr &AL : DS.getAttributes())
4886 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4887 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
4888 }
4889 }
4890
4891 return TagD;
4892}
4893
4894/// We are trying to inject an anonymous member into the given scope;
4895/// check if there's an existing declaration that can't be overloaded.
4896///
4897/// \return true if this is a forbidden redeclaration
4898static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4899 Scope *S,
4900 DeclContext *Owner,
4901 DeclarationName Name,
4902 SourceLocation NameLoc,
4903 bool IsUnion) {
4904 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4905 Sema::ForVisibleRedeclaration);
4906 if (!SemaRef.LookupName(R, S)) return false;
4907
4908 // Pick a representative declaration.
4909 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4910 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 4910, __extension__ __PRETTY_FUNCTION__))
;
4911
4912 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4913 return false;
4914
4915 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4916 << IsUnion << Name;
4917 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4918
4919 return true;
4920}
4921
4922/// InjectAnonymousStructOrUnionMembers - Inject the members of the
4923/// anonymous struct or union AnonRecord into the owning context Owner
4924/// and scope S. This routine will be invoked just after we realize
4925/// that an unnamed union or struct is actually an anonymous union or
4926/// struct, e.g.,
4927///
4928/// @code
4929/// union {
4930/// int i;
4931/// float f;
4932/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4933/// // f into the surrounding scope.x
4934/// @endcode
4935///
4936/// This routine is recursive, injecting the names of nested anonymous
4937/// structs/unions into the owning context and scope as well.
4938static bool
4939InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4940 RecordDecl *AnonRecord, AccessSpecifier AS,
4941 SmallVectorImpl<NamedDecl *> &Chaining) {
4942 bool Invalid = false;
4943
4944 // Look every FieldDecl and IndirectFieldDecl with a name.
4945 for (auto *D : AnonRecord->decls()) {
4946 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4947 cast<NamedDecl>(D)->getDeclName()) {
4948 ValueDecl *VD = cast<ValueDecl>(D);
4949 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4950 VD->getLocation(),
4951 AnonRecord->isUnion())) {
4952 // C++ [class.union]p2:
4953 // The names of the members of an anonymous union shall be
4954 // distinct from the names of any other entity in the
4955 // scope in which the anonymous union is declared.
4956 Invalid = true;
4957 } else {
4958 // C++ [class.union]p2:
4959 // For the purpose of name lookup, after the anonymous union
4960 // definition, the members of the anonymous union are
4961 // considered to have been defined in the scope in which the
4962 // anonymous union is declared.
4963 unsigned OldChainingSize = Chaining.size();
4964 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4965 Chaining.append(IF->chain_begin(), IF->chain_end());
4966 else
4967 Chaining.push_back(VD);
4968
4969 assert(Chaining.size() >= 2)(static_cast <bool> (Chaining.size() >= 2) ? void (0
) : __assert_fail ("Chaining.size() >= 2", "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 4969, __extension__ __PRETTY_FUNCTION__))
;
4970 NamedDecl **NamedChain =
4971 new (SemaRef.Context)NamedDecl*[Chaining.size()];
4972 for (unsigned i = 0; i < Chaining.size(); i++)
4973 NamedChain[i] = Chaining[i];
4974
4975 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4976 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4977 VD->getType(), {NamedChain, Chaining.size()});
4978
4979 for (const auto *Attr : VD->attrs())
4980 IndirectField->addAttr(Attr->clone(SemaRef.Context));
4981
4982 IndirectField->setAccess(AS);
4983 IndirectField->setImplicit();
4984 SemaRef.PushOnScopeChains(IndirectField, S);
4985
4986 // That includes picking up the appropriate access specifier.
4987 if (AS != AS_none) IndirectField->setAccess(AS);
4988
4989 Chaining.resize(OldChainingSize);
4990 }
4991 }
4992 }
4993
4994 return Invalid;
4995}
4996
4997/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4998/// a VarDecl::StorageClass. Any error reporting is up to the caller:
4999/// illegal input values are mapped to SC_None.
5000static StorageClass
5001StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5002 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5003 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.\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 5004, __extension__ __PRETTY_FUNCTION__))
5004 "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.\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 5004, __extension__ __PRETTY_FUNCTION__))
;
5005 switch (StorageClassSpec) {
5006 case DeclSpec::SCS_unspecified: return SC_None;
5007 case DeclSpec::SCS_extern:
5008 if (DS.isExternInLinkageSpec())
5009 return SC_None;
5010 return SC_Extern;
5011 case DeclSpec::SCS_static: return SC_Static;
5012 case DeclSpec::SCS_auto: return SC_Auto;
5013 case DeclSpec::SCS_register: return SC_Register;
5014 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5015 // Illegal SCSs map to None: error reporting is up to the caller.
5016 case DeclSpec::SCS_mutable: // Fall through.
5017 case DeclSpec::SCS_typedef: return SC_None;
5018 }
5019 llvm_unreachable("unknown storage class specifier")::llvm::llvm_unreachable_internal("unknown storage class specifier"
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 5019)
;
5020}
5021
5022static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5023 assert(Record->hasInClassInitializer())(static_cast <bool> (Record->hasInClassInitializer()
) ? void (0) : __assert_fail ("Record->hasInClassInitializer()"
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 5023, __extension__ __PRETTY_FUNCTION__))
;
5024
5025 for (const auto *I : Record->decls()) {
5026 const auto *FD = dyn_cast<FieldDecl>(I);
5027 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5028 FD = IFD->getAnonField();
5029 if (FD && FD->hasInClassInitializer())
5030 return FD->getLocation();
5031 }
5032
5033 llvm_unreachable("couldn't find in-class initializer")::llvm::llvm_unreachable_internal("couldn't find in-class initializer"
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 5033)
;
5034}
5035
5036static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5037 SourceLocation DefaultInitLoc) {
5038 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5039 return;
5040
5041 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5042 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5043}
5044
5045static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5046 CXXRecordDecl *AnonUnion) {
5047 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5048 return;
5049
5050 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
5051}
5052
5053/// BuildAnonymousStructOrUnion - Handle the declaration of an
5054/// anonymous structure or union. Anonymous unions are a C++ feature
5055/// (C++ [class.union]) and a C11 feature; anonymous structures
5056/// are a C11 feature and GNU C++ extension.
5057Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5058 AccessSpecifier AS,
5059 RecordDecl *Record,
5060 const PrintingPolicy &Policy) {
5061 DeclContext *Owner = Record->getDeclContext();
5062
5063 // Diagnose whether this anonymous struct/union is an extension.
5064 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5065 Diag(Record->getLocation(), diag::ext_anonymous_union);
5066 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5067 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5068 else if (!Record->isUnion() && !getLangOpts().C11)
5069 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5070
5071 // C and C++ require different kinds of checks for anonymous
5072 // structs/unions.
5073 bool Invalid = false;
5074 if (getLangOpts().CPlusPlus) {
5075 const char *PrevSpec = nullptr;
5076 if (Record->isUnion()) {
5077 // C++ [class.union]p6:
5078 // C++17 [class.union.anon]p2:
5079 // Anonymous unions declared in a named namespace or in the
5080 // global namespace shall be declared static.
5081 unsigned DiagID;
5082 DeclContext *OwnerScope = Owner->getRedeclContext();
5083 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5084 (OwnerScope->isTranslationUnit() ||
5085 (OwnerScope->isNamespace() &&
5086 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5087 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5088 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5089
5090 // Recover by adding 'static'.
5091 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5092 PrevSpec, DiagID, Policy);
5093 }
5094 // C++ [class.union]p6:
5095 // A storage class is not allowed in a declaration of an
5096 // anonymous union in a class scope.
5097 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5098 isa<RecordDecl>(Owner)) {
5099 Diag(DS.getStorageClassSpecLoc(),
5100 diag::err_anonymous_union_with_storage_spec)
5101 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5102
5103 // Recover by removing the storage specifier.
5104 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5105 SourceLocation(),
5106 PrevSpec, DiagID, Context.getPrintingPolicy());
5107 }
5108 }
5109
5110 // Ignore const/volatile/restrict qualifiers.
5111 if (DS.getTypeQualifiers()) {
5112 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5113 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5114 << Record->isUnion() << "const"
5115 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5116 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5117 Diag(DS.getVolatileSpecLoc(),
5118 diag::ext_anonymous_struct_union_qualified)
5119 << Record->isUnion() << "volatile"
5120 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5121 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5122 Diag(DS.getRestrictSpecLoc(),
5123 diag::ext_anonymous_struct_union_qualified)
5124 << Record->isUnion() << "restrict"
5125 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5126 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5127 Diag(DS.getAtomicSpecLoc(),
5128 diag::ext_anonymous_struct_union_qualified)
5129 << Record->isUnion() << "_Atomic"
5130 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5131 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5132 Diag(DS.getUnalignedSpecLoc(),
5133 diag::ext_anonymous_struct_union_qualified)
5134 << Record->isUnion() << "__unaligned"
5135 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5136
5137 DS.ClearTypeQualifiers();
5138 }
5139
5140 // C++ [class.union]p2:
5141 // The member-specification of an anonymous union shall only
5142 // define non-static data members. [Note: nested types and
5143 // functions cannot be declared within an anonymous union. ]
5144 for (auto *Mem : Record->decls()) {
5145 // Ignore invalid declarations; we already diagnosed them.
5146 if (Mem->isInvalidDecl())
5147 continue;
5148
5149 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5150 // C++ [class.union]p3:
5151 // An anonymous union shall not have private or protected
5152 // members (clause 11).
5153 assert(FD->getAccess() != AS_none)(static_cast <bool> (FD->getAccess() != AS_none) ? void
(0) : __assert_fail ("FD->getAccess() != AS_none", "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 5153, __extension__ __PRETTY_FUNCTION__))
;
5154 if (FD->getAccess() != AS_public) {
5155 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5156 << Record->isUnion() << (FD->getAccess() == AS_protected);
5157 Invalid = true;
5158 }
5159
5160 // C++ [class.union]p1
5161 // An object of a class with a non-trivial constructor, a non-trivial
5162 // copy constructor, a non-trivial destructor, or a non-trivial copy
5163 // assignment operator cannot be a member of a union, nor can an
5164 // array of such objects.
5165 if (CheckNontrivialField(FD))
5166 Invalid = true;
5167 } else if (Mem->isImplicit()) {
5168 // Any implicit members are fine.
5169 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5170 // This is a type that showed up in an
5171 // elaborated-type-specifier inside the anonymous struct or
5172 // union, but which actually declares a type outside of the
5173 // anonymous struct or union. It's okay.
5174 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5175 if (!MemRecord->isAnonymousStructOrUnion() &&
5176 MemRecord->getDeclName()) {
5177 // Visual C++ allows type definition in anonymous struct or union.
5178 if (getLangOpts().MicrosoftExt)
5179 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5180 << Record->isUnion();
5181 else {
5182 // This is a nested type declaration.
5183 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5184 << Record->isUnion();
5185 Invalid = true;
5186 }
5187 } else {
5188 // This is an anonymous type definition within another anonymous type.
5189 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5190 // not part of standard C++.
5191 Diag(MemRecord->getLocation(),
5192 diag::ext_anonymous_record_with_anonymous_type)
5193 << Record->isUnion();
5194 }
5195 } else if (isa<AccessSpecDecl>(Mem)) {
5196 // Any access specifier is fine.
5197 } else if (isa<StaticAssertDecl>(Mem)) {
5198 // In C++1z, static_assert declarations are also fine.
5199 } else {
5200 // We have something that isn't a non-static data
5201 // member. Complain about it.
5202 unsigned DK = diag::err_anonymous_record_bad_member;
5203 if (isa<TypeDecl>(Mem))
5204 DK = diag::err_anonymous_record_with_type;
5205 else if (isa<FunctionDecl>(Mem))
5206 DK = diag::err_anonymous_record_with_function;
5207 else if (isa<VarDecl>(Mem))
5208 DK = diag::err_anonymous_record_with_static;
5209
5210 // Visual C++ allows type definition in anonymous struct or union.
5211 if (getLangOpts().MicrosoftExt &&
5212 DK == diag::err_anonymous_record_with_type)
5213 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5214 << Record->isUnion();
5215 else {
5216 Diag(Mem->getLocation(), DK) << Record->isUnion();
5217 Invalid = true;
5218 }
5219 }
5220 }
5221
5222 // C++11 [class.union]p8 (DR1460):
5223 // At most one variant member of a union may have a
5224 // brace-or-equal-initializer.
5225 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5226 Owner->isRecord())
5227 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5228 cast<CXXRecordDecl>(Record));
5229 }
5230
5231 if (!Record->isUnion() && !Owner->isRecord()) {
5232 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5233 << getLangOpts().CPlusPlus;
5234 Invalid = true;
5235 }
5236
5237 // C++ [dcl.dcl]p3:
5238 // [If there are no declarators], and except for the declaration of an
5239 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5240 // names into the program
5241 // C++ [class.mem]p2:
5242 // each such member-declaration shall either declare at least one member
5243 // name of the class or declare at least one unnamed bit-field
5244 //
5245 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5246 if (getLangOpts().CPlusPlus && Record->field_empty())
5247 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5248
5249 // Mock up a declarator.
5250 Declarator Dc(DS, DeclaratorContext::Member);
5251 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5252 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 5252, __extension__ __PRETTY_FUNCTION__))
;
5253
5254 // Create a declaration for this anonymous struct/union.
5255 NamedDecl *Anon = nullptr;
5256 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5257 Anon = FieldDecl::Create(
5258 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5259 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5260 /*BitWidth=*/nullptr, /*Mutable=*/false,
5261 /*InitStyle=*/ICIS_NoInit);
5262 Anon->setAccess(AS);
5263 ProcessDeclAttributes(S, Anon, Dc);
5264
5265 if (getLangOpts().CPlusPlus)
5266 FieldCollector->Add(cast<FieldDecl>(Anon));
5267 } else {
5268 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5269 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5270 if (SCSpec == DeclSpec::SCS_mutable) {
5271 // mutable can only appear on non-static class members, so it's always
5272 // an error here
5273 Diag(Record->getLocation(), diag::err_mutable_nonmember);
5274 Invalid = true;
5275 SC = SC_None;
5276 }
5277
5278 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 5278, __extension__ __PRETTY_FUNCTION__))
;
5279 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5280 Record->getLocation(), /*IdentifierInfo=*/nullptr,
5281 Context.getTypeDeclType(Record), TInfo, SC);
5282
5283 // Default-initialize the implicit variable. This initialization will be
5284 // trivial in almost all cases, except if a union member has an in-class
5285 // initializer:
5286 // union { int n = 0; };
5287 if (!Invalid)
5288 ActOnUninitializedDecl(Anon);
5289 }
5290 Anon->setImplicit();
5291
5292 // Mark this as an anonymous struct/union type.
5293 Record->setAnonymousStructOrUnion(true);
5294
5295 // Add the anonymous struct/union object to the current
5296 // context. We'll be referencing this object when we refer to one of
5297 // its members.
5298 Owner->addDecl(Anon);
5299
5300 // Inject the members of the anonymous struct/union into the owning
5301 // context and into the identifier resolver chain for name lookup
5302 // purposes.
5303 SmallVector<NamedDecl*, 2> Chain;
5304 Chain.push_back(Anon);
5305
5306 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5307 Invalid = true;
5308
5309 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5310 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5311 MangleNumberingContext *MCtx;
5312 Decl *ManglingContextDecl;
5313 std::tie(MCtx, ManglingContextDecl) =
5314 getCurrentMangleNumberContext(NewVD->getDeclContext());
5315 if (MCtx) {
5316 Context.setManglingNumber(
5317 NewVD, MCtx->getManglingNumber(
5318 NewVD, getMSManglingNumber(getLangOpts(), S)));
5319 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5320 }
5321 }
5322 }
5323
5324 if (Invalid)
5325 Anon->setInvalidDecl();
5326
5327 return Anon;
5328}
5329
5330/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5331/// Microsoft C anonymous structure.
5332/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5333/// Example:
5334///
5335/// struct A { int a; };
5336/// struct B { struct A; int b; };
5337///
5338/// void foo() {
5339/// B var;
5340/// var.a = 3;
5341/// }
5342///
5343Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5344 RecordDecl *Record) {
5345 assert(Record && "expected a record!")(static_cast <bool> (Record && "expected a record!"
) ? void (0) : __assert_fail ("Record && \"expected a record!\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 5345, __extension__ __PRETTY_FUNCTION__))
;
5346
5347 // Mock up a declarator.
5348 Declarator Dc(DS, DeclaratorContext::TypeName);
5349 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5350 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 5350, __extension__ __PRETTY_FUNCTION__))
;
5351
5352 auto *ParentDecl = cast<RecordDecl>(CurContext);
5353 QualType RecTy = Context.getTypeDeclType(Record);
5354
5355 // Create a declaration for this anonymous struct.
5356 NamedDecl *Anon =
5357 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5358 /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5359 /*BitWidth=*/nullptr, /*Mutable=*/false,
5360 /*InitStyle=*/ICIS_NoInit);
5361 Anon->setImplicit();
5362
5363 // Add the anonymous struct object to the current context.
5364 CurContext->addDecl(Anon);
5365
5366 // Inject the members of the anonymous struct into the current
5367 // context and into the identifier resolver chain for name lookup
5368 // purposes.
5369 SmallVector<NamedDecl*, 2> Chain;
5370 Chain.push_back(Anon);
5371
5372 RecordDecl *RecordDef = Record->getDefinition();
5373 if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5374 diag::err_field_incomplete_or_sizeless) ||
5375 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5376 AS_none, Chain)) {
5377 Anon->setInvalidDecl();
5378 ParentDecl->setInvalidDecl();
5379 }
5380
5381 return Anon;
5382}
5383
5384/// GetNameForDeclarator - Determine the full declaration name for the
5385/// given Declarator.
5386DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5387 return GetNameFromUnqualifiedId(D.getName());
5388}
5389
5390/// Retrieves the declaration name from a parsed unqualified-id.
5391DeclarationNameInfo
5392Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5393 DeclarationNameInfo NameInfo;
5394 NameInfo.setLoc(Name.StartLocation);
5395
5396 switch (Name.getKind()) {
5397
5398 case UnqualifiedIdKind::IK_ImplicitSelfParam:
5399 case UnqualifiedIdKind::IK_Identifier:
5400 NameInfo.setName(Name.Identifier);
5401 return NameInfo;
5402
5403 case UnqualifiedIdKind::IK_DeductionGuideName: {
5404 // C++ [temp.deduct.guide]p3:
5405 // The simple-template-id shall name a class template specialization.
5406 // The template-name shall be the same identifier as the template-name
5407 // of the simple-template-id.
5408 // These together intend to imply that the template-name shall name a
5409 // class template.
5410 // FIXME: template<typename T> struct X {};
5411 // template<typename T> using Y = X<T>;
5412 // Y(int) -> Y<int>;
5413 // satisfies these rules but does not name a class template.
5414 TemplateName TN = Name.TemplateName.get().get();
5415 auto *Template = TN.getAsTemplateDecl();
5416 if (!Template || !isa<ClassTemplateDecl>(Template)) {
5417 Diag(Name.StartLocation,
5418 diag::err_deduction_guide_name_not_class_template)
5419 << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5420 if (Template)
5421 Diag(Template->getLocation(), diag::note_template_decl_here);
5422 return DeclarationNameInfo();
5423 }
5424
5425 NameInfo.setName(
5426 Context.DeclarationNames.getCXXDeductionGuideName(Template));
5427 return NameInfo;
5428 }
5429
5430 case UnqualifiedIdKind::IK_OperatorFunctionId:
5431 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5432 Name.OperatorFunctionId.Operator));
5433 NameInfo.setCXXOperatorNameRange(SourceRange(
5434 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5435 return NameInfo;
5436
5437 case UnqualifiedIdKind::IK_LiteralOperatorId:
5438 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5439 Name.Identifier));
5440 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5441 return NameInfo;
5442
5443 case UnqualifiedIdKind::IK_ConversionFunctionId: {
5444 TypeSourceInfo *TInfo;
5445 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5446 if (Ty.isNull())
5447 return DeclarationNameInfo();
5448 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5449 Context.getCanonicalType(Ty)));
5450 NameInfo.setNamedTypeInfo(TInfo);
5451 return NameInfo;
5452 }
5453
5454 case UnqualifiedIdKind::IK_ConstructorName: {
5455 TypeSourceInfo *TInfo;
5456 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5457 if (Ty.isNull())
5458 return DeclarationNameInfo();
5459 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5460 Context.getCanonicalType(Ty)));
5461 NameInfo.setNamedTypeInfo(TInfo);
5462 return NameInfo;
5463 }
5464
5465 case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5466 // In well-formed code, we can only have a constructor
5467 // template-id that refers to the current context, so go there
5468 // to find the actual type being constructed.
5469 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5470 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5471 return DeclarationNameInfo();
5472
5473 // Determine the type of the class being constructed.
5474 QualType CurClassType = Context.getTypeDeclType(CurClass);
5475
5476 // FIXME: Check two things: that the template-id names the same type as
5477 // CurClassType, and that the template-id does not occur when the name
5478 // was qualified.
5479
5480 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5481 Context.getCanonicalType(CurClassType)));
5482 // FIXME: should we retrieve TypeSourceInfo?
5483 NameInfo.setNamedTypeInfo(nullptr);
5484 return NameInfo;
5485 }
5486
5487 case UnqualifiedIdKind::IK_DestructorName: {
5488 TypeSourceInfo *TInfo;
5489 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5490 if (Ty.isNull())
5491 return DeclarationNameInfo();
5492 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5493 Context.getCanonicalType(Ty)));
5494 NameInfo.setNamedTypeInfo(TInfo);
5495 return NameInfo;
5496 }
5497
5498 case UnqualifiedIdKind::IK_TemplateId: {
5499 TemplateName TName = Name.TemplateId->Template.get();
5500 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5501 return Context.getNameForTemplate(TName, TNameLoc);
5502 }
5503
5504 } // switch (Name.getKind())
5505
5506 llvm_unreachable("Unknown name kind")::llvm::llvm_unreachable_internal("Unknown name kind", "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 5506)
;
5507}
5508
5509static QualType getCoreType(QualType Ty) {
5510 do {
5511 if (Ty->isPointerType() || Ty->isReferenceType())
5512 Ty = Ty->getPointeeType();
5513 else if (Ty->isArrayType())
5514 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5515 else
5516 return Ty.withoutLocalFastQualifiers();
5517 } while (true);
5518}
5519
5520/// hasSimilarParameters - Determine whether the C++ functions Declaration
5521/// and Definition have "nearly" matching parameters. This heuristic is
5522/// used to improve diagnostics in the case where an out-of-line function
5523/// definition doesn't match any declaration within the class or namespace.
5524/// Also sets Params to the list of indices to the parameters that differ
5525/// between the declaration and the definition. If hasSimilarParameters
5526/// returns true and Params is empty, then all of the parameters match.
5527static bool hasSimilarParameters(ASTContext &Context,
5528 FunctionDecl *Declaration,
5529 FunctionDecl *Definition,
5530 SmallVectorImpl<unsigned> &Params) {
5531 Params.clear();
5532 if (Declaration->param_size() != Definition->param_size())
5533 return false;
5534 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5535 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5536 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5537
5538 // The parameter types are identical
5539 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5540 continue;
5541
5542 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5543 QualType DefParamBaseTy = getCoreType(DefParamTy);
5544 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5545 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5546
5547 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5548 (DeclTyName && DeclTyName == DefTyName))
5549 Params.push_back(Idx);
5550 else // The two parameters aren't even close
5551 return false;
5552 }
5553
5554 return true;
5555}
5556
5557/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5558/// declarator needs to be rebuilt in the current instantiation.
5559/// Any bits of declarator which appear before the name are valid for
5560/// consideration here. That's specifically the type in the decl spec
5561/// and the base type in any member-pointer chunks.
5562static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5563 DeclarationName Name) {
5564 // The types we specifically need to rebuild are:
5565 // - typenames, typeofs, and decltypes
5566 // - types which will become injected class names
5567 // Of course, we also need to rebuild any type referencing such a
5568 // type. It's safest to just say "dependent", but we call out a
5569 // few cases here.
5570
5571 DeclSpec &DS = D.getMutableDeclSpec();
5572 switch (DS.getTypeSpecType()) {
5573 case DeclSpec::TST_typename:
5574 case DeclSpec::TST_typeofType:
5575 case DeclSpec::TST_underlyingType:
5576 case DeclSpec::TST_atomic: {
5577 // Grab the type from the parser.
5578 TypeSourceInfo *TSI = nullptr;
5579 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5580 if (T.isNull() || !T->isInstantiationDependentType()) break;
5581
5582 // Make sure there's a type source info. This isn't really much
5583 // of a waste; most dependent types should have type source info
5584 // attached already.
5585 if (!TSI)
5586 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5587
5588 // Rebuild the type in the current instantiation.
5589 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5590 if (!TSI) return true;
5591
5592 // Store the new type back in the decl spec.
5593 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5594 DS.UpdateTypeRep(LocType);
5595 break;
5596 }
5597
5598 case DeclSpec::TST_decltype:
5599 case DeclSpec::TST_typeofExpr: {
5600 Expr *E = DS.getRepAsExpr();
5601 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5602 if (Result.isInvalid()) return true;
5603 DS.UpdateExprRep(Result.get());
5604 break;
5605 }
5606
5607 default:
5608 // Nothing to do for these decl specs.
5609 break;
5610 }
5611
5612 // It doesn't matter what order we do this in.
5613 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5614 DeclaratorChunk &Chunk = D.getTypeObject(I);
5615
5616 // The only type information in the declarator which can come
5617 // before the declaration name is the base type of a member
5618 // pointer.
5619 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5620 continue;
5621
5622 // Rebuild the scope specifier in-place.
5623 CXXScopeSpec &SS = Chunk.Mem.Scope();
5624 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5625 return true;
5626 }
5627
5628 return false;
5629}
5630
5631void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
5632 // Avoid warning twice on the same identifier, and don't warn on redeclaration
5633 // of system decl.
5634 if (D->getPreviousDecl() || D->isImplicit())
5635 return;
5636 ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
5637 if (Status != ReservedIdentifierStatus::NotReserved &&
5638 !Context.getSourceManager().isInSystemHeader(D->getLocation()))
5639 Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
5640 << D << static_cast<int>(Status);
5641}
5642
5643Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5644 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
5645 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5646
5647 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5648 Dcl && Dcl->getDeclContext()->isFileContext())
5649 Dcl->setTopLevelDeclInObjCContainer();
5650
5651 return Dcl;
5652}
5653
5654/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5655/// If T is the name of a class, then each of the following shall have a
5656/// name different from T:
5657/// - every static data member of class T;
5658/// - every member function of class T
5659/// - every member of class T that is itself a type;
5660/// \returns true if the declaration name violates these rules.
5661bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5662 DeclarationNameInfo NameInfo) {
5663 DeclarationName Name = NameInfo.getName();
5664
5665 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5666 while (Record && Record->isAnonymousStructOrUnion())
5667 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5668 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5669 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5670 return true;
5671 }
5672
5673 return false;
5674}
5675
5676/// Diagnose a declaration whose declarator-id has the given
5677/// nested-name-specifier.
5678///
5679/// \param SS The nested-name-specifier of the declarator-id.
5680///
5681/// \param DC The declaration context to which the nested-name-specifier
5682/// resolves.
5683///
5684/// \param Name The name of the entity being declared.
5685///
5686/// \param Loc The location of the name of the entity being declared.
5687///
5688/// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5689/// we're declaring an explicit / partial specialization / instantiation.
5690///
5691/// \returns true if we cannot safely recover from this error, false otherwise.
5692bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5693 DeclarationName Name,
5694 SourceLocation Loc, bool IsTemplateId) {
5695 DeclContext *Cur = CurContext;
5696 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5697 Cur = Cur->getParent();
5698
5699 // If the user provided a superfluous scope specifier that refers back to the
5700 // class in which the entity is already declared, diagnose and ignore it.
5701 //
5702 // class X {
5703 // void X::f();
5704 // };
5705 //
5706 // Note, it was once ill-formed to give redundant qualification in all
5707 // contexts, but that rule was removed by DR482.
5708 if (Cur->Equals(DC)) {
5709 if (Cur->isRecord()) {
5710 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5711 : diag::err_member_extra_qualification)
5712 << Name << FixItHint::CreateRemoval(SS.getRange());
5713 SS.clear();
5714 } else {
5715 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5716 }
5717 return false;
5718 }
5719
5720 // Check whether the qualifying scope encloses the scope of the original
5721 // declaration. For a template-id, we perform the checks in
5722 // CheckTemplateSpecializationScope.
5723 if (!Cur->Encloses(DC) && !IsTemplateId) {
5724 if (Cur->isRecord())
5725 Diag(Loc, diag::err_member_qualification)
5726 << Name << SS.getRange();
5727 else if (isa<TranslationUnitDecl>(DC))
5728 Diag(Loc, diag::err_invalid_declarator_global_scope)
5729 << Name << SS.getRange();
5730 else if (isa<FunctionDecl>(Cur))
5731 Diag(Loc, diag::err_invalid_declarator_in_function)
5732 << Name << SS.getRange();
5733 else if (isa<BlockDecl>(Cur))
5734 Diag(Loc, diag::err_invalid_declarator_in_block)
5735 << Name << SS.getRange();
5736 else
5737 Diag(Loc, diag::err_invalid_declarator_scope)
5738 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5739
5740 return true;
5741 }
5742
5743 if (Cur->isRecord()) {
5744 // Cannot qualify members within a class.
5745 Diag(Loc, diag::err_member_qualification)
5746 << Name << SS.getRange();
5747 SS.clear();
5748
5749 // C++ constructors and destructors with incorrect scopes can break
5750 // our AST invariants by having the wrong underlying types. If
5751 // that's the case, then drop this declaration entirely.
5752 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5753 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5754 !Context.hasSameType(Name.getCXXNameType(),
5755 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5756 return true;
5757
5758 return false;
5759 }
5760
5761 // C++11 [dcl.meaning]p1:
5762 // [...] "The nested-name-specifier of the qualified declarator-id shall
5763 // not begin with a decltype-specifer"
5764 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5765 while (SpecLoc.getPrefix())
5766 SpecLoc = SpecLoc.getPrefix();
5767 if (dyn_cast_or_null<DecltypeType>(
5768 SpecLoc.getNestedNameSpecifier()->getAsType()))
5769 Diag(Loc, diag::err_decltype_in_declarator)
5770 << SpecLoc.getTypeLoc().getSourceRange();
5771
5772 return false;
5773}
5774
5775NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5776 MultiTemplateParamsArg TemplateParamLists) {
5777 // TODO: consider using NameInfo for diagnostic.
5778 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5779 DeclarationName Name = NameInfo.getName();
5780
5781 // All of these full declarators require an identifier. If it doesn't have
5782 // one, the ParsedFreeStandingDeclSpec action should be used.
5783 if (D.isDecompositionDeclarator()) {
5784 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5785 } else if (!Name) {
5786 if (!D.isInvalidType()) // Reject this if we think it is valid.
5787 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5788 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5789 return nullptr;
5790 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5791 return nullptr;
5792
5793 // The scope passed in may not be a decl scope. Zip up the scope tree until
5794 // we find one that is.
5795 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5796 (S->getFlags() & Scope::TemplateParamScope) != 0)
5797 S = S->getParent();
5798
5799 DeclContext *DC = CurContext;
5800 if (D.getCXXScopeSpec().isInvalid())
5801 D.setInvalidType();
5802 else if (D.getCXXScopeSpec().isSet()) {
5803 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5804 UPPC_DeclarationQualifier))
5805 return nullptr;
5806
5807 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5808 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5809 if (!DC || isa<EnumDecl>(DC)) {
5810 // If we could not compute the declaration context, it's because the
5811 // declaration context is dependent but does not refer to a class,
5812 // class template, or class template partial specialization. Complain
5813 // and return early, to avoid the coming semantic disaster.
5814 Diag(D.getIdentifierLoc(),
5815 diag::err_template_qualified_declarator_no_match)
5816 << D.getCXXScopeSpec().getScopeRep()
5817 << D.getCXXScopeSpec().getRange();
5818 return nullptr;
5819 }
5820 bool IsDependentContext = DC->isDependentContext();
5821
5822 if (!IsDependentContext &&
5823 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5824 return nullptr;
5825
5826 // If a class is incomplete, do not parse entities inside it.
5827 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5828 Diag(D.getIdentifierLoc(),
5829 diag::err_member_def_undefined_record)
5830 << Name << DC << D.getCXXScopeSpec().getRange();
5831 return nullptr;
5832 }
5833 if (!D.getDeclSpec().isFriendSpecified()) {
5834 if (diagnoseQualifiedDeclaration(
5835 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5836 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5837 if (DC->isRecord())
5838 return nullptr;
5839
5840 D.setInvalidType();
5841 }
5842 }
5843
5844 // Check whether we need to rebuild the type of the given
5845 // declaration in the current instantiation.
5846 if (EnteringContext && IsDependentContext &&
5847 TemplateParamLists.size() != 0) {
5848 ContextRAII SavedContext(*this, DC);
5849 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5850 D.setInvalidType();
5851 }
5852 }
5853
5854 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5855 QualType R = TInfo->getType();
5856
5857 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5858 UPPC_DeclarationType))
5859 D.setInvalidType();
5860
5861 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5862 forRedeclarationInCurContext());
5863
5864 // See if this is a redefinition of a variable in the same scope.
5865 if (!D.getCXXScopeSpec().isSet()) {
5866 bool IsLinkageLookup = false;
5867 bool CreateBuiltins = false;
5868
5869 // If the declaration we're planning to build will be a function
5870 // or object with linkage, then look for another declaration with
5871 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5872 //
5873 // If the declaration we're planning to build will be declared with
5874 // external linkage in the translation unit, create any builtin with
5875 // the same name.
5876 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5877 /* Do nothing*/;
5878 else if (CurContext->isFunctionOrMethod() &&
5879 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5880 R->isFunctionType())) {
5881 IsLinkageLookup = true;
5882 CreateBuiltins =
5883 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5884 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5885 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5886 CreateBuiltins = true;
5887
5888 if (IsLinkageLookup) {
5889 Previous.clear(LookupRedeclarationWithLinkage);
5890 Previous.setRedeclarationKind(ForExternalRedeclaration);
5891 }
5892
5893 LookupName(Previous, S, CreateBuiltins);
5894 } else { // Something like "int foo::x;"
5895 LookupQualifiedName(Previous, DC);
5896
5897 // C++ [dcl.meaning]p1:
5898 // When the declarator-id is qualified, the declaration shall refer to a
5899 // previously declared member of the class or namespace to which the
5900 // qualifier refers (or, in the case of a namespace, of an element of the
5901 // inline namespace set of that namespace (7.3.1)) or to a specialization
5902 // thereof; [...]
5903 //
5904 // Note that we already checked the context above, and that we do not have
5905 // enough information to make sure that Previous contains the declaration
5906 // we want to match. For example, given:
5907 //
5908 // class X {
5909 // void f();
5910 // void f(float);
5911 // };
5912 //
5913 // void X::f(int) { } // ill-formed
5914 //
5915 // In this case, Previous will point to the overload set
5916 // containing the two f's declared in X, but neither of them
5917 // matches.
5918
5919 // C++ [dcl.meaning]p1:
5920 // [...] the member shall not merely have been introduced by a
5921 // using-declaration in the scope of the class or namespace nominated by
5922 // the nested-name-specifier of the declarator-id.
5923 RemoveUsingDecls(Previous);
5924 }
5925
5926 if (Previous.isSingleResult() &&
5927 Previous.getFoundDecl()->isTemplateParameter()) {
5928 // Maybe we will complain about the shadowed template parameter.
5929 if (!D.isInvalidType())
5930 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5931 Previous.getFoundDecl());
5932
5933 // Just pretend that we didn't see the previous declaration.
5934 Previous.clear();
5935 }
5936
5937 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5938 // Forget that the previous declaration is the injected-class-name.
5939 Previous.clear();
5940
5941 // In C++, the previous declaration we find might be a tag type
5942 // (class or enum). In this case, the new declaration will hide the
5943 // tag type. Note that this applies to functions, function templates, and
5944 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5945 if (Previous.isSingleTagDecl() &&
5946 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5947 (TemplateParamLists.size() == 0 || R->isFunctionType()))
5948 Previous.clear();
5949
5950 // Check that there are no default arguments other than in the parameters
5951 // of a function declaration (C++ only).
5952 if (getLangOpts().CPlusPlus)
5953 CheckExtraCXXDefaultArguments(D);
5954
5955 NamedDecl *New;
5956
5957 bool AddToScope = true;
5958 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5959 if (TemplateParamLists.size()) {
5960 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5961 return nullptr;
5962 }
5963
5964 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5965 } else if (R->isFunctionType()) {
5966 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5967 TemplateParamLists,
5968 AddToScope);
5969 } else {
5970 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5971 AddToScope);
5972 }
5973
5974 if (!New)
5975 return nullptr;
5976
5977 // If this has an identifier and is not a function template specialization,
5978 // add it to the scope stack.
5979 if (New->getDeclName() && AddToScope)
5980 PushOnScopeChains(New, S);
5981
5982 if (isInOpenMPDeclareTargetContext())
5983 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5984
5985 return New;
5986}
5987
5988/// Helper method to turn variable array types into constant array
5989/// types in certain situations which would otherwise be errors (for
5990/// GCC compatibility).
5991static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5992 ASTContext &Context,
5993 bool &SizeIsNegative,
5994 llvm::APSInt &Oversized) {
5995 // This method tries to turn a variable array into a constant
5996 // array even when the size isn't an ICE. This is necessary
5997 // for compatibility with code that depends on gcc's buggy
5998 // constant expression folding, like struct {char x[(int)(char*)2];}
5999 SizeIsNegative = false;
6000 Oversized = 0;
6001
6002 if (T->isDependentType())
6003 return QualType();
6004
6005 QualifierCollector Qs;
6006 const Type *Ty = Qs.strip(T);
6007
6008 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6009 QualType Pointee = PTy->getPointeeType();
6010 QualType FixedType =
6011 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6012 Oversized);
6013 if (FixedType.isNull()) return FixedType;
6014 FixedType = Context.getPointerType(FixedType);
6015 return Qs.apply(Context, FixedType);
6016 }
6017 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6018 QualType Inner = PTy->getInnerType();
6019 QualType FixedType =
6020 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6021 Oversized);
6022 if (FixedType.isNull()) return FixedType;
6023 FixedType = Context.getParenType(FixedType);
6024 return Qs.apply(Context, FixedType);
6025 }
6026
6027 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6028 if (!VLATy)
6029 return QualType();
6030
6031 QualType ElemTy = VLATy->getElementType();
6032 if (ElemTy->isVariablyModifiedType()) {
6033 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6034 SizeIsNegative, Oversized);
6035 if (ElemTy.isNull())
6036 return QualType();
6037 }
6038
6039 Expr::EvalResult Result;
6040 if (!VLATy->getSizeExpr() ||
6041 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6042 return QualType();
6043
6044 llvm::APSInt Res = Result.Val.getInt();
6045
6046 // Check whether the array size is negative.
6047 if (Res.isSigned() && Res.isNegative()) {
6048 SizeIsNegative = true;
6049 return QualType();
6050 }
6051
6052 // Check whether the array is too large to be addressed.
6053 unsigned ActiveSizeBits =
6054 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6055 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6056 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6057 : Res.getActiveBits();
6058 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6059 Oversized = Res;
6060 return QualType();
6061 }
6062
6063 QualType FoldedArrayType = Context.getConstantArrayType(
6064 ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
6065 return Qs.apply(Context, FoldedArrayType);
6066}
6067
6068static void
6069FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6070 SrcTL = SrcTL.getUnqualifiedLoc();
6071 DstTL = DstTL.getUnqualifiedLoc();
6072 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6073 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6074 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6075 DstPTL.getPointeeLoc());
6076 DstPTL.setStarLoc(SrcPTL.getStarLoc());
6077 return;
6078 }
6079 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6080 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6081 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6082 DstPTL.getInnerLoc());
6083 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6084 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6085 return;
6086 }
6087 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6088 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6089 TypeLoc SrcElemTL = SrcATL.getElementLoc();
6090 TypeLoc DstElemTL = DstATL.getElementLoc();
6091 if (VariableArrayTypeLoc SrcElemATL =
6092 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6093 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6094 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6095 } else {
6096 DstElemTL.initializeFullCopy(SrcElemTL);
6097 }
6098 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6099 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6100 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6101}
6102
6103/// Helper method to turn variable array types into constant array
6104/// types in certain situations which would otherwise be errors (for
6105/// GCC compatibility).
6106static TypeSourceInfo*
6107TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6108 ASTContext &Context,
6109 bool &SizeIsNegative,
6110 llvm::APSInt &Oversized) {
6111 QualType FixedTy
6112 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6113 SizeIsNegative, Oversized);
6114 if (FixedTy.isNull())
6115 return nullptr;
6116 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6117 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6118 FixedTInfo->getTypeLoc());
6119 return FixedTInfo;
6120}
6121
6122/// Attempt to fold a variable-sized type to a constant-sized type, returning
6123/// true if we were successful.
6124bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6125 QualType &T, SourceLocation Loc,
6126 unsigned FailedFoldDiagID) {
6127 bool SizeIsNegative;
6128 llvm::APSInt Oversized;
6129 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6130 TInfo, Context, SizeIsNegative, Oversized);
6131 if (FixedTInfo) {
6132 Diag(Loc, diag::ext_vla_folded_to_constant);
6133 TInfo = FixedTInfo;
6134 T = FixedTInfo->getType();
6135 return true;
6136 }
6137
6138 if (SizeIsNegative)
6139 Diag(Loc, diag::err_typecheck_negative_array_size);
6140 else if (Oversized.getBoolValue())
6141 Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6142 else if (FailedFoldDiagID)
6143 Diag(Loc, FailedFoldDiagID);
6144 return false;
6145}
6146
6147/// Register the given locally-scoped extern "C" declaration so
6148/// that it can be found later for redeclarations. We include any extern "C"
6149/// declaration that is not visible in the translation unit here, not just
6150/// function-scope declarations.
6151void
6152Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6153 if (!getLangOpts().CPlusPlus &&
6154 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6155 // Don't need to track declarations in the TU in C.
6156 return;
6157
6158 // Note that we have a locally-scoped external with this name.
6159 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6160}
6161
6162NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6163 // FIXME: We can have multiple results via __attribute__((overloadable)).
6164 auto Result = Context.getExternCContextDecl()->lookup(Name);
6165 return Result.empty() ? nullptr : *Result.begin();
6166}
6167
6168/// Diagnose function specifiers on a declaration of an identifier that
6169/// does not identify a function.
6170void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6171 // FIXME: We should probably indicate the identifier in question to avoid
6172 // confusion for constructs like "virtual int a(), b;"
6173 if (DS.isVirtualSpecified())
6174 Diag(DS.getVirtualSpecLoc(),
6175 diag::err_virtual_non_function);
6176
6177 if (DS.hasExplicitSpecifier())
6178 Diag(DS.getExplicitSpecLoc(),
6179 diag::err_explicit_non_function);
6180
6181 if (DS.isNoreturnSpecified())
6182 Diag(DS.getNoreturnSpecLoc(),
6183 diag::err_noreturn_non_function);
6184}
6185
6186NamedDecl*
6187Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6188 TypeSourceInfo *TInfo, LookupResult &Previous) {
6189 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6190 if (D.getCXXScopeSpec().isSet()) {
6191 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6192 << D.getCXXScopeSpec().getRange();
6193 D.setInvalidType();
6194 // Pretend we didn't see the scope specifier.
6195 DC = CurContext;
6196 Previous.clear();
6197 }
6198
6199 DiagnoseFunctionSpecifiers(D.getDeclSpec());
6200
6201 if (D.getDeclSpec().isInlineSpecified())
6202 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6203 << getLangOpts().CPlusPlus17;
6204 if (D.getDeclSpec().hasConstexprSpecifier())
6205 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6206 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6207
6208 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
6209 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
6210 Diag(D.getName().StartLocation,
6211 diag::err_deduction_guide_invalid_specifier)
6212 << "typedef";
6213 else
6214 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6215 << D.getName().getSourceRange();
6216 return nullptr;
6217 }
6218
6219 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6220 if (!NewTD) return nullptr;
6221
6222 // Handle attributes prior to checking for duplicates in MergeVarDecl
6223 ProcessDeclAttributes(S, NewTD, D);
6224
6225 CheckTypedefForVariablyModifiedType(S, NewTD);
6226
6227 bool Redeclaration = D.isRedeclaration();
6228 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6229 D.setRedeclaration(Redeclaration);
6230 return ND;
6231}
6232
6233void
6234Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6235 // C99 6.7.7p2: If a typedef name specifies a variably modified type
6236 // then it shall have block scope.
6237 // Note that variably modified types must be fixed before merging the decl so
6238 // that redeclarations will match.
6239 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6240 QualType T = TInfo->getType();
6241 if (T->isVariablyModifiedType()) {
6242 setFunctionHasBranchProtectedScope();
6243
6244 if (S->getFnParent() == nullptr) {
6245 bool SizeIsNegative;
6246 llvm::APSInt Oversized;
6247 TypeSourceInfo *FixedTInfo =
6248 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6249 SizeIsNegative,
6250 Oversized);
6251 if (FixedTInfo) {
6252 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6253 NewTD->setTypeSourceInfo(FixedTInfo);
6254 } else {
6255 if (SizeIsNegative)
6256 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6257 else if (T->isVariableArrayType())
6258 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6259 else if (Oversized.getBoolValue())
6260 Diag(NewTD->getLocation(), diag::err_array_too_large)
6261 << toString(Oversized, 10);
6262 else
6263 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6264 NewTD->setInvalidDecl();
6265 }
6266 }
6267 }
6268}
6269
6270/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6271/// declares a typedef-name, either using the 'typedef' type specifier or via
6272/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6273NamedDecl*
6274Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6275 LookupResult &Previous, bool &Redeclaration) {
6276
6277 // Find the shadowed declaration before filtering for scope.
6278 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6279
6280 // Merge the decl with the existing one if appropriate. If the decl is
6281 // in an outer scope, it isn't the same thing.
6282 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6283 /*AllowInlineNamespace*/false);
6284 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6285 if (!Previous.empty()) {
6286 Redeclaration = true;
6287 MergeTypedefNameDecl(S, NewTD, Previous);
6288 } else {
6289 inferGslPointerAttribute(NewTD);
6290 }
6291
6292 if (ShadowedDecl && !Redeclaration)
6293 CheckShadow(NewTD, ShadowedDecl, Previous);
6294
6295 // If this is the C FILE type, notify the AST context.
6296 if (IdentifierInfo *II = NewTD->getIdentifier())
6297 if (!NewTD->isInvalidDecl() &&
6298 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6299 if (II->isStr("FILE"))
6300 Context.setFILEDecl(NewTD);
6301 else if (II->isStr("jmp_buf"))
6302 Context.setjmp_bufDecl(NewTD);
6303 else if (II->isStr("sigjmp_buf"))
6304 Context.setsigjmp_bufDecl(NewTD);
6305 else if (II->isStr("ucontext_t"))
6306 Context.setucontext_tDecl(NewTD);
6307 }
6308
6309 return NewTD;
6310}
6311
6312/// Determines whether the given declaration is an out-of-scope
6313/// previous declaration.
6314///
6315/// This routine should be invoked when name lookup has found a
6316/// previous declaration (PrevDecl) that is not in the scope where a
6317/// new declaration by the same name is being introduced. If the new
6318/// declaration occurs in a local scope, previous declarations with
6319/// linkage may still be considered previous declarations (C99
6320/// 6.2.2p4-5, C++ [basic.link]p6).
6321///
6322/// \param PrevDecl the previous declaration found by name
6323/// lookup
6324///
6325/// \param DC the context in which the new declaration is being
6326/// declared.
6327///
6328/// \returns true if PrevDecl is an out-of-scope previous declaration
6329/// for a new delcaration with the same name.
6330static bool
6331isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6332 ASTContext &Context) {
6333 if (!PrevDecl)
6334 return false;
6335
6336 if (!PrevDecl->hasLinkage())
6337 return false;
6338
6339 if (Context.getLangOpts().CPlusPlus) {
6340 // C++ [basic.link]p6:
6341 // If there is a visible declaration of an entity with linkage
6342 // having the same name and type, ignoring entities declared
6343 // outside the innermost enclosing namespace scope, the block
6344 // scope declaration declares that same entity and receives the
6345 // linkage of the previous declaration.
6346 DeclContext *OuterContext = DC->getRedeclContext();
6347 if (!OuterContext->isFunctionOrMethod())
6348 // This rule only applies to block-scope declarations.
6349 return false;
6350
6351 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6352 if (PrevOuterContext->isRecord())
6353 // We found a member function: ignore it.
6354 return false;
6355
6356 // Find the innermost enclosing namespace for the new and
6357 // previous declarations.
6358 OuterContext = OuterContext->getEnclosingNamespaceContext();
6359 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6360
6361 // The previous declaration is in a different namespace, so it
6362 // isn't the same function.
6363 if (!OuterContext->Equals(PrevOuterContext))
6364 return false;
6365 }
6366
6367 return true;
6368}
6369
6370static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6371 CXXScopeSpec &SS = D.getCXXScopeSpec();
6372 if (!SS.isSet()) return;
6373 DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6374}
6375
6376bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6377 QualType type = decl->getType();
6378 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6379 if (lifetime == Qualifiers::OCL_Autoreleasing) {
6380 // Various kinds of declaration aren't allowed to be __autoreleasing.
6381 unsigned kind = -1U;
6382 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6383 if (var->hasAttr<BlocksAttr>())
6384 kind = 0; // __block
6385 else if (!var->hasLocalStorage())
6386 kind = 1; // global
6387 } else if (isa<ObjCIvarDecl>(decl)) {
6388 kind = 3; // ivar
6389 } else if (isa<FieldDecl>(decl)) {
6390 kind = 2; // field
6391 }
6392
6393 if (kind != -1U) {
6394 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6395 << kind;
6396 }
6397 } else if (lifetime == Qualifiers::OCL_None) {
6398 // Try to infer lifetime.
6399 if (!type->isObjCLifetimeType())
6400 return false;
6401
6402 lifetime = type->getObjCARCImplicitLifetime();
6403 type = Context.getLifetimeQualifiedType(type, lifetime);
6404 decl->setType(type);
6405 }
6406
6407 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6408 // Thread-local variables cannot have lifetime.
6409 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6410 var->getTLSKind()) {
6411 Diag(var->getLocation(), diag::err_arc_thread_ownership)
6412 << var->getType();
6413 return true;
6414 }
6415 }
6416
6417 return false;
6418}
6419
6420void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6421 if (Decl->getType().hasAddressSpace())
6422 return;
6423 if (Decl->getType()->isDependentType())
6424 return;
6425 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6426 QualType Type = Var->getType();
6427 if (Type->isSamplerT() || Type->isVoidType())
6428 return;
6429 LangAS ImplAS = LangAS::opencl_private;
6430 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
6431 // __opencl_c_program_scope_global_variables feature, the address space
6432 // for a variable at program scope or a static or extern variable inside
6433 // a function are inferred to be __global.
6434 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
6435 Var->hasGlobalStorage())
6436 ImplAS = LangAS::opencl_global;
6437 // If the original type from a decayed type is an array type and that array
6438 // type has no address space yet, deduce it now.
6439 if (auto DT = dyn_cast<DecayedType>(Type)) {
6440 auto OrigTy = DT->getOriginalType();
6441 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6442 // Add the address space to the original array type and then propagate
6443 // that to the element type through `getAsArrayType`.
6444 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6445 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6446 // Re-generate the decayed type.
6447 Type = Context.getDecayedType(OrigTy);
6448 }
6449 }
6450 Type = Context.getAddrSpaceQualType(Type, ImplAS);
6451 // Apply any qualifiers (including address space) from the array type to
6452 // the element type. This implements C99 6.7.3p8: "If the specification of
6453 // an array type includes any type qualifiers, the element type is so
6454 // qualified, not the array type."
6455 if (Type->isArrayType())
6456 Type = QualType(Context.getAsArrayType(Type), 0);
6457 Decl->setType(Type);
6458 }
6459}
6460
6461static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6462 // Ensure that an auto decl is deduced otherwise the checks below might cache
6463 // the wrong linkage.
6464 assert(S.ParsingInitForAutoVars.count(&ND) == 0)(static_cast <bool> (S.ParsingInitForAutoVars.count(&
ND) == 0) ? void (0) : __assert_fail ("S.ParsingInitForAutoVars.count(&ND) == 0"
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 6464, __extension__ __PRETTY_FUNCTION__))
;
6465
6466 // 'weak' only applies to declarations with external linkage.
6467 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6468 if (!ND.isExternallyVisible()) {
6469 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6470 ND.dropAttr<WeakAttr>();
6471 }
6472 }
6473 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6474 if (ND.isExternallyVisible()) {
6475 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6476 ND.dropAttr<WeakRefAttr>();
6477 ND.dropAttr<AliasAttr>();
6478 }
6479 }
6480
6481 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6482 if (VD->hasInit()) {
6483 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6484 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!\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 6485, __extension__ __PRETTY_FUNCTION__))
6485 !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!\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 6485, __extension__ __PRETTY_FUNCTION__))
;
6486 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6487 VD->dropAttr<AliasAttr>();
6488 }
6489 }
6490 }
6491
6492 // 'selectany' only applies to externally visible variable declarations.
6493 // It does not apply to functions.
6494 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6495 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6496 S.Diag(Attr->getLocation(),
6497 diag::err_attribute_selectany_non_extern_data);
6498 ND.dropAttr<SelectAnyAttr>();
6499 }
6500 }
6501
6502 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6503 auto *VD = dyn_cast<VarDecl>(&ND);
6504 bool IsAnonymousNS = false;
6505 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6506 if (VD) {
6507 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6508 while (NS && !IsAnonymousNS) {
6509 IsAnonymousNS = NS->isAnonymousNamespace();
6510 NS = dyn_cast<NamespaceDecl>(NS->getParent());
6511 }
6512 }
6513 // dll attributes require external linkage. Static locals may have external
6514 // linkage but still cannot be explicitly imported or exported.
6515 // In Microsoft mode, a variable defined in anonymous namespace must have
6516 // external linkage in order to be exported.
6517 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6518 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6519 (!AnonNSInMicrosoftMode &&
6520 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6521 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6522 << &ND << Attr;
6523 ND.setInvalidDecl();
6524 }
6525 }
6526
6527 // Check the attributes on the function type, if any.
6528 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6529 // Don't declare this variable in the second operand of the for-statement;
6530 // GCC miscompiles that by ending its lifetime before evaluating the
6531 // third operand. See gcc.gnu.org/PR86769.
6532 AttributedTypeLoc ATL;
6533 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6534 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6535 TL = ATL.getModifiedLoc()) {
6536 // The [[lifetimebound]] attribute can be applied to the implicit object
6537 // parameter of a non-static member function (other than a ctor or dtor)
6538 // by applying it to the function type.
6539 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6540 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6541 if (!MD || MD->isStatic()) {
6542 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6543 << !MD << A->getRange();
6544 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6545 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6546 << isa<CXXDestructorDecl>(MD) << A->getRange();
6547 }
6548 }
6549 }
6550 }
6551}
6552
6553static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6554 NamedDecl *NewDecl,
6555 bool IsSpecialization,
6556 bool IsDefinition) {
6557 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6558 return;
6559
6560 bool IsTemplate = false;
6561 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6562 OldDecl = OldTD->getTemplatedDecl();
6563 IsTemplate = true;
6564 if (!IsSpecialization)
6565 IsDefinition = false;
6566 }
6567 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6568 NewDecl = NewTD->getTemplatedDecl();
6569 IsTemplate = true;
6570 }
6571
6572 if (!OldDecl || !NewDecl)
6573 return;
6574
6575 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6576 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6577 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6578 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6579
6580 // dllimport and dllexport are inheritable attributes so we have to exclude
6581 // inherited attribute instances.
6582 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6583 (NewExportAttr && !NewExportAttr->isInherited());
6584
6585 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6586 // the only exception being explicit specializations.
6587 // Implicitly generated declarations are also excluded for now because there
6588 // is no other way to switch these to use dllimport or dllexport.
6589 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6590
6591 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6592 // Allow with a warning for free functions and global variables.
6593 bool JustWarn = false;
6594 if (!OldDecl->isCXXClassMember()) {
6595 auto *VD = dyn_cast<VarDecl>(OldDecl);
6596 if (VD && !VD->getDescribedVarTemplate())
6597 JustWarn = true;
6598 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6599 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6600 JustWarn = true;
6601 }
6602
6603 // We cannot change a declaration that's been used because IR has already
6604 // been emitted. Dllimported functions will still work though (modulo
6605 // address equality) as they can use the thunk.
6606 if (OldDecl->isUsed())
6607 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6608 JustWarn = false;
6609
6610 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6611 : diag::err_attribute_dll_redeclaration;
6612 S.Diag(NewDecl->getLocation(), DiagID)
6613 << NewDecl
6614 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6615 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6616 if (!JustWarn) {
6617 NewDecl->setInvalidDecl();
6618 return;
6619 }
6620 }
6621
6622 // A redeclaration is not allowed to drop a dllimport attribute, the only
6623 // exceptions being inline function definitions (except for function
6624 // templates), local extern declarations, qualified friend declarations or
6625 // special MSVC extension: in the last case, the declaration is treated as if
6626 // it were marked dllexport.
6627 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6628 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
6629 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6630 // Ignore static data because out-of-line definitions are diagnosed
6631 // separately.
6632 IsStaticDataMember = VD->isStaticDataMember();
6633 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6634 VarDecl::DeclarationOnly;
6635 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6636 IsInline = FD->isInlined();
6637 IsQualifiedFriend = FD->getQualifier() &&
6638 FD->getFriendObjectKind() == Decl::FOK_Declared;
6639 }
6640
6641 if (OldImportAttr && !HasNewAttr &&
6642 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
6643 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6644 if (IsMicrosoftABI && IsDefinition) {
6645 S.Diag(NewDecl->getLocation(),
6646 diag::warn_redeclaration_without_import_attribute)
6647 << NewDecl;
6648 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6649 NewDecl->dropAttr<DLLImportAttr>();
6650 NewDecl->addAttr(
6651 DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6652 } else {
6653 S.Diag(NewDecl->getLocation(),
6654 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6655 << NewDecl << OldImportAttr;
6656 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6657 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6658 OldDecl->dropAttr<DLLImportAttr>();
6659 NewDecl->dropAttr<DLLImportAttr>();
6660 }
6661 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
6662 // In MinGW, seeing a function declared inline drops the dllimport
6663 // attribute.
6664 OldDecl->dropAttr<DLLImportAttr>();
6665 NewDecl->dropAttr<DLLImportAttr>();
6666 S.Diag(NewDecl->getLocation(),
6667 diag::warn_dllimport_dropped_from_inline_function)
6668 << NewDecl << OldImportAttr;
6669 }
6670
6671 // A specialization of a class template member function is processed here
6672 // since it's a redeclaration. If the parent class is dllexport, the
6673 // specialization inherits that attribute. This doesn't happen automatically
6674 // since the parent class isn't instantiated until later.
6675 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6676 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6677 !NewImportAttr && !NewExportAttr) {
6678 if (const DLLExportAttr *ParentExportAttr =
6679 MD->getParent()->getAttr<DLLExportAttr>()) {
6680 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6681 NewAttr->setInherited(true);
6682 NewDecl->addAttr(NewAttr);
6683 }
6684 }
6685 }
6686}
6687
6688/// Given that we are within the definition of the given function,
6689/// will that definition behave like C99's 'inline', where the
6690/// definition is discarded except for optimization purposes?
6691static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6692 // Try to avoid calling GetGVALinkageForFunction.
6693
6694 // All cases of this require the 'inline' keyword.
6695 if (!FD->isInlined()) return false;
6696
6697 // This is only possible in C++ with the gnu_inline attribute.
6698 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6699 return false;
6700
6701 // Okay, go ahead and call the relatively-more-expensive function.
6702 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6703}
6704
6705/// Determine whether a variable is extern "C" prior to attaching
6706/// an initializer. We can't just call isExternC() here, because that
6707/// will also compute and cache whether the declaration is externally
6708/// visible, which might change when we attach the initializer.
6709///
6710/// This can only be used if the declaration is known to not be a
6711/// redeclaration of an internal linkage declaration.
6712///
6713/// For instance:
6714///
6715/// auto x = []{};
6716///
6717/// Attaching the initializer here makes this declaration not externally
6718/// visible, because its type has internal linkage.
6719///
6720/// FIXME: This is a hack.
6721template<typename T>
6722static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6723 if (S.getLangOpts().CPlusPlus) {
6724 // In C++, the overloadable attribute negates the effects of extern "C".
6725 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6726 return false;
6727
6728 // So do CUDA's host/device attributes.
6729 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6730 D->template hasAttr<CUDAHostAttr>()))
6731 return false;
6732 }
6733 return D->isExternC();
6734}
6735
6736static bool shouldConsiderLinkage(const VarDecl *VD) {
6737 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6738 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6739 isa<OMPDeclareMapperDecl>(DC))
6740 return VD->hasExternalStorage();
6741 if (DC->isFileContext())
6742 return true;
6743 if (DC->isRecord())
6744 return false;
6745 if (isa<RequiresExprBodyDecl>(DC))
6746 return false;
6747 llvm_unreachable("Unexpected context")::llvm::llvm_unreachable_internal("Unexpected context", "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 6747)
;
6748}
6749
6750static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6751 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6752 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6753 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6754 return true;
6755 if (DC->isRecord())
6756 return false;
6757 llvm_unreachable("Unexpected context")::llvm::llvm_unreachable_internal("Unexpected context", "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 6757)
;
6758}
6759
6760static bool hasParsedAttr(Scope *S, const Declarator &PD,
6761 ParsedAttr::Kind Kind) {
6762 // Check decl attributes on the DeclSpec.
6763 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6764 return true;
6765
6766 // Walk the declarator structure, checking decl attributes that were in a type
6767 // position to the decl itself.
6768 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6769 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6770 return true;
6771 }
6772
6773 // Finally, check attributes on the decl itself.
6774 return PD.getAttributes().hasAttribute(Kind);
6775}
6776
6777/// Adjust the \c DeclContext for a function or variable that might be a
6778/// function-local external declaration.
6779bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6780 if (!DC->isFunctionOrMethod())
6781 return false;
6782
6783 // If this is a local extern function or variable declared within a function
6784 // template, don't add it into the enclosing namespace scope until it is
6785 // instantiated; it might have a dependent type right now.
6786 if (DC->isDependentContext())
6787 return true;
6788
6789 // C++11 [basic.link]p7:
6790 // When a block scope declaration of an entity with linkage is not found to
6791 // refer to some other declaration, then that entity is a member of the
6792 // innermost enclosing namespace.
6793 //
6794 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6795 // semantically-enclosing namespace, not a lexically-enclosing one.
6796 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6797 DC = DC->getParent();
6798 return true;
6799}
6800
6801/// Returns true if given declaration has external C language linkage.
6802static bool isDeclExternC(const Decl *D) {
6803 if (const auto *FD = dyn_cast<FunctionDecl>(D))
6804 return FD->isExternC();
6805 if (const auto *VD = dyn_cast<VarDecl>(D))
6806 return VD->isExternC();
6807
6808 llvm_unreachable("Unknown type of decl!")::llvm::llvm_unreachable_internal("Unknown type of decl!", "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 6808)
;
6809}
6810
6811/// Returns true if there hasn't been any invalid type diagnosed.
6812static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
6813 DeclContext *DC = NewVD->getDeclContext();
6814 QualType R = NewVD->getType();
6815
6816 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6817 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6818 // argument.
6819 if (R->isImageType() || R->isPipeType()) {
6820 Se.Diag(NewVD->getLocation(),
6821 diag::err_opencl_type_can_only_be_used_as_function_parameter)
6822 << R;
6823 NewVD->setInvalidDecl();
6824 return false;
6825 }
6826
6827 // OpenCL v1.2 s6.9.r:
6828 // The event type cannot be used to declare a program scope variable.
6829 // OpenCL v2.0 s6.9.q:
6830 // The clk_event_t and reserve_id_t types cannot be declared in program
6831 // scope.
6832 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
6833 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6834 Se.Diag(NewVD->getLocation(),
6835 diag::err_invalid_type_for_program_scope_var)
6836 << R;
6837 NewVD->setInvalidDecl();
6838 return false;
6839 }
6840 }
6841
6842 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6843 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
6844 Se.getLangOpts())) {
6845 QualType NR = R.getCanonicalType();
6846 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
6847 NR->isReferenceType()) {
6848 if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
6849 NR->isFunctionReferenceType()) {
6850 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
6851 << NR->isReferenceType();
6852 NewVD->setInvalidDecl();
6853 return false;
6854 }
6855 NR = NR->getPointeeType();
6856 }
6857 }
6858
6859 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
6860 Se.getLangOpts())) {
6861 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6862 // half array type (unless the cl_khr_fp16 extension is enabled).
6863 if (Se.Context.getBaseElementType(R)->isHalfType()) {
6864 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
6865 NewVD->setInvalidDecl();
6866 return false;
6867 }
6868 }
6869
6870 // OpenCL v1.2 s6.9.r:
6871 // The event type cannot be used with the __local, __constant and __global
6872 // address space qualifiers.
6873 if (R->isEventT()) {
6874 if (R.getAddressSpace() != LangAS::opencl_private) {
6875 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
6876 NewVD->setInvalidDecl();
6877 return false;
6878 }
6879 }
6880
6881 if (R->isSamplerT()) {
6882 // OpenCL v1.2 s6.9.b p4:
6883 // The sampler type cannot be used with the __local and __global address
6884 // space qualifiers.
6885 if (R.getAddressSpace() == LangAS::opencl_local ||
6886 R.getAddressSpace() == LangAS::opencl_global) {
6887 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
6888 NewVD->setInvalidDecl();
6889 }
6890
6891 // OpenCL v1.2 s6.12.14.1:
6892 // A global sampler must be declared with either the constant address
6893 // space qualifier or with the const qualifier.
6894 if (DC->isTranslationUnit() &&
6895 !(R.getAddressSpace() == LangAS::opencl_constant ||
6896 R.isConstQualified())) {
6897 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
6898 NewVD->setInvalidDecl();
6899 }
6900 if (NewVD->isInvalidDecl())
6901 return false;
6902 }
6903
6904 return true;
6905}
6906
6907template <typename AttrTy>
6908static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
6909 const TypedefNameDecl *TND = TT->getDecl();
6910 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
6911 AttrTy *Clone = Attribute->clone(S.Context);
6912 Clone->setInherited(true);
6913 D->addAttr(Clone);
6914 }
6915}
6916
6917NamedDecl *Sema::ActOnVariableDeclarator(
6918 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6919 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6920 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6921 QualType R = TInfo->getType();
6922 DeclarationName Name = GetNameForDeclarator(D).getName();
6923
6924 IdentifierInfo *II = Name.getAsIdentifierInfo();
6925
6926 if (D.isDecompositionDeclarator()) {
6927 // Take the name of the first declarator as our name for diagnostic
6928 // purposes.
6929 auto &Decomp = D.getDecompositionDeclarator();
6930 if (!Decomp.bindings().empty()) {
6931 II = Decomp.bindings()[0].Name;
6932 Name = II;
6933 }
6934 } else if (!II) {
6935 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6936 return nullptr;
6937 }
6938
6939
6940 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6941 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6942
6943 // dllimport globals without explicit storage class are treated as extern. We
6944 // have to change the storage class this early to get the right DeclContext.
6945 if (SC == SC_None && !DC->isRecord() &&
6946 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6947 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6948 SC = SC_Extern;
6949
6950 DeclContext *OriginalDC = DC;
6951 bool IsLocalExternDecl = SC == SC_Extern &&
6952 adjustContextForLocalExternDecl(DC);
6953
6954 if (SCSpec == DeclSpec::SCS_mutable) {
6955 // mutable can only appear on non-static class members, so it's always
6956 // an error here
6957 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6958 D.setInvalidType();
6959 SC = SC_None;
6960 }
6961
6962 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6963 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6964 D.getDeclSpec().getStorageClassSpecLoc())) {
6965 // In C++11, the 'register' storage class specifier is deprecated.
6966 // Suppress the warning in system macros, it's used in macros in some
6967 // popular C system headers, such as in glibc's htonl() macro.
6968 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6969 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6970 : diag::warn_deprecated_register)
6971 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6972 }
6973
6974 DiagnoseFunctionSpecifiers(D.getDeclSpec());
6975
6976 if (!DC->isRecord() && S->getFnParent() == nullptr) {
6977 // C99 6.9p2: The storage-class specifiers auto and register shall not
6978 // appear in the declaration specifiers in an external declaration.
6979 // Global Register+Asm is a GNU extension we support.
6980 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6981 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6982 D.setInvalidType();
6983 }
6984 }
6985
6986 // If this variable has a VLA type and an initializer, try to
6987 // fold to a constant-sized type. This is otherwise invalid.
6988 if (D.hasInitializer() && R->isVariableArrayType())
6989 tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
6990 /*DiagID=*/0);
6991
6992 bool IsMemberSpecialization = false;
6993 bool IsVariableTemplateSpecialization = false;
6994 bool IsPartialSpecialization = false;
6995 bool IsVariableTemplate = false;
6996 VarDecl *NewVD = nullptr;
6997 VarTemplateDecl *NewTemplate = nullptr;
6998 TemplateParameterList *TemplateParams = nullptr;
6999 if (!getLangOpts().CPlusPlus) {
7000 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
7001 II, R, TInfo, SC);
7002
7003 if (R->getContainedDeducedType())
7004 ParsingInitForAutoVars.insert(NewVD);
7005
7006 if (D.isInvalidType())
7007 NewVD->setInvalidDecl();
7008
7009 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7010 NewVD->hasLocalStorage())
7011 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7012 NTCUC_AutoVar, NTCUK_Destruct);
7013 } else {
7014 bool Invalid = false;
7015
7016 if (DC->isRecord() && !CurContext->isRecord()) {
7017 // This is an out-of-line definition of a static data member.
7018 switch (SC) {
7019 case SC_None:
7020 break;
7021 case SC_Static:
7022 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7023 diag::err_static_out_of_line)
7024 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7025 break;
7026 case SC_Auto:
7027 case SC_Register:
7028 case SC_Extern:
7029 // [dcl.stc] p2: The auto or register specifiers shall be applied only
7030 // to names of variables declared in a block or to function parameters.
7031 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7032 // of class members
7033
7034 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7035 diag::err_storage_class_for_static_member)
7036 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7037 break;
7038 case SC_PrivateExtern:
7039 llvm_unreachable("C storage class in c++!")::llvm::llvm_unreachable_internal("C storage class in c++!", "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 7039)
;
7040 }
7041 }
7042
7043 if (SC == SC_Static && CurContext->isRecord()) {
7044 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7045 // Walk up the enclosing DeclContexts to check for any that are
7046 // incompatible with static data members.
7047 const DeclContext *FunctionOrMethod = nullptr;
7048 const CXXRecordDecl *AnonStruct = nullptr;
7049 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7050 if (Ctxt->isFunctionOrMethod()) {
7051 FunctionOrMethod = Ctxt;
7052 break;
7053 }
7054 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7055 if (ParentDecl && !ParentDecl->getDeclName()) {
7056 AnonStruct = ParentDecl;
7057 break;
7058 }
7059 }
7060 if (FunctionOrMethod) {
7061 // C++ [class.static.data]p5: A local class shall not have static data
7062 // members.
7063 Diag(D.getIdentifierLoc(),
7064 diag::err_static_data_member_not_allowed_in_local_class)
7065 << Name << RD->getDeclName() << RD->getTagKind();
7066 } else if (AnonStruct) {
7067 // C++ [class.static.data]p4: Unnamed classes and classes contained
7068 // directly or indirectly within unnamed classes shall not contain
7069 // static data members.
7070 Diag(D.getIdentifierLoc(),
7071 diag::err_static_data_member_not_allowed_in_anon_struct)
7072 << Name << AnonStruct->getTagKind();
7073 Invalid = true;
7074 } else if (RD->isUnion()) {
7075 // C++98 [class.union]p1: If a union contains a static data member,
7076 // the program is ill-formed. C++11 drops this restriction.
7077 Diag(D.getIdentifierLoc(),
7078 getLangOpts().CPlusPlus11
7079 ? diag::warn_cxx98_compat_static_data_member_in_union
7080 : diag::ext_static_data_member_in_union) << Name;
7081 }
7082 }
7083 }
7084
7085 // Match up the template parameter lists with the scope specifier, then
7086 // determine whether we have a template or a template specialization.
7087 bool InvalidScope = false;
7088 TemplateParams = MatchTemplateParametersToScopeSpecifier(
7089 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7090 D.getCXXScopeSpec(),
7091 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7092 ? D.getName().TemplateId
7093 : nullptr,
7094 TemplateParamLists,
7095 /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
7096 Invalid |= InvalidScope;
7097
7098 if (TemplateParams) {
7099 if (!TemplateParams->size() &&
7100 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7101 // There is an extraneous 'template<>' for this variable. Complain
7102 // about it, but allow the declaration of the variable.
7103 Diag(TemplateParams->getTemplateLoc(),
7104 diag::err_template_variable_noparams)
7105 << II
7106 << SourceRange(TemplateParams->getTemplateLoc(),
7107 TemplateParams->getRAngleLoc());
7108 TemplateParams = nullptr;
7109 } else {
7110 // Check that we can declare a template here.
7111 if (CheckTemplateDeclScope(S, TemplateParams))
7112 return nullptr;
7113
7114 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7115 // This is an explicit specialization or a partial specialization.
7116 IsVariableTemplateSpecialization = true;
7117 IsPartialSpecialization = TemplateParams->size() > 0;
7118 } else { // if (TemplateParams->size() > 0)
7119 // This is a template declaration.
7120 IsVariableTemplate = true;
7121
7122 // Only C++1y supports variable templates (N3651).
7123 Diag(D.getIdentifierLoc(),
7124 getLangOpts().CPlusPlus14
7125 ? diag::warn_cxx11_compat_variable_template
7126 : diag::ext_variable_template);
7127 }
7128 }
7129 } else {
7130 // Check that we can declare a member specialization here.
7131 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7132 CheckTemplateDeclScope(S, TemplateParamLists.back()))
7133 return nullptr;
7134 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 7136, __extension__ __PRETTY_FUNCTION__))
7135 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 7136, __extension__ __PRETTY_FUNCTION__))
7136 "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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 7136, __extension__ __PRETTY_FUNCTION__))
;
7137 }
7138
7139 if (IsVariableTemplateSpecialization) {
7140 SourceLocation TemplateKWLoc =
7141 TemplateParamLists.size() > 0
7142 ? TemplateParamLists[0]->getTemplateLoc()
7143 : SourceLocation();
7144 DeclResult Res = ActOnVarTemplateSpecialization(
7145 S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7146 IsPartialSpecialization);
7147 if (Res.isInvalid())
7148 return nullptr;
7149 NewVD = cast<VarDecl>(Res.get());
7150 AddToScope = false;
7151 } else if (D.isDecompositionDeclarator()) {
7152 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7153 D.getIdentifierLoc(), R, TInfo, SC,
7154 Bindings);
7155 } else
7156 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7157 D.getIdentifierLoc(), II, R, TInfo, SC);
7158
7159 // If this is supposed to be a variable template, create it as such.
7160 if (IsVariableTemplate) {
7161 NewTemplate =
7162 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7163 TemplateParams, NewVD);
7164 NewVD->setDescribedVarTemplate(NewTemplate);
7165 }
7166
7167 // If this decl has an auto type in need of deduction, make a note of the
7168 // Decl so we can diagnose uses of it in its own initializer.
7169 if (R->getContainedDeducedType())
7170 ParsingInitForAutoVars.insert(NewVD);
7171
7172 if (D.isInvalidType() || Invalid) {
7173 NewVD->setInvalidDecl();
7174 if (NewTemplate)
7175 NewTemplate->setInvalidDecl();
7176 }
7177
7178 SetNestedNameSpecifier(*this, NewVD, D);
7179
7180 // If we have any template parameter lists that don't directly belong to
7181 // the variable (matching the scope specifier), store them.
7182 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7183 if (TemplateParamLists.size() > VDTemplateParamLists)
7184 NewVD->setTemplateParameterListsInfo(
7185 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7186 }
7187
7188 if (D.getDeclSpec().isInlineSpecified()) {
7189 if (!getLangOpts().CPlusPlus) {
7190 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7191 << 0;
7192 } else if (CurContext->isFunctionOrMethod()) {
7193 // 'inline' is not allowed on block scope variable declaration.
7194 Diag(D.getDeclSpec().getInlineSpecLoc(),
7195 diag::err_inline_declaration_block_scope) << Name
7196 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7197 } else {
7198 Diag(D.getDeclSpec().getInlineSpecLoc(),
7199 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7200 : diag::ext_inline_variable);
7201 NewVD->setInlineSpecified();
7202 }
7203 }
7204
7205 // Set the lexical context. If the declarator has a C++ scope specifier, the
7206 // lexical context will be different from the semantic context.
7207 NewVD->setLexicalDeclContext(CurContext);
7208 if (NewTemplate)
7209 NewTemplate->setLexicalDeclContext(CurContext);
7210
7211 if (IsLocalExternDecl) {
7212 if (D.isDecompositionDeclarator())
7213 for (auto *B : Bindings)
7214 B->setLocalExternDecl();
7215 else
7216 NewVD->setLocalExternDecl();
7217 }
7218
7219 bool EmitTLSUnsupportedError = false;
7220 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7221 // C++11 [dcl.stc]p4:
7222 // When thread_local is applied to a variable of block scope the
7223 // storage-class-specifier static is implied if it does not appear
7224 // explicitly.
7225 // Core issue: 'static' is not implied if the variable is declared
7226 // 'extern'.
7227 if (NewVD->hasLocalStorage() &&
7228 (SCSpec != DeclSpec::SCS_unspecified ||
7229 TSCS != DeclSpec::TSCS_thread_local ||
7230 !DC->isFunctionOrMethod()))
7231 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7232 diag::err_thread_non_global)
7233 << DeclSpec::getSpecifierName(TSCS);
7234 else if (!Context.getTargetInfo().isTLSSupported()) {
7235 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7236 getLangOpts().SYCLIsDevice) {
7237 // Postpone error emission until we've collected attributes required to
7238 // figure out whether it's a host or device variable and whether the
7239 // error should be ignored.
7240 EmitTLSUnsupportedError = true;
7241 // We still need to mark the variable as TLS so it shows up in AST with
7242 // proper storage class for other tools to use even if we're not going
7243 // to emit any code for it.
7244 NewVD->setTSCSpec(TSCS);
7245 } else
7246 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7247 diag::err_thread_unsupported);
7248 } else
7249 NewVD->setTSCSpec(TSCS);
7250 }
7251
7252 switch (D.getDeclSpec().getConstexprSpecifier()) {
7253 case ConstexprSpecKind::Unspecified:
7254 break;
7255
7256 case ConstexprSpecKind::Consteval:
7257 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7258 diag::err_constexpr_wrong_decl_kind)
7259 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7260 LLVM_FALLTHROUGH[[gnu::fallthrough]];
7261
7262 case ConstexprSpecKind::Constexpr:
7263 NewVD->setConstexpr(true);
7264 // C++1z [dcl.spec.constexpr]p1:
7265 // A static data member declared with the constexpr specifier is
7266 // implicitly an inline variable.
7267 if (NewVD->isStaticDataMember() &&
7268 (getLangOpts().CPlusPlus17 ||
7269 Context.getTargetInfo().getCXXABI().isMicrosoft()))
7270 NewVD->setImplicitlyInline();
7271 break;
7272
7273 case ConstexprSpecKind::Constinit:
7274 if (!NewVD->hasGlobalStorage())
7275 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7276 diag::err_constinit_local_variable);
7277 else
7278 NewVD->addAttr(ConstInitAttr::Create(
7279 Context, D.getDeclSpec().getConstexprSpecLoc(),
7280 AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7281 break;
7282 }
7283
7284 // C99 6.7.4p3
7285 // An inline definition of a function with external linkage shall
7286 // not contain a definition of a modifiable object with static or
7287 // thread storage duration...
7288 // We only apply this when the function is required to be defined
7289 // elsewhere, i.e. when the function is not 'extern inline'. Note
7290 // that a local variable with thread storage duration still has to
7291 // be marked 'static'. Also note that it's possible to get these
7292 // semantics in C++ using __attribute__((gnu_inline)).
7293 if (SC == SC_Static && S->getFnParent() != nullptr &&
7294 !NewVD->getType().isConstQualified()) {
7295 FunctionDecl *CurFD = getCurFunctionDecl();
7296 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7297 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7298 diag::warn_static_local_in_extern_inline);
7299 MaybeSuggestAddingStaticToDecl(CurFD);
7300 }
7301 }
7302
7303 if (D.getDeclSpec().isModulePrivateSpecified()) {
7304 if (IsVariableTemplateSpecialization)
7305 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7306 << (IsPartialSpecialization ? 1 : 0)
7307 << FixItHint::CreateRemoval(
7308 D.getDeclSpec().getModulePrivateSpecLoc());
7309 else if (IsMemberSpecialization)
7310 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7311 << 2
7312 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7313 else if (NewVD->hasLocalStorage())
7314 Diag(NewVD->getLocation(), diag::err_module_private_local)
7315 << 0 << NewVD
7316 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7317 << FixItHint::CreateRemoval(
7318 D.getDeclSpec().getModulePrivateSpecLoc());
7319 else {
7320 NewVD->setModulePrivate();
7321 if (NewTemplate)
7322 NewTemplate->setModulePrivate();
7323 for (auto *B : Bindings)
7324 B->setModulePrivate();
7325 }
7326 }
7327
7328 if (getLangOpts().OpenCL) {
7329 deduceOpenCLAddressSpace(NewVD);
7330
7331 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
7332 if (TSC != TSCS_unspecified) {
7333 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7334 diag::err_opencl_unknown_type_specifier)
7335 << getLangOpts().getOpenCLVersionString()
7336 << DeclSpec::getSpecifierName(TSC) << 1;
7337 NewVD->setInvalidDecl();
7338 }
7339 }
7340
7341 // Handle attributes prior to checking for duplicates in MergeVarDecl
7342 ProcessDeclAttributes(S, NewVD, D);
7343
7344 // FIXME: This is probably the wrong location to be doing this and we should
7345 // probably be doing this for more attributes (especially for function
7346 // pointer attributes such as format, warn_unused_result, etc.). Ideally
7347 // the code to copy attributes would be generated by TableGen.
7348 if (R->isFunctionPointerType())
7349 if (const auto *TT = R->getAs<TypedefType>())
7350 copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7351
7352 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7353 getLangOpts().SYCLIsDevice) {
7354 if (EmitTLSUnsupportedError &&
7355 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7356 (getLangOpts().OpenMPIsDevice &&
7357 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7358 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7359 diag::err_thread_unsupported);
7360
7361 if (EmitTLSUnsupportedError &&
7362 (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
7363 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7364 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7365 // storage [duration]."
7366 if (SC == SC_None && S->getFnParent() != nullptr &&
7367 (NewVD->hasAttr<CUDASharedAttr>() ||
7368 NewVD->hasAttr<CUDAConstantAttr>())) {
7369 NewVD->setStorageClass(SC_Static);
7370 }
7371 }
7372
7373 // Ensure that dllimport globals without explicit storage class are treated as
7374 // extern. The storage class is set above using parsed attributes. Now we can
7375 // check the VarDecl itself.
7376 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"
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 7378, __extension__ __PRETTY_FUNCTION__))
7377 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"
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 7378, __extension__ __PRETTY_FUNCTION__))
7378 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"
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 7378, __extension__ __PRETTY_FUNCTION__))
;
7379
7380 // In auto-retain/release, infer strong retension for variables of
7381 // retainable type.
7382 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7383 NewVD->setInvalidDecl();
7384
7385 // Handle GNU asm-label extension (encoded as an attribute).
7386 if (Expr *E = (Expr*)D.getAsmLabel()) {
7387 // The parser guarantees this is a string.
7388 StringLiteral *SE = cast<StringLiteral>(E);
7389 StringRef Label = SE->getString();
7390 if (S->getFnParent() != nullptr) {
7391 switch (SC) {
7392 case SC_None:
7393 case SC_Auto:
7394 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7395 break;
7396 case SC_Register:
7397 // Local Named register
7398 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7399 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7400 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7401 break;
7402 case SC_Static:
7403 case SC_Extern:
7404 case SC_PrivateExtern:
7405 break;
7406 }
7407 } else if (SC == SC_Register) {
7408 // Global Named register
7409 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7410 const auto &TI = Context.getTargetInfo();
7411 bool HasSizeMismatch;
7412
7413 if (!TI.isValidGCCRegisterName(Label))
7414 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7415 else if (!TI.validateGlobalRegisterVariable(Label,
7416 Context.getTypeSize(R),
7417 HasSizeMismatch))
7418 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7419 else if (HasSizeMismatch)
7420 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7421 }
7422
7423 if (!R->isIntegralType(Context) && !R->isPointerType()) {
7424 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7425 NewVD->setInvalidDecl(true);
7426 }
7427 }
7428
7429 NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7430 /*IsLiteralLabel=*/true,
7431 SE->getStrTokenLoc(0)));
7432 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7433 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7434 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7435 if (I != ExtnameUndeclaredIdentifiers.end()) {
7436 if (isDeclExternC(NewVD)) {
7437 NewVD->addAttr(I->second);
7438 ExtnameUndeclaredIdentifiers.erase(I);
7439 } else
7440 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7441 << /*Variable*/1 << NewVD;
7442 }
7443 }
7444
7445 // Find the shadowed declaration before filtering for scope.
7446 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7447 ? getShadowedDeclaration(NewVD, Previous)
7448 : nullptr;
7449
7450 // Don't consider existing declarations that are in a different
7451 // scope and are out-of-semantic-context declarations (if the new
7452 // declaration has linkage).
7453 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7454 D.getCXXScopeSpec().isNotEmpty() ||
7455 IsMemberSpecialization ||
7456 IsVariableTemplateSpecialization);
7457
7458 // Check whether the previous declaration is in the same block scope. This
7459 // affects whether we merge types with it, per C++11 [dcl.array]p3.
7460 if (getLangOpts().CPlusPlus &&
7461 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7462 NewVD->setPreviousDeclInSameBlockScope(
7463 Previous.isSingleResult() && !Previous.isShadowed() &&
7464 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7465
7466 if (!getLangOpts().CPlusPlus) {
7467 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7468 } else {
7469 // If this is an explicit specialization of a static data member, check it.
7470 if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7471 CheckMemberSpecialization(NewVD, Previous))
7472 NewVD->setInvalidDecl();
7473
7474 // Merge the decl with the existing one if appropriate.
7475 if (!Previous.empty()) {
7476 if (Previous.isSingleResult() &&
7477 isa<FieldDecl>(Previous.getFoundDecl()) &&
7478 D.getCXXScopeSpec().isSet()) {
7479 // The user tried to define a non-static data member
7480 // out-of-line (C++ [dcl.meaning]p1).
7481 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7482 << D.getCXXScopeSpec().getRange();
7483 Previous.clear();
7484 NewVD->setInvalidDecl();
7485 }
7486 } else if (D.getCXXScopeSpec().isSet()) {
7487 // No previous declaration in the qualifying scope.
7488 Diag(D.getIdentifierLoc(), diag::err_no_member)
7489 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7490 << D.getCXXScopeSpec().getRange();
7491 NewVD->setInvalidDecl();
7492 }
7493
7494 if (!IsVariableTemplateSpecialization)
7495 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7496
7497 if (NewTemplate) {
7498 VarTemplateDecl *PrevVarTemplate =
7499 NewVD->getPreviousDecl()
7500 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7501 : nullptr;
7502
7503 // Check the template parameter list of this declaration, possibly
7504 // merging in the template parameter list from the previous variable
7505 // template declaration.
7506 if (CheckTemplateParameterList(
7507 TemplateParams,
7508 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7509 : nullptr,
7510 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7511 DC->isDependentContext())
7512 ? TPC_ClassTemplateMember
7513 : TPC_VarTemplate))
7514 NewVD->setInvalidDecl();
7515
7516 // If we are providing an explicit specialization of a static variable
7517 // template, make a note of that.
7518 if (PrevVarTemplate &&
7519 PrevVarTemplate->getInstantiatedFromMemberTemplate())
7520 PrevVarTemplate->setMemberSpecialization();
7521 }
7522 }
7523
7524 // Diagnose shadowed variables iff this isn't a redeclaration.
7525 if (ShadowedDecl && !D.isRedeclaration())
7526 CheckShadow(NewVD, ShadowedDecl, Previous);
7527
7528 ProcessPragmaWeak(S, NewVD);
7529
7530 // If this is the first declaration of an extern C variable, update
7531 // the map of such variables.
7532 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7533 isIncompleteDeclExternC(*this, NewVD))
7534 RegisterLocallyScopedExternCDecl(NewVD, S);
7535
7536 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7537 MangleNumberingContext *MCtx;
7538 Decl *ManglingContextDecl;
7539 std::tie(MCtx, ManglingContextDecl) =
7540 getCurrentMangleNumberContext(NewVD->getDeclContext());
7541 if (MCtx) {
7542 Context.setManglingNumber(
7543 NewVD, MCtx->getManglingNumber(
7544 NewVD, getMSManglingNumber(getLangOpts(), S)));
7545 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7546 }
7547 }
7548
7549 // Special handling of variable named 'main'.
7550 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7551 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7552 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7553
7554 // C++ [basic.start.main]p3
7555 // A program that declares a variable main at global scope is ill-formed.
7556 if (getLangOpts().CPlusPlus)
7557 Diag(D.getBeginLoc(), diag::err_main_global_variable);
7558
7559 // In C, and external-linkage variable named main results in undefined
7560 // behavior.
7561 else if (NewVD->hasExternalFormalLinkage())
7562 Diag(D.getBeginLoc(), diag::warn_main_redefined);
7563 }
7564
7565 if (D.isRedeclaration() && !Previous.empty()) {
7566 NamedDecl *Prev = Previous.getRepresentativeDecl();
7567 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7568 D.isFunctionDefinition());
7569 }
7570
7571 if (NewTemplate) {
7572 if (NewVD->isInvalidDecl())
7573 NewTemplate->setInvalidDecl();
7574 ActOnDocumentableDecl(NewTemplate);
7575 return NewTemplate;
7576 }
7577
7578 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7579 CompleteMemberSpecialization(NewVD, Previous);
7580
7581 return NewVD;
7582}
7583
7584/// Enum describing the %select options in diag::warn_decl_shadow.
7585enum ShadowedDeclKind {
7586 SDK_Local,
7587 SDK_Global,
7588 SDK_StaticMember,
7589 SDK_Field,
7590 SDK_Typedef,
7591 SDK_Using,
7592 SDK_StructuredBinding
7593};
7594
7595/// Determine what kind of declaration we're shadowing.
7596static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7597 const DeclContext *OldDC) {
7598 if (isa<TypeAliasDecl>(ShadowedDecl))
7599 return SDK_Using;
7600 else if (isa<TypedefDecl>(ShadowedDecl))
7601 return SDK_Typedef;
7602 else if (isa<BindingDecl>(ShadowedDecl))
7603 return SDK_StructuredBinding;
7604 else if (isa<RecordDecl>(OldDC))
7605 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7606
7607 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7608}
7609
7610/// Return the location of the capture if the given lambda captures the given
7611/// variable \p VD, or an invalid source location otherwise.
7612static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7613 const VarDecl *VD) {
7614 for (const Capture &Capture : LSI->Captures) {
7615 if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7616 return Capture.getLocation();
7617 }
7618 return SourceLocation();
7619}
7620
7621static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7622 const LookupResult &R) {
7623 // Only diagnose if we're shadowing an unambiguous field or variable.
7624 if (R.getResultKind() != LookupResult::Found)
7625 return false;
7626
7627 // Return false if warning is ignored.
7628 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7629}
7630
7631/// Return the declaration shadowed by the given variable \p D, or null
7632/// if it doesn't shadow any declaration or shadowing warnings are disabled.
7633NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7634 const LookupResult &R) {
7635 if (!shouldWarnIfShadowedDecl(Diags, R))
7636 return nullptr;
7637
7638 // Don't diagnose declarations at file scope.
7639 if (D->hasGlobalStorage())
7640 return nullptr;
7641
7642 NamedDecl *ShadowedDecl = R.getFoundDecl();
7643 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7644 : nullptr;
7645}
7646
7647/// Return the declaration shadowed by the given typedef \p D, or null
7648/// if it doesn't shadow any declaration or shadowing warnings are disabled.
7649NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7650 const LookupResult &R) {
7651 // Don't warn if typedef declaration is part of a class
7652 if (D->getDeclContext()->isRecord())
7653 return nullptr;
7654
7655 if (!shouldWarnIfShadowedDecl(Diags, R))
7656 return nullptr;
7657
7658 NamedDecl *ShadowedDecl = R.getFoundDecl();
7659 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7660}
7661
7662/// Return the declaration shadowed by the given variable \p D, or null
7663/// if it doesn't shadow any declaration or shadowing warnings are disabled.
7664NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
7665 const LookupResult &R) {
7666 if (!shouldWarnIfShadowedDecl(Diags, R))
7667 return nullptr;
7668
7669 NamedDecl *ShadowedDecl = R.getFoundDecl();
7670 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7671 : nullptr;
7672}
7673
7674/// Diagnose variable or built-in function shadowing. Implements
7675/// -Wshadow.
7676///
7677/// This method is called whenever a VarDecl is added to a "useful"
7678/// scope.
7679///
7680/// \param ShadowedDecl the declaration that is shadowed by the given variable
7681/// \param R the lookup of the name
7682///
7683void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7684 const LookupResult &R) {
7685 DeclContext *NewDC = D->getDeclContext();
7686
7687 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7688 // Fields are not shadowed by variables in C++ static methods.
7689 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7690 if (MD->isStatic())
7691 return;
7692
7693 // Fields shadowed by constructor parameters are a special case. Usually
7694 // the constructor initializes the field with the parameter.
7695 if (isa<CXXConstructorDecl>(NewDC))
7696 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7697 // Remember that this was shadowed so we can either warn about its
7698 // modification or its existence depending on warning settings.
7699 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7700 return;
7701 }
7702 }
7703
7704 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7705 if (shadowedVar->isExternC()) {
7706 // For shadowing external vars, make sure that we point to the global
7707 // declaration, not a locally scoped extern declaration.
7708 for (auto I : shadowedVar->redecls())
7709 if (I->isFileVarDecl()) {
7710 ShadowedDecl = I;
7711 break;
7712 }
7713 }
7714
7715 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7716
7717 unsigned WarningDiag = diag::warn_decl_shadow;
7718 SourceLocation CaptureLoc;
7719 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7720 isa<CXXMethodDecl>(NewDC)) {
7721 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7722 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7723 if (RD->getLambdaCaptureDefault() == LCD_None) {
7724 // Try to avoid warnings for lambdas with an explicit capture list.
7725 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7726 // Warn only when the lambda captures the shadowed decl explicitly.
7727 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7728 if (CaptureLoc.isInvalid())
7729 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7730 } else {
7731 // Remember that this was shadowed so we can avoid the warning if the
7732 // shadowed decl isn't captured and the warning settings allow it.
7733 cast<LambdaScopeInfo>(getCurFunction())
7734 ->ShadowingDecls.push_back(
7735 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7736 return;
7737 }
7738 }
7739
7740 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7741 // A variable can't shadow a local variable in an enclosing scope, if
7742 // they are separated by a non-capturing declaration context.
7743 for (DeclContext *ParentDC = NewDC;
7744 ParentDC && !ParentDC->Equals(OldDC);
7745 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7746 // Only block literals, captured statements, and lambda expressions
7747 // can capture; other scopes don't.
7748 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7749 !isLambdaCallOperator(ParentDC)) {
7750 return;
7751 }
7752 }
7753 }
7754 }
7755 }
7756
7757 // Only warn about certain kinds of shadowing for class members.
7758 if (NewDC && NewDC->isRecord()) {
7759 // In particular, don't warn about shadowing non-class members.
7760 if (!OldDC->isRecord())
7761 return;
7762
7763 // TODO: should we warn about static data members shadowing
7764 // static data members from base classes?
7765
7766 // TODO: don't diagnose for inaccessible shadowed members.
7767 // This is hard to do perfectly because we might friend the
7768 // shadowing context, but that's just a false negative.
7769 }
7770
7771
7772 DeclarationName Name = R.getLookupName();
7773
7774 // Emit warning and note.
7775 if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7776 return;
7777 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7778 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7779 if (!CaptureLoc.isInvalid())
7780 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7781 << Name << /*explicitly*/ 1;
7782 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7783}
7784
7785/// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7786/// when these variables are captured by the lambda.
7787void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7788 for (const auto &Shadow : LSI->ShadowingDecls) {
7789 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7790 // Try to avoid the warning when the shadowed decl isn't captured.
7791 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7792 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7793 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7794 ? diag::warn_decl_shadow_uncaptured_local
7795 : diag::warn_decl_shadow)
7796 << Shadow.VD->getDeclName()
7797 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7798 if (!CaptureLoc.isInvalid())
7799 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7800 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7801 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7802 }
7803}
7804
7805/// Check -Wshadow without the advantage of a previous lookup.
7806void Sema::CheckShadow(Scope *S, VarDecl *D) {
7807 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7808 return;
7809
7810 LookupResult R(*this, D->getDeclName(), D->getLocation(),
7811 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7812 LookupName(R, S);
7813 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7814 CheckShadow(D, ShadowedDecl, R);
7815}
7816
7817/// Check if 'E', which is an expression that is about to be modified, refers
7818/// to a constructor parameter that shadows a field.
7819void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7820 // Quickly ignore expressions that can't be shadowing ctor parameters.
7821 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7822 return;
7823 E = E->IgnoreParenImpCasts();
7824 auto *DRE = dyn_cast<DeclRefExpr>(E);
7825 if (!DRE)
7826 return;
7827 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7828 auto I = ShadowingDecls.find(D);
7829 if (I == ShadowingDecls.end())
7830 return;
7831 const NamedDecl *ShadowedDecl = I->second;
7832 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7833 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7834 Diag(D->getLocation(), diag::note_var_declared_here) << D;
7835 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7836
7837 // Avoid issuing multiple warnings about the same decl.
7838 ShadowingDecls.erase(I);
7839}
7840
7841/// Check for conflict between this global or extern "C" declaration and
7842/// previous global or extern "C" declarations. This is only used in C++.
7843template<typename T>
7844static bool checkGlobalOrExternCConflict(
7845 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7846 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\\\"\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 7846, __extension__ __PRETTY_FUNCTION__))
;
7847 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7848
7849 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7850 // The common case: this global doesn't conflict with any extern "C"
7851 // declaration.
7852 return false;
7853 }
7854
7855 if (Prev) {
7856 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7857 // Both the old and new declarations have C language linkage. This is a
7858 // redeclaration.
7859 Previous.clear();
7860 Previous.addDecl(Prev);
7861 return true;
7862 }
7863
7864 // This is a global, non-extern "C" declaration, and there is a previous
7865 // non-global extern "C" declaration. Diagnose if this is a variable
7866 // declaration.
7867 if (!isa<VarDecl>(ND))
7868 return false;
7869 } else {
7870 // The declaration is extern "C". Check for any declaration in the
7871 // translation unit which might conflict.
7872 if (IsGlobal) {
7873 // We have already performed the lookup into the translation unit.
7874 IsGlobal = false;
7875 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7876 I != E; ++I) {
7877 if (isa<VarDecl>(*I)) {
7878 Prev = *I;
7879 break;
7880 }
7881 }
7882 } else {
7883 DeclContext::lookup_result R =
7884 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7885 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7886 I != E; ++I) {
7887 if (isa<VarDecl>(*I)) {
7888 Prev = *I;
7889 break;
7890 }
7891 // FIXME: If we have any other entity with this name in global scope,
7892 // the declaration is ill-formed, but that is a defect: it breaks the
7893 // 'stat' hack, for instance. Only variables can have mangled name
7894 // clashes with extern "C" declarations, so only they deserve a
7895 // diagnostic.
7896 }
7897 }
7898
7899 if (!Prev)
7900 return false;
7901 }
7902
7903 // Use the first declaration's location to ensure we point at something which
7904 // is lexically inside an extern "C" linkage-spec.
7905 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 7905, __extension__ __PRETTY_FUNCTION__))
;
7906 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7907 Prev = FD->getFirstDecl();
7908 else
7909 Prev = cast<VarDecl>(Prev)->getFirstDecl();
7910
7911 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7912 << IsGlobal << ND;
7913 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7914 << IsGlobal;
7915 return false;
7916}
7917
7918/// Apply special rules for handling extern "C" declarations. Returns \c true
7919/// if we have found that this is a redeclaration of some prior entity.
7920///
7921/// Per C++ [dcl.link]p6:
7922/// Two declarations [for a function or variable] with C language linkage
7923/// with the same name that appear in different scopes refer to the same
7924/// [entity]. An entity with C language linkage shall not be declared with
7925/// the same name as an entity in global scope.
7926template<typename T>
7927static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7928 LookupResult &Previous) {
7929 if (!S.getLangOpts().CPlusPlus) {
7930 // In C, when declaring a global variable, look for a corresponding 'extern'
7931 // variable declared in function scope. We don't need this in C++, because
7932 // we find local extern decls in the surrounding file-scope DeclContext.
7933 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7934 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7935 Previous.clear();
7936 Previous.addDecl(Prev);
7937 return true;
7938 }
7939 }
7940 return false;
7941 }
7942
7943 // A declaration in the translation unit can conflict with an extern "C"
7944 // declaration.
7945 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7946 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7947
7948 // An extern "C" declaration can conflict with a declaration in the
7949 // translation unit or can be a redeclaration of an extern "C" declaration
7950 // in another scope.
7951 if (isIncompleteDeclExternC(S,ND))
7952 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7953
7954 // Neither global nor extern "C": nothing to do.
7955 return false;
7956}
7957
7958void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7959 // If the decl is already known invalid, don't check it.
7960 if (NewVD->isInvalidDecl())
7961 return;
7962
7963 QualType T = NewVD->getType();
7964
7965 // Defer checking an 'auto' type until its initializer is attached.
7966 if (T->isUndeducedType())
7967 return;
7968
7969 if (NewVD->hasAttrs())
7970 CheckAlignasUnderalignment(NewVD);
7971
7972 if (T->isObjCObjectType()) {
7973 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7974 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7975 T = Context.getObjCObjectPointerType(T);
7976 NewVD->setType(T);
7977 }
7978
7979 // Emit an error if an address space was applied to decl with local storage.
7980 // This includes arrays of objects with address space qualifiers, but not
7981 // automatic variables that point to other address spaces.
7982 // ISO/IEC TR 18037 S5.1.2
7983 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7984 T.getAddressSpace() != LangAS::Default) {
7985 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7986 NewVD->setInvalidDecl();
7987 return;
7988 }
7989
7990 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7991 // scope.
7992 if (getLangOpts().OpenCLVersion == 120 &&
7993 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
7994 getLangOpts()) &&
7995 NewVD->isStaticLocal()) {
7996 Diag(NewVD->getLocation(), diag::err_static_function_scope);
7997 NewVD->setInvalidDecl();
7998 return;
7999 }
8000
8001 if (getLangOpts().OpenCL) {
8002 if (!diagnoseOpenCLTypes(*this, NewVD))
8003 return;
8004
8005 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8006 if (NewVD->hasAttr<BlocksAttr>()) {
8007 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8008 return;
8009 }
8010
8011 if (T->isBlockPointerType()) {
8012 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8013 // can't use 'extern' storage class.
8014 if (!T.isConstQualified()) {
8015 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8016 << 0 /*const*/;
8017 NewVD->setInvalidDecl();
8018 return;
8019 }
8020 if (NewVD->hasExternalStorage()) {
8021 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8022 NewVD->setInvalidDecl();
8023 return;
8024 }
8025 }
8026
8027 // FIXME: Adding local AS in C++ for OpenCL might make sense.
8028 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8029 NewVD->hasExternalStorage()) {
8030 if (!T->isSamplerT() && !T->isDependentType() &&
8031 !(T.getAddressSpace() == LangAS::opencl_constant ||
8032 (T.getAddressSpace() == LangAS::opencl_global &&
8033 getOpenCLOptions().areProgramScopeVariablesSupported(
8034 getLangOpts())))) {
8035 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8036 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8037 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8038 << Scope << "global or constant";
8039 else
8040 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8041 << Scope << "constant";
8042 NewVD->setInvalidDecl();
8043 return;
8044 }
8045 } else {
8046 if (T.getAddressSpace() == LangAS::opencl_global) {
8047 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8048 << 1 /*is any function*/ << "global";
8049 NewVD->setInvalidDecl();
8050 return;
8051 }
8052 if (T.getAddressSpace() == LangAS::opencl_constant ||
8053 T.getAddressSpace() == LangAS::opencl_local) {
8054 FunctionDecl *FD = getCurFunctionDecl();
8055 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8056 // in functions.
8057 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8058 if (T.getAddressSpace() == LangAS::opencl_constant)
8059 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8060 << 0 /*non-kernel only*/ << "constant";
8061 else
8062 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8063 << 0 /*non-kernel only*/ << "local";
8064 NewVD->setInvalidDecl();
8065 return;
8066 }
8067 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8068 // in the outermost scope of a kernel function.
8069 if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8070 if (!getCurScope()->isFunctionScope()) {
8071 if (T.getAddressSpace() == LangAS::opencl_constant)
8072 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8073 << "constant";
8074 else
8075 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8076 << "local";
8077 NewVD->setInvalidDecl();
8078 return;
8079 }
8080 }
8081 } else if (T.getAddressSpace() != LangAS::opencl_private &&
8082 // If we are parsing a template we didn't deduce an addr
8083 // space yet.
8084 T.getAddressSpace() != LangAS::Default) {
8085 // Do not allow other address spaces on automatic variable.
8086 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8087 NewVD->setInvalidDecl();
8088 return;
8089 }
8090 }
8091 }
8092
8093 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8094 && !NewVD->hasAttr<BlocksAttr>()) {
8095 if (getLangOpts().getGC() != LangOptions::NonGC)
8096 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8097 else {
8098 assert(!getLangOpts().ObjCAutoRefCount)(static_cast <bool> (!getLangOpts().ObjCAutoRefCount) ?
void (0) : __assert_fail ("!getLangOpts().ObjCAutoRefCount",
"/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 8098, __extension__ __PRETTY_FUNCTION__))
;
8099 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8100 }
8101 }
8102
8103 bool isVM = T->isVariablyModifiedType();
8104 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8105 NewVD->hasAttr<BlocksAttr>())
8106 setFunctionHasBranchProtectedScope();
8107
8108 if ((isVM && NewVD->hasLinkage()) ||
8109 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8110 bool SizeIsNegative;
8111 llvm::APSInt Oversized;
8112 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
8113 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8114 QualType FixedT;
8115 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
8116 FixedT = FixedTInfo->getType();
8117 else if (FixedTInfo) {
8118 // Type and type-as-written are canonically different. We need to fix up
8119 // both types separately.
8120 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8121 Oversized);
8122 }
8123 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8124 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8125 // FIXME: This won't give the correct result for
8126 // int a[10][n];
8127 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8128
8129 if (NewVD->isFileVarDecl())
8130 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8131 << SizeRange;
8132 else if (NewVD->isStaticLocal())
8133 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8134 << SizeRange;
8135 else
8136 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8137 << SizeRange;
8138 NewVD->setInvalidDecl();
8139 return;
8140 }
8141
8142 if (!FixedTInfo) {
8143 if (NewVD->isFileVarDecl())
8144 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8145 else
8146 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8147 NewVD->setInvalidDecl();
8148 return;
8149 }
8150
8151 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8152 NewVD->setType(FixedT);
8153 NewVD->setTypeSourceInfo(FixedTInfo);
8154 }
8155
8156 if (T->isVoidType()) {
8157 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8158 // of objects and functions.
8159 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8160 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8161 << T;
8162 NewVD->setInvalidDecl();
8163 return;
8164 }
8165 }
8166
8167 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8168 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8169 NewVD->setInvalidDecl();
8170 return;
8171 }
8172
8173 if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
8174 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8175 NewVD->setInvalidDecl();
8176 return;
8177 }
8178
8179 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8180 Diag(NewVD->getLocation(), diag::err_block_on_vm);
8181 NewVD->setInvalidDecl();
8182 return;
8183 }
8184
8185 if (NewVD->isConstexpr() && !T->isDependentType() &&
8186 RequireLiteralType(NewVD->getLocation(), T,
8187 diag::err_constexpr_var_non_literal)) {
8188 NewVD->setInvalidDecl();
8189 return;
8190 }
8191
8192 // PPC MMA non-pointer types are not allowed as non-local variable types.
8193 if (Context.getTargetInfo().getTriple().isPPC64() &&
8194 !NewVD->isLocalVarDecl() &&
8195 CheckPPCMMAType(T, NewVD->getLocation())) {
8196 NewVD->setInvalidDecl();
8197 return;
8198 }
8199}
8200
8201/// Perform semantic checking on a newly-created variable
8202/// declaration.
8203///
8204/// This routine performs all of the type-checking required for a
8205/// variable declaration once it has been built. It is used both to
8206/// check variables after they have been parsed and their declarators
8207/// have been translated into a declaration, and to check variables
8208/// that have been instantiated from a template.
8209///
8210/// Sets NewVD->isInvalidDecl() if an error was encountered.
8211///
8212/// Returns true if the variable declaration is a redeclaration.
8213bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8214 CheckVariableDeclarationType(NewVD);
8215
8216 // If the decl is already known invalid, don't check it.
8217 if (NewVD->isInvalidDecl())
8218 return false;
8219
8220 // If we did not find anything by this name, look for a non-visible
8221 // extern "C" declaration with the same name.
8222 if (Previous.empty() &&
8223 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8224 Previous.setShadowed();
8225
8226 if (!Previous.empty()) {
8227 MergeVarDecl(NewVD, Previous);
8228 return true;
8229 }
8230 return false;
8231}
8232
8233/// AddOverriddenMethods - See if a method overrides any in the base classes,
8234/// and if so, check that it's a valid override and remember it.
8235bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8236 llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
8237
8238 // Look for methods in base classes that this method might override.
8239 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8240 /*DetectVirtual=*/false);
8241 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8242 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8243 DeclarationName Name = MD->getDeclName();
8244
8245 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8246 // We really want to find the base class destructor here.
8247 QualType T = Context.getTypeDeclType(BaseRecord);
8248 CanQualType CT = Context.getCanonicalType(T);
8249 Name = Context.DeclarationNames.getCXXDestructorName(CT);
8250 }
8251
8252 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8253 CXXMethodDecl *BaseMD =
8254 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8255 if (!BaseMD || !BaseMD->isVirtual() ||
8256 IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8257 /*ConsiderCudaAttrs=*/true,
8258 // C++2a [class.virtual]p2 does not consider requires
8259 // clauses when overriding.
8260 /*ConsiderRequiresClauses=*/false))
8261 continue;
8262
8263 if (Overridden.insert(BaseMD).second) {
8264 MD->addOverriddenMethod(BaseMD);
8265 CheckOverridingFunctionReturnType(MD, BaseMD);
8266 CheckOverridingFunctionAttributes(MD, BaseMD);
8267 CheckOverridingFunctionExceptionSpec(MD, BaseMD);
8268 CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
8269 }
8270
8271 // A method can only override one function from each base class. We
8272 // don't track indirectly overridden methods from bases of bases.
8273 return true;
8274 }
8275
8276 return false;
8277 };
8278
8279 DC->lookupInBases(VisitBase, Paths);
8280 return !Overridden.empty();
8281}
8282
8283namespace {
8284 // Struct for holding all of the extra arguments needed by
8285 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8286 struct ActOnFDArgs {
8287 Scope *S;
8288 Declarator &D;
8289 MultiTemplateParamsArg TemplateParamLists;
8290 bool AddToScope;
8291 };
8292} // end anonymous namespace
8293
8294namespace {
8295
8296// Callback to only accept typo corrections that have a non-zero edit distance.
8297// Also only accept corrections that have the same parent decl.
8298class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8299 public:
8300 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8301 CXXRecordDecl *Parent)
8302 : Context(Context), OriginalFD(TypoFD),
8303 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8304
8305 bool ValidateCandidate(const TypoCorrection &candidate) override {
8306 if (candidate.getEditDistance() == 0)
8307 return false;
8308
8309 SmallVector<unsigned, 1> MismatchedParams;
8310 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8311 CDeclEnd = candidate.end();
8312 CDecl != CDeclEnd; ++CDecl) {
8313 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8314
8315 if (FD && !FD->hasBody() &&
8316 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8317 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8318 CXXRecordDecl *Parent = MD->getParent();
8319 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8320 return true;
8321 } else if (!ExpectedParent) {
8322 return true;
8323 }
8324 }
8325 }
8326
8327 return false;
8328 }
8329
8330 std::unique_ptr<CorrectionCandidateCallback> clone() override {
8331 return std::make_unique<DifferentNameValidatorCCC>(*this);
8332 }
8333
8334 private:
8335 ASTContext &Context;
8336 FunctionDecl *OriginalFD;
8337 CXXRecordDecl *ExpectedParent;
8338};
8339
8340} // end anonymous namespace
8341
8342void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8343 TypoCorrectedFunctionDefinitions.insert(F);
8344}
8345
8346/// Generate diagnostics for an invalid function redeclaration.
8347///
8348/// This routine handles generating the diagnostic messages for an invalid
8349/// function redeclaration, including finding possible similar declarations
8350/// or performing typo correction if there are no previous declarations with
8351/// the same name.
8352///
8353/// Returns a NamedDecl iff typo correction was performed and substituting in
8354/// the new declaration name does not cause new errors.
8355static NamedDecl *DiagnoseInvalidRedeclaration(
8356 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8357 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8358 DeclarationName Name = NewFD->getDeclName();
8359 DeclContext *NewDC = NewFD->getDeclContext();
8360 SmallVector<unsigned, 1> MismatchedParams;
8361 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8362 TypoCorrection Correction;
8363 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8364 unsigned DiagMsg =
8365 IsLocalFriend ? diag::err_no_matching_local_friend :
8366 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8367 diag::err_member_decl_does_not_match;
8368 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8369 IsLocalFriend ? Sema::LookupLocalFriendName
8370 : Sema::LookupOrdinaryName,
8371 Sema::ForVisibleRedeclaration);
8372
8373 NewFD->setInvalidDecl();
8374 if (IsLocalFriend)
8375 SemaRef.LookupName(Prev, S);
8376 else
8377 SemaRef.LookupQualifiedName(Prev, NewDC);
8378 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 8379, __extension__ __PRETTY_FUNCTION__))
8379 "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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 8379, __extension__ __PRETTY_FUNCTION__))
;
8380 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8381 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8382 MD ? MD->getParent() : nullptr);
8383 if (!Prev.empty()) {
8384 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8385 Func != FuncEnd; ++Func) {
8386 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8387 if (FD &&
8388 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8389 // Add 1 to the index so that 0 can mean the mismatch didn't
8390 // involve a parameter
8391 unsigned ParamNum =
8392 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8393 NearMatches.push_back(std::make_pair(FD, ParamNum));
8394 }
8395 }
8396 // If the qualified name lookup yielded nothing, try typo correction
8397 } else if ((Correction = SemaRef.CorrectTypo(
8398 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8399 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8400 IsLocalFriend ? nullptr : NewDC))) {
8401 // Set up everything for the call to ActOnFunctionDeclarator
8402 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8403 ExtraArgs.D.getIdentifierLoc());
8404 Previous.clear();
8405 Previous.setLookupName(Correction.getCorrection());
8406 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8407 CDeclEnd = Correction.end();
8408 CDecl != CDeclEnd; ++CDecl) {
8409 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8410 if (FD && !FD->hasBody() &&
8411 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8412 Previous.addDecl(FD);
8413 }
8414 }
8415 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8416
8417 NamedDecl *Result;
8418 // Retry building the function declaration with the new previous
8419 // declarations, and with errors suppressed.
8420 {
8421 // Trap errors.
8422 Sema::SFINAETrap Trap(SemaRef);
8423
8424 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8425 // pieces need to verify the typo-corrected C++ declaration and hopefully
8426 // eliminate the need for the parameter pack ExtraArgs.
8427 Result = SemaRef.ActOnFunctionDeclarator(
8428 ExtraArgs.S, ExtraArgs.D,
8429 Correction.getCorrectionDecl()->getDeclContext(),
8430 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8431 ExtraArgs.AddToScope);
8432
8433 if (Trap.hasErrorOccurred())
8434 Result = nullptr;
8435 }
8436
8437 if (Result) {
8438 // Determine which correction we picked.
8439 Decl *Canonical = Result->getCanonicalDecl();
8440 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8441 I != E; ++I)
8442 if ((*I)->getCanonicalDecl() == Canonical)
8443 Correction.setCorrectionDecl(*I);
8444
8445 // Let Sema know about the correction.
8446 SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8447 SemaRef.diagnoseTypo(
8448 Correction,
8449 SemaRef.PDiag(IsLocalFriend
8450 ? diag::err_no_matching_local_friend_suggest
8451 : diag::err_member_decl_does_not_match_suggest)
8452 << Name << NewDC << IsDefinition);
8453 return Result;
8454 }
8455
8456 // Pretend the typo correction never occurred
8457 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8458 ExtraArgs.D.getIdentifierLoc());
8459 ExtraArgs.D.setRedeclaration(wasRedeclaration);
8460 Previous.clear();
8461 Previous.setLookupName(Name);
8462 }
8463
8464 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8465 << Name << NewDC << IsDefinition << NewFD->getLocation();
8466
8467 bool NewFDisConst = false;
8468 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8469 NewFDisConst = NewMD->isConst();
8470
8471 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8472 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8473 NearMatch != NearMatchEnd; ++NearMatch) {
8474 FunctionDecl *FD = NearMatch->first;
8475 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8476 bool FDisConst = MD && MD->isConst();
8477 bool IsMember = MD || !IsLocalFriend;
8478
8479 // FIXME: These notes are poorly worded for the local friend case.
8480 if (unsigned Idx = NearMatch->second) {
8481 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8482 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8483 if (Loc.isInvalid()) Loc = FD->getLocation();
8484 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8485 : diag::note_local_decl_close_param_match)
8486 << Idx << FDParam->getType()
8487 << NewFD->getParamDecl(Idx - 1)->getType();
8488 } else if (FDisConst != NewFDisConst) {
8489 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8490 << NewFDisConst << FD->getSourceRange().getEnd();
8491 } else
8492 SemaRef.Diag(FD->getLocation(),
8493 IsMember ? diag::note_member_def_close_match
8494 : diag::note_local_decl_close_match);
8495 }
8496 return nullptr;
8497}
8498
8499static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8500 switch (D.getDeclSpec().getStorageClassSpec()) {
8501 default: llvm_unreachable("Unknown storage class!")::llvm::llvm_unreachable_internal("Unknown storage class!", "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 8501)
;
8502 case DeclSpec::SCS_auto:
8503 case DeclSpec::SCS_register:
8504 case DeclSpec::SCS_mutable:
8505 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8506 diag::err_typecheck_sclass_func);
8507 D.getMutableDeclSpec().ClearStorageClassSpecs();
8508 D.setInvalidType();
8509 break;
8510 case DeclSpec::SCS_unspecified: break;
8511 case DeclSpec::SCS_extern:
8512 if (D.getDeclSpec().isExternInLinkageSpec())
8513 return SC_None;
8514 return SC_Extern;
8515 case DeclSpec::SCS_static: {
8516 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8517 // C99 6.7.1p5:
8518 // The declaration of an identifier for a function that has
8519 // block scope shall have no explicit storage-class specifier
8520 // other than extern
8521 // See also (C++ [dcl.stc]p4).
8522 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8523 diag::err_static_block_func);
8524 break;
8525 } else
8526 return SC_Static;
8527 }
8528 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8529 }
8530
8531 // No explicit storage class has already been returned
8532 return SC_None;
8533}
8534
8535static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8536 DeclContext *DC, QualType &R,
8537 TypeSourceInfo *TInfo,
8538 StorageClass SC,
8539 bool &IsVirtualOkay) {
8540 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8541 DeclarationName Name = NameInfo.getName();
8542
8543 FunctionDecl *NewFD = nullptr;
8544 bool isInline = D.getDeclSpec().isInlineSpecified();
8545
8546 if (!SemaRef.getLangOpts().CPlusPlus) {
8547 // Determine whether the function was written with a
8548 // prototype. This true when:
8549 // - there is a prototype in the declarator, or
8550 // - the type R of the function is some kind of typedef or other non-
8551 // attributed reference to a type name (which eventually refers to a
8552 // function type).
8553 bool HasPrototype =
8554 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8555 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8556
8557 NewFD = FunctionDecl::Create(
8558 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
8559 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
8560 ConstexprSpecKind::Unspecified,
8561 /*TrailingRequiresClause=*/nullptr);
8562 if (D.isInvalidType())
8563 NewFD->setInvalidDecl();
8564
8565 return NewFD;
8566 }
8567
8568 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8569
8570 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8571 if (ConstexprKind == ConstexprSpecKind::Constinit) {
8572 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8573 diag::err_constexpr_wrong_decl_kind)
8574 << static_cast<int>(ConstexprKind);
8575 ConstexprKind = ConstexprSpecKind::Unspecified;
8576 D.getMutableDeclSpec().ClearConstexprSpec();
8577 }
8578 Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8579
8580 // Check that the return type is not an abstract class type.
8581 // For record types, this is done by the AbstractClassUsageDiagnoser once
8582 // the class has been completely parsed.
8583 if (!DC->isRecord() &&
8584 SemaRef.RequireNonAbstractType(
8585 D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8586 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8587 D.setInvalidType();
8588
8589 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8590 // This is a C++ constructor declaration.
8591 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 8592, __extension__ __PRETTY_FUNCTION__))
8592 "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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 8592, __extension__ __PRETTY_FUNCTION__))
;
8593
8594 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8595 return CXXConstructorDecl::Create(
8596 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8597 TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(),
8598 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8599 InheritedConstructor(), TrailingRequiresClause);
8600
8601 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8602 // This is a C++ destructor declaration.
8603 if (DC->isRecord()) {
8604 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8605 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8606 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8607 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8608 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8609 /*isImplicitlyDeclared=*/false, ConstexprKind,
8610 TrailingRequiresClause);
8611
8612 // If the destructor needs an implicit exception specification, set it
8613 // now. FIXME: It'd be nice to be able to create the right type to start
8614 // with, but the type needs to reference the destructor declaration.
8615 if (SemaRef.getLangOpts().CPlusPlus11)
8616 SemaRef.AdjustDestructorExceptionSpec(NewDD);
8617
8618 IsVirtualOkay = true;
8619 return NewDD;
8620
8621 } else {
8622 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8623 D.setInvalidType();
8624
8625 // Create a FunctionDecl to satisfy the function definition parsing
8626 // code path.
8627 return FunctionDecl::Create(
8628 SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
8629 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8630 /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
8631 }
8632
8633 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8634 if (!DC->isRecord()) {
8635 SemaRef.Diag(D.getIdentifierLoc(),
8636 diag::err_conv_function_not_member);
8637 return nullptr;
8638 }
8639
8640 SemaRef.CheckConversionDeclarator(D, R, SC);
8641 if (D.isInvalidType())
8642 return nullptr;
8643
8644 IsVirtualOkay = true;
8645 return CXXConversionDecl::Create(
8646 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8647 TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8648 ExplicitSpecifier, ConstexprKind, SourceLocation(),
8649 TrailingRequiresClause);
8650
8651 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8652 if (TrailingRequiresClause)
8653 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8654 diag::err_trailing_requires_clause_on_deduction_guide)
8655 << TrailingRequiresClause->getSourceRange();
8656 SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8657
8658 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8659 ExplicitSpecifier, NameInfo, R, TInfo,
8660 D.getEndLoc());
8661 } else if (DC->isRecord()) {
8662 // If the name of the function is the same as the name of the record,
8663 // then this must be an invalid constructor that has a return type.
8664 // (The parser checks for a return type and makes the declarator a
8665 // constructor if it has no return type).
8666 if (Name.getAsIdentifierInfo() &&
8667 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8668 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8669 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8670 << SourceRange(D.getIdentifierLoc());
8671 return nullptr;
8672 }
8673
8674 // This is a C++ method declaration.
8675 CXXMethodDecl *Ret = CXXMethodDecl::Create(
8676 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8677 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8678 ConstexprKind, SourceLocation(), TrailingRequiresClause);
8679 IsVirtualOkay = !Ret->isStatic();
8680 return Ret;
8681 } else {
8682 bool isFriend =
8683 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8684 if (!isFriend && SemaRef.CurContext->isRecord())
8685 return nullptr;
8686
8687 // Determine whether the function was written with a
8688 // prototype. This true when:
8689 // - we're in C++ (where every function has a prototype),
8690 return FunctionDecl::Create(
8691 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
8692 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8693 true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
8694 }
8695}
8696
8697enum OpenCLParamType {
8698 ValidKernelParam,
8699 PtrPtrKernelParam,
8700 PtrKernelParam,
8701 InvalidAddrSpacePtrKernelParam,
8702 InvalidKernelParam,
8703 RecordKernelParam
8704};
8705
8706static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8707 // Size dependent types are just typedefs to normal integer types
8708 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8709 // integers other than by their names.
8710 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8711
8712 // Remove typedefs one by one until we reach a typedef
8713 // for a size dependent type.
8714 QualType DesugaredTy = Ty;
8715 do {
8716 ArrayRef<StringRef> Names(SizeTypeNames);
8717 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8718 if (Names.end() != Match)
8719 return true;
8720
8721 Ty = DesugaredTy;
8722 DesugaredTy = Ty.getSingleStepDesugaredType(C);
8723 } while (DesugaredTy != Ty);
8724
8725 return false;
8726}
8727
8728static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8729 if (PT->isDependentType())
8730 return InvalidKernelParam;
8731
8732 if (PT->isPointerType() || PT->isReferenceType()) {
8733 QualType PointeeType = PT->getPointeeType();
8734 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8735 PointeeType.getAddressSpace() == LangAS::opencl_private ||
8736 PointeeType.getAddressSpace() == LangAS::Default)
8737 return InvalidAddrSpacePtrKernelParam;
8738
8739 if (PointeeType->isPointerType()) {
8740 // This is a pointer to pointer parameter.
8741 // Recursively check inner type.
8742 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
8743 if (ParamKind == InvalidAddrSpacePtrKernelParam ||
8744 ParamKind == InvalidKernelParam)
8745 return ParamKind;
8746
8747 return PtrPtrKernelParam;
8748 }
8749
8750 // C++ for OpenCL v1.0 s2.4:
8751 // Moreover the types used in parameters of the kernel functions must be:
8752 // Standard layout types for pointer parameters. The same applies to
8753 // reference if an implementation supports them in kernel parameters.
8754 if (S.getLangOpts().OpenCLCPlusPlus &&
8755 !S.getOpenCLOptions().isAvailableOption(
8756 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
8757 !PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
8758 !PointeeType->isStandardLayoutType())
8759 return InvalidKernelParam;
8760
8761 return PtrKernelParam;
8762 }
8763
8764 // OpenCL v1.2 s6.9.k:
8765 // Arguments to kernel functions in a program cannot be declared with the
8766 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8767 // uintptr_t or a struct and/or union that contain fields declared to be one
8768 // of these built-in scalar types.
8769 if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8770 return InvalidKernelParam;
8771
8772 if (PT->isImageType())
8773 return PtrKernelParam;
8774
8775 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8776 return InvalidKernelParam;
8777
8778 // OpenCL extension spec v1.2 s9.5:
8779 // This extension adds support for half scalar and vector types as built-in
8780 // types that can be used for arithmetic operations, conversions etc.
8781 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
8782 PT->isHalfType())
8783 return InvalidKernelParam;
8784
8785 // Look into an array argument to check if it has a forbidden type.
8786 if (PT->isArrayType()) {
8787 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8788 // Call ourself to check an underlying type of an array. Since the
8789 // getPointeeOrArrayElementType returns an innermost type which is not an
8790 // array, this recursive call only happens once.
8791 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8792 }
8793
8794 // C++ for OpenCL v1.0 s2.4:
8795 // Moreover the types used in parameters of the kernel functions must be:
8796 // Trivial and standard-layout types C++17 [basic.types] (plain old data
8797 // types) for parameters passed by value;
8798 if (S.getLangOpts().OpenCLCPlusPlus &&
8799 !S.getOpenCLOptions().isAvailableOption(
8800 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
8801 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
8802 return InvalidKernelParam;
8803
8804 if (PT->isRecordType())
8805 return RecordKernelParam;
8806
8807 return ValidKernelParam;
8808}
8809
8810static void checkIsValidOpenCLKernelParameter(
8811 Sema &S,
8812 Declarator &D,
8813 ParmVarDecl *Param,
8814 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8815 QualType PT = Param->getType();
8816
8817 // Cache the valid types we encounter to avoid rechecking structs that are
8818 // used again
8819 if (ValidTypes.count(PT.getTypePtr()))
8820 return;
8821
8822 switch (getOpenCLKernelParameterType(S, PT)) {
8823 case PtrPtrKernelParam:
8824 // OpenCL v3.0 s6.11.a:
8825 // A kernel function argument cannot be declared as a pointer to a pointer
8826 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
8827 if (S.getLangOpts().OpenCLVersion <= 120 &&
8828 !S.getLangOpts().OpenCLCPlusPlus) {
8829 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8830 D.setInvalidType();
8831 return;
8832 }
8833
8834 ValidTypes.insert(PT.getTypePtr());
8835 return;
8836
8837 case InvalidAddrSpacePtrKernelParam:
8838 // OpenCL v1.0 s6.5:
8839 // __kernel function arguments declared to be a pointer of a type can point
8840 // to one of the following address spaces only : __global, __local or
8841 // __constant.
8842 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8843 D.setInvalidType();
8844 return;
8845
8846 // OpenCL v1.2 s6.9.k:
8847 // Arguments to kernel functions in a program cannot be declared with the
8848 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8849 // uintptr_t or a struct and/or union that contain fields declared to be
8850 // one of these built-in scalar types.
8851
8852 case InvalidKernelParam:
8853 // OpenCL v1.2 s6.8 n:
8854 // A kernel function argument cannot be declared
8855 // of event_t type.
8856 // Do not diagnose half type since it is diagnosed as invalid argument
8857 // type for any function elsewhere.
8858 if (!PT->isHalfType()) {
8859 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8860
8861 // Explain what typedefs are involved.
8862 const TypedefType *Typedef = nullptr;
8863 while ((Typedef = PT->getAs<TypedefType>())) {
8864 SourceLocation Loc = Typedef->getDecl()->getLocation();
8865 // SourceLocation may be invalid for a built-in type.
8866 if (Loc.isValid())
8867 S.Diag(Loc, diag::note_entity_declared_at) << PT;
8868 PT = Typedef->desugar();
8869 }
8870 }
8871
8872 D.setInvalidType();
8873 return;
8874
8875 case PtrKernelParam:
8876 case ValidKernelParam:
8877 ValidTypes.insert(PT.getTypePtr());
8878 return;
8879
8880 case RecordKernelParam:
8881 break;
8882 }
8883
8884 // Track nested structs we will inspect
8885 SmallVector<const Decl *, 4> VisitStack;
8886
8887 // Track where we are in the nested structs. Items will migrate from
8888 // VisitStack to HistoryStack as we do the DFS for bad field.
8889 SmallVector<const FieldDecl *, 4> HistoryStack;
8890 HistoryStack.push_back(nullptr);
8891
8892 // At this point we already handled everything except of a RecordType or
8893 // an ArrayType of a RecordType.
8894 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.\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 8894, __extension__ __PRETTY_FUNCTION__))
;
8895 const RecordType *RecTy =
8896 PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8897 const RecordDecl *OrigRecDecl = RecTy->getDecl();
8898
8899 VisitStack.push_back(RecTy->getDecl());
8900 assert(VisitStack.back() && "First decl null?")(static_cast <bool> (VisitStack.back() && "First decl null?"
) ? void (0) : __assert_fail ("VisitStack.back() && \"First decl null?\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 8900, __extension__ __PRETTY_FUNCTION__))
;
8901
8902 do {
8903 const Decl *Next = VisitStack.pop_back_val();
8904 if (!Next) {
8905 assert(!HistoryStack.empty())(static_cast <bool> (!HistoryStack.empty()) ? void (0) :
__assert_fail ("!HistoryStack.empty()", "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 8905, __extension__ __PRETTY_FUNCTION__))
;
8906 // Found a marker, we have gone up a level
8907 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8908 ValidTypes.insert(Hist->getType().getTypePtr());
8909
8910 continue;
8911 }
8912
8913 // Adds everything except the original parameter declaration (which is not a
8914 // field itself) to the history stack.
8915 const RecordDecl *RD;
8916 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8917 HistoryStack.push_back(Field);
8918
8919 QualType FieldTy = Field->getType();
8920 // Other field types (known to be valid or invalid) are handled while we
8921 // walk around RecordDecl::fields().
8922 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&(static_cast <bool> ((FieldTy->isArrayType() || FieldTy
->isRecordType()) && "Unexpected type.") ? void (0
) : __assert_fail ("(FieldTy->isArrayType() || FieldTy->isRecordType()) && \"Unexpected type.\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 8923, __extension__ __PRETTY_FUNCTION__))
8923 "Unexpected type.")(static_cast <bool> ((FieldTy->isArrayType() || FieldTy
->isRecordType()) && "Unexpected type.") ? void (0
) : __assert_fail ("(FieldTy->isArrayType() || FieldTy->isRecordType()) && \"Unexpected type.\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 8923, __extension__ __PRETTY_FUNCTION__))
;
8924 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8925
8926 RD = FieldRecTy->castAs<RecordType>()->getDecl();
8927 } else {
8928 RD = cast<RecordDecl>(Next);
8929 }
8930
8931 // Add a null marker so we know when we've gone back up a level
8932 VisitStack.push_back(nullptr);
8933
8934 for (const auto *FD : RD->fields()) {
8935 QualType QT = FD->getType();
8936
8937 if (ValidTypes.count(QT.getTypePtr()))
8938 continue;
8939
8940 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8941 if (ParamType == ValidKernelParam)
8942 continue;
8943
8944 if (ParamType == RecordKernelParam) {
8945 VisitStack.push_back(FD);
8946 continue;
8947 }
8948
8949 // OpenCL v1.2 s6.9.p:
8950 // Arguments to kernel functions that are declared to be a struct or union
8951 // do not allow OpenCL objects to be passed as elements of the struct or
8952 // union.
8953 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8954 ParamType == InvalidAddrSpacePtrKernelParam) {
8955 S.Diag(Param->getLocation(),
8956 diag::err_record_with_pointers_kernel_param)
8957 << PT->isUnionType()
8958 << PT;
8959 } else {
8960 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8961 }
8962
8963 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8964 << OrigRecDecl->getDeclName();
8965
8966 // We have an error, now let's go back up through history and show where
8967 // the offending field came from
8968 for (ArrayRef<const FieldDecl *>::const_iterator
8969 I = HistoryStack.begin() + 1,
8970 E = HistoryStack.end();
8971 I != E; ++I) {
8972 const FieldDecl *OuterField = *I;
8973 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8974 << OuterField->getType();
8975 }
8976
8977 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8978 << QT->isPointerType()
8979 << QT;
8980 D.setInvalidType();
8981 return;
8982 }
8983 } while (!VisitStack.empty());
8984}
8985
8986/// Find the DeclContext in which a tag is implicitly declared if we see an
8987/// elaborated type specifier in the specified context, and lookup finds
8988/// nothing.
8989static DeclContext *getTagInjectionContext(DeclContext *DC) {
8990 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8991 DC = DC->getParent();
8992 return DC;
8993}
8994
8995/// Find the Scope in which a tag is implicitly declared if we see an
8996/// elaborated type specifier in the specified context, and lookup finds
8997/// nothing.
8998static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8999 while (S->isClassScope() ||
9000 (LangOpts.CPlusPlus &&
9001 S->isFunctionPrototypeScope()) ||
9002 ((S->getFlags() & Scope::DeclScope) == 0) ||
9003 (S->getEntity() && S->getEntity()->isTransparentContext()))
9004 S = S->getParent();
9005 return S;
9006}
9007
9008NamedDecl*
9009Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
9010 TypeSourceInfo *TInfo, LookupResult &Previous,
9011 MultiTemplateParamsArg TemplateParamListsRef,
9012 bool &AddToScope) {
9013 QualType R = TInfo->getType();
9014
9015 assert(R->isFunctionType())(static_cast <bool> (R->isFunctionType()) ? void (0)
: __assert_fail ("R->isFunctionType()", "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 9015, __extension__ __PRETTY_FUNCTION__))
;
9016 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
9017 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9018
9019 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9020 for (TemplateParameterList *TPL : TemplateParamListsRef)
9021 TemplateParamLists.push_back(TPL);
9022 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
9023 if (!TemplateParamLists.empty() &&
9024 Invented->getDepth() == TemplateParamLists.back()->getDepth())
9025 TemplateParamLists.back() = Invented;
9026 else
9027 TemplateParamLists.push_back(Invented);
9028 }
9029
9030 // TODO: consider using NameInfo for diagnostic.
9031 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9032 DeclarationName Name = NameInfo.getName();
9033 StorageClass SC = getFunctionStorageClass(*this, D);
9034
9035 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
9036 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
9037 diag::err_invalid_thread)
9038 << DeclSpec::getSpecifierName(TSCS);
9039
9040 if (D.isFirstDeclarationOfMember())
9041 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
9042 D.getIdentifierLoc());
9043
9044 bool isFriend = false;
9045 FunctionTemplateDecl *FunctionTemplate = nullptr;
9046 bool isMemberSpecialization = false;
9047 bool isFunctionTemplateSpecialization = false;
9048
9049 bool isDependentClassScopeExplicitSpecialization = false;
9050 bool HasExplicitTemplateArgs = false;
9051 TemplateArgumentListInfo TemplateArgs;
9052
9053 bool isVirtualOkay = false;
9054
9055 DeclContext *OriginalDC = DC;
9056 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9057
9058 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
9059 isVirtualOkay);
9060 if (!NewFD) return nullptr;
9061
9062 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
9063 NewFD->setTopLevelDeclInObjCContainer();
9064
9065 // Set the lexical context. If this is a function-scope declaration, or has a
9066 // C++ scope specifier, or is the object of a friend declaration, the lexical
9067 // context will be different from the semantic context.
9068 NewFD->setLexicalDeclContext(CurContext);
9069
9070 if (IsLocalExternDecl)
9071 NewFD->setLocalExternDecl();
9072
9073 if (getLangOpts().CPlusPlus) {
9074 bool isInline = D.getDeclSpec().isInlineSpecified();
9075 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9076 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9077 isFriend = D.getDeclSpec().isFriendSpecified();
9078 if (isFriend && !isInline && D.isFunctionDefinition()) {
9079 // C++ [class.friend]p5
9080 // A function can be defined in a friend declaration of a
9081 // class . . . . Such a function is implicitly inline.
9082 NewFD->setImplicitlyInline();
9083 }
9084
9085 // If this is a method defined in an __interface, and is not a constructor
9086 // or an overloaded operator, then set the pure flag (isVirtual will already
9087 // return true).
9088 if (const CXXRecordDecl *Parent =
9089 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9090 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9091 NewFD->setPure(true);
9092
9093 // C++ [class.union]p2
9094 // A union can have member functions, but not virtual functions.
9095 if (isVirtual && Parent->isUnion())
9096 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9097 }
9098
9099 SetNestedNameSpecifier(*this, NewFD, D);
9100 isMemberSpecialization = false;
9101 isFunctionTemplateSpecialization = false;
9102 if (D.isInvalidType())
9103 NewFD->setInvalidDecl();
9104
9105 // Match up the template parameter lists with the scope specifier, then
9106 // determine whether we have a template or a template specialization.
9107 bool Invalid = false;
9108 TemplateParameterList *TemplateParams =
9109 MatchTemplateParametersToScopeSpecifier(
9110 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
9111 D.getCXXScopeSpec(),
9112 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
9113 ? D.getName().TemplateId
9114 : nullptr,
9115 TemplateParamLists, isFriend, isMemberSpecialization,
9116 Invalid);
9117 if (TemplateParams) {
9118 // Check that we can declare a template here.
9119 if (CheckTemplateDeclScope(S, TemplateParams))
9120 NewFD->setInvalidDecl();
9121
9122 if (TemplateParams->size() > 0) {
9123 // This is a function template
9124
9125 // A destructor cannot be a template.
9126 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9127 Diag(NewFD->getLocation(), diag::err_destructor_template);
9128 NewFD->setInvalidDecl();
9129 }
9130
9131 // If we're adding a template to a dependent context, we may need to
9132 // rebuilding some of the types used within the template parameter list,
9133 // now that we know what the current instantiation is.
9134 if (DC->isDependentContext()) {
9135 ContextRAII SavedContext(*this, DC);
9136 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
9137 Invalid = true;
9138 }
9139
9140 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
9141 NewFD->getLocation(),
9142 Name, TemplateParams,
9143 NewFD);
9144 FunctionTemplate->setLexicalDeclContext(CurContext);
9145 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
9146
9147 // For source fidelity, store the other template param lists.
9148 if (TemplateParamLists.size() > 1) {
9149 NewFD->setTemplateParameterListsInfo(Context,
9150 ArrayRef<TemplateParameterList *>(TemplateParamLists)
9151 .drop_back(1));
9152 }
9153 } else {
9154 // This is a function template specialization.
9155 isFunctionTemplateSpecialization = true;
9156 // For source fidelity, store all the template param lists.
9157 if (TemplateParamLists.size() > 0)
9158 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9159
9160 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9161 if (isFriend) {
9162 // We want to remove the "template<>", found here.
9163 SourceRange RemoveRange = TemplateParams->getSourceRange();
9164
9165 // If we remove the template<> and the name is not a
9166 // template-id, we're actually silently creating a problem:
9167 // the friend declaration will refer to an untemplated decl,
9168 // and clearly the user wants a template specialization. So
9169 // we need to insert '<>' after the name.
9170 SourceLocation InsertLoc;
9171 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9172 InsertLoc = D.getName().getSourceRange().getEnd();
9173 InsertLoc = getLocForEndOfToken(InsertLoc);
9174 }
9175
9176 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9177 << Name << RemoveRange
9178 << FixItHint::CreateRemoval(RemoveRange)
9179 << FixItHint::CreateInsertion(InsertLoc, "<>");
9180 }
9181 }
9182 } else {
9183 // Check that we can declare a template here.
9184 if (!TemplateParamLists.empty() && isMemberSpecialization &&
9185 CheckTemplateDeclScope(S, TemplateParamLists.back()))
9186 NewFD->setInvalidDecl();
9187
9188 // All template param lists were matched against the scope specifier:
9189 // this is NOT (an explicit specialization of) a template.
9190 if (TemplateParamLists.size() > 0)
9191 // For source fidelity, store all the template param lists.
9192 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9193 }
9194
9195 if (Invalid) {
9196 NewFD->setInvalidDecl();
9197 if (FunctionTemplate)
9198 FunctionTemplate->setInvalidDecl();
9199 }
9200
9201 // C++ [dcl.fct.spec]p5:
9202 // The virtual specifier shall only be used in declarations of
9203 // nonstatic class member functions that appear within a
9204 // member-specification of a class declaration; see 10.3.
9205 //
9206 if (isVirtual && !NewFD->isInvalidDecl()) {
9207 if (!isVirtualOkay) {
9208 Diag(D.getDeclSpec().getVirtualSpecLoc(),
9209 diag::err_virtual_non_function);
9210 } else if (!CurContext->isRecord()) {
9211 // 'virtual' was specified outside of the class.
9212 Diag(D.getDeclSpec().getVirtualSpecLoc(),
9213 diag::err_virtual_out_of_class)
9214 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9215 } else if (NewFD->getDescribedFunctionTemplate()) {
9216 // C++ [temp.mem]p3:
9217 // A member function template shall not be virtual.
9218 Diag(D.getDeclSpec().getVirtualSpecLoc(),
9219 diag::err_virtual_member_function_template)
9220 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9221 } else {
9222 // Okay: Add virtual to the method.
9223 NewFD->setVirtualAsWritten(true);
9224 }
9225
9226 if (getLangOpts().CPlusPlus14 &&
9227 NewFD->getReturnType()->isUndeducedType())
9228 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9229 }
9230
9231 if (getLangOpts().CPlusPlus14 &&
9232 (NewFD->isDependentContext() ||
9233 (isFriend && CurContext->isDependentContext())) &&
9234 NewFD->getReturnType()->isUndeducedType()) {
9235 // If the function template is referenced directly (for instance, as a
9236 // member of the current instantiation), pretend it has a dependent type.
9237 // This is not really justified by the standard, but is the only sane
9238 // thing to do.
9239 // FIXME: For a friend function, we have not marked the function as being
9240 // a friend yet, so 'isDependentContext' on the FD doesn't work.
9241 const FunctionProtoType *FPT =
9242 NewFD->getType()->castAs<FunctionProtoType>();
9243 QualType Result =
9244 SubstAutoType(FPT->getReturnType(), Context.DependentTy);
9245 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9246 FPT->getExtProtoInfo()));
9247 }
9248
9249 // C++ [dcl.fct.spec]p3:
9250 // The inline specifier shall not appear on a block scope function
9251 // declaration.
9252 if (isInline && !NewFD->isInvalidDecl()) {
9253 if (CurContext->isFunctionOrMethod()) {
9254 // 'inline' is not allowed on block scope function declaration.
9255 Diag(D.getDeclSpec().getInlineSpecLoc(),
9256 diag::err_inline_declaration_block_scope) << Name
9257 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9258 }
9259 }
9260
9261 // C++ [dcl.fct.spec]p6:
9262 // The explicit specifier shall be used only in the declaration of a
9263 // constructor or conversion function within its class definition;
9264 // see 12.3.1 and 12.3.2.
9265 if (hasExplicit && !NewFD->isInvalidDecl() &&
9266 !isa<CXXDeductionGuideDecl>(NewFD)) {
9267 if (!CurContext->isRecord()) {
9268 // 'explicit' was specified outside of the class.
9269 Diag(D.getDeclSpec().getExplicitSpecLoc(),
9270 diag::err_explicit_out_of_class)
9271 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9272 } else if (!isa<CXXConstructorDecl>(NewFD) &&
9273 !isa<CXXConversionDecl>(NewFD)) {
9274 // 'explicit' was specified on a function that wasn't a constructor
9275 // or conversion function.
9276 Diag(D.getDeclSpec().getExplicitSpecLoc(),
9277 diag::err_explicit_non_ctor_or_conv_function)
9278 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9279 }
9280 }
9281
9282 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9283 if (ConstexprKind != ConstexprSpecKind::Unspecified) {
9284 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9285 // are implicitly inline.
9286 NewFD->setImplicitlyInline();
9287
9288 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9289 // be either constructors or to return a literal type. Therefore,
9290 // destructors cannot be declared constexpr.
9291 if (isa<CXXDestructorDecl>(NewFD) &&
9292 (!getLangOpts().CPlusPlus20 ||
9293 ConstexprKind == ConstexprSpecKind::Consteval)) {
9294 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9295 << static_cast<int>(ConstexprKind);
9296 NewFD->setConstexprKind(getLangOpts().CPlusPlus20
9297 ? ConstexprSpecKind::Unspecified
9298 : ConstexprSpecKind::Constexpr);
9299 }
9300 // C++20 [dcl.constexpr]p2: An allocation function, or a
9301 // deallocation function shall not be declared with the consteval
9302 // specifier.
9303 if (ConstexprKind == ConstexprSpecKind::Consteval &&
9304 (NewFD->getOverloadedOperator() == OO_New ||
9305 NewFD->getOverloadedOperator() == OO_Array_New ||
9306 NewFD->getOverloadedOperator() == OO_Delete ||
9307 NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9308 Diag(D.getDeclSpec().getConstexprSpecLoc(),
9309 diag::err_invalid_consteval_decl_kind)
9310 << NewFD;
9311 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
9312 }
9313 }
9314
9315 // If __module_private__ was specified, mark the function accordingly.
9316 if (D.getDeclSpec().isModulePrivateSpecified()) {
9317 if (isFunctionTemplateSpecialization) {
9318 SourceLocation ModulePrivateLoc
9319 = D.getDeclSpec().getModulePrivateSpecLoc();
9320 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9321 << 0
9322 << FixItHint::CreateRemoval(ModulePrivateLoc);
9323 } else {
9324 NewFD->setModulePrivate();
9325 if (FunctionTemplate)
9326 FunctionTemplate->setModulePrivate();
9327 }
9328 }
9329
9330 if (isFriend) {
9331 if (FunctionTemplate) {
9332 FunctionTemplate->setObjectOfFriendDecl();
9333 FunctionTemplate->setAccess(AS_public);
9334 }
9335 NewFD->setObjectOfFriendDecl();
9336 NewFD->setAccess(AS_public);
9337 }
9338
9339 // If a function is defined as defaulted or deleted, mark it as such now.
9340 // We'll do the relevant checks on defaulted / deleted functions later.
9341 switch (D.getFunctionDefinitionKind()) {
9342 case FunctionDefinitionKind::Declaration:
9343 case FunctionDefinitionKind::Definition:
9344 break;
9345
9346 case FunctionDefinitionKind::Defaulted:
9347 NewFD->setDefaulted();
9348 break;
9349
9350 case FunctionDefinitionKind::Deleted:
9351 NewFD->setDeletedAsWritten();
9352 break;
9353 }
9354
9355 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9356 D.isFunctionDefinition()) {
9357 // C++ [class.mfct]p2:
9358 // A member function may be defined (8.4) in its class definition, in
9359 // which case it is an inline member function (7.1.2)
9360 NewFD->setImplicitlyInline();
9361 }
9362
9363 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9364 !CurContext->isRecord()) {
9365 // C++ [class.static]p1:
9366 // A data or function member of a class may be declared static
9367 // in a class definition, in which case it is a static member of
9368 // the class.
9369
9370 // Complain about the 'static' specifier if it's on an out-of-line
9371 // member function definition.
9372
9373 // MSVC permits the use of a 'static' storage specifier on an out-of-line
9374 // member function template declaration and class member template
9375 // declaration (MSVC versions before 2015), warn about this.
9376 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9377 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9378 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9379 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9380 ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9381 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9382 }
9383
9384 // C++11 [except.spec]p15:
9385 // A deallocation function with no exception-specification is treated
9386 // as if it were specified with noexcept(true).
9387 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9388 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9389 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9390 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9391 NewFD->setType(Context.getFunctionType(
9392 FPT->getReturnType(), FPT->getParamTypes(),
9393 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9394 }
9395
9396 // Filter out previous declarations that don't match the scope.
9397 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9398 D.getCXXScopeSpec().isNotEmpty() ||
9399 isMemberSpecialization ||
9400 isFunctionTemplateSpecialization);
9401
9402 // Handle GNU asm-label extension (encoded as an attribute).
9403 if (Expr *E = (Expr*) D.getAsmLabel()) {
9404 // The parser guarantees this is a string.
9405 StringLiteral *SE = cast<StringLiteral>(E);
9406 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9407 /*IsLiteralLabel=*/true,
9408 SE->getStrTokenLoc(0)));
9409 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9410 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9411 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9412 if (I != ExtnameUndeclaredIdentifiers.end()) {
9413 if (isDeclExternC(NewFD)) {
9414 NewFD->addAttr(I->second);
9415 ExtnameUndeclaredIdentifiers.erase(I);
9416 } else
9417 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9418 << /*Variable*/0 << NewFD;
9419 }
9420 }
9421
9422 // Copy the parameter declarations from the declarator D to the function
9423 // declaration NewFD, if they are available. First scavenge them into Params.
9424 SmallVector<ParmVarDecl*, 16> Params;
9425 unsigned FTIIdx;
9426 if (D.isFunctionDeclarator(FTIIdx)) {
9427 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9428
9429 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9430 // function that takes no arguments, not a function that takes a
9431 // single void argument.
9432 // We let through "const void" here because Sema::GetTypeForDeclarator
9433 // already checks for that case.
9434 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9435 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9436 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9437 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 ?\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 9437, __extension__ __PRETTY_FUNCTION__))
;
9438 Param->setDeclContext(NewFD);
9439 Params.push_back(Param);
9440
9441 if (Param->isInvalidDecl())
9442 NewFD->setInvalidDecl();
9443 }
9444 }
9445
9446 if (!getLangOpts().CPlusPlus) {
9447 // In C, find all the tag declarations from the prototype and move them
9448 // into the function DeclContext. Remove them from the surrounding tag
9449 // injection context of the function, which is typically but not always
9450 // the TU.
9451 DeclContext *PrototypeTagContext =
9452 getTagInjectionContext(NewFD->getLexicalDeclContext());
9453 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9454 auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9455
9456 // We don't want to reparent enumerators. Look at their parent enum
9457 // instead.
9458 if (!TD) {
9459 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9460 TD = cast<EnumDecl>(ECD->getDeclContext());
9461 }
9462 if (!TD)
9463 continue;
9464 DeclContext *TagDC = TD->getLexicalDeclContext();
9465 if (!TagDC->containsDecl(TD))
9466 continue;
9467 TagDC->removeDecl(TD);
9468 TD->setDeclContext(NewFD);
9469 NewFD->addDecl(TD);
9470
9471 // Preserve the lexical DeclContext if it is not the surrounding tag
9472 // injection context of the FD. In this example, the semantic context of
9473 // E will be f and the lexical context will be S, while both the
9474 // semantic and lexical contexts of S will be f:
9475 // void f(struct S { enum E { a } f; } s);
9476 if (TagDC != PrototypeTagContext)
9477 TD->setLexicalDeclContext(TagDC);
9478 }
9479 }
9480 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9481 // When we're declaring a function with a typedef, typeof, etc as in the
9482 // following example, we'll need to synthesize (unnamed)
9483 // parameters for use in the declaration.
9484 //
9485 // @code
9486 // typedef void fn(int);
9487 // fn f;
9488 // @endcode
9489
9490 // Synthesize a parameter for each argument type.
9491 for (const auto &AI : FT->param_types()) {
9492 ParmVarDecl *Param =
9493 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9494 Param->setScopeInfo(0, Params.size());
9495 Params.push_back(Param);
9496 }
9497 } else {
9498 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 9499, __extension__ __PRETTY_FUNCTION__))
9499 "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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 9499, __extension__ __PRETTY_FUNCTION__))
;
9500 }
9501
9502 // Finally, we know we have the right number of parameters, install them.
9503 NewFD->setParams(Params);
9504
9505 if (D.getDeclSpec().isNoreturnSpecified())
9506 NewFD->addAttr(C11NoReturnAttr::Create(Context,
9507 D.getDeclSpec().getNoreturnSpecLoc(),
9508 AttributeCommonInfo::AS_Keyword));
9509
9510 // Functions returning a variably modified type violate C99 6.7.5.2p2
9511 // because all functions have linkage.
9512 if (!NewFD->isInvalidDecl() &&
9513 NewFD->getReturnType()->isVariablyModifiedType()) {
9514 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9515 NewFD->setInvalidDecl();
9516 }
9517
9518 // Apply an implicit SectionAttr if '#pragma clang section text' is active
9519 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9520 !NewFD->hasAttr<SectionAttr>())
9521 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9522 Context, PragmaClangTextSection.SectionName,
9523 PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9524
9525 // Apply an implicit SectionAttr if #pragma code_seg is active.
9526 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9527 !NewFD->hasAttr<SectionAttr>()) {
9528 NewFD->addAttr(SectionAttr::CreateImplicit(
9529 Context, CodeSegStack.CurrentValue->getString(),
9530 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9531 SectionAttr::Declspec_allocate));
9532 if (UnifySection(CodeSegStack.CurrentValue->getString(),
9533 ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9534 ASTContext::PSF_Read,
9535 NewFD))
9536 NewFD->dropAttr<SectionAttr>();
9537 }
9538
9539 // Apply an implicit CodeSegAttr from class declspec or
9540 // apply an implicit SectionAttr from #pragma code_seg if active.
9541 if (!NewFD->hasAttr<CodeSegAttr>()) {
9542 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9543 D.isFunctionDefinition())) {
9544 NewFD->addAttr(SAttr);
9545 }
9546 }
9547
9548 // Handle attributes.
9549 ProcessDeclAttributes(S, NewFD, D);
9550
9551 if (getLangOpts().OpenCL) {
9552 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9553 // type declaration will generate a compilation error.
9554 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9555 if (AddressSpace != LangAS::Default) {
9556 Diag(NewFD->getLocation(),
9557 diag::err_opencl_return_value_with_address_space);
9558 NewFD->setInvalidDecl();
9559 }
9560 }
9561
9562 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice))
9563 checkDeviceDecl(NewFD, D.getBeginLoc());
9564
9565 if (!getLangOpts().CPlusPlus) {
9566 // Perform semantic checking on the function declaration.
9567 if (!NewFD->isInvalidDecl() && NewFD->isMain())
9568 CheckMain(NewFD, D.getDeclSpec());
9569
9570 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9571 CheckMSVCRTEntryPoint(NewFD);
9572
9573 if (!NewFD->isInvalidDecl())
9574 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9575 isMemberSpecialization));
9576 else if (!Previous.empty())
9577 // Recover gracefully from an invalid redeclaration.
9578 D.setRedeclaration(true);
9579 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 9581, __extension__ __PRETTY_FUNCTION__))
9580 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 9581, __extension__ __PRETTY_FUNCTION__))
9581 "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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 9581, __extension__ __PRETTY_FUNCTION__))
;
9582
9583 // Diagnose no-prototype function declarations with calling conventions that
9584 // don't support variadic calls. Only do this in C and do it after merging
9585 // possibly prototyped redeclarations.
9586 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9587 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9588 CallingConv CC = FT->getExtInfo().getCC();
9589 if (!supportsVariadicCall(CC)) {
9590 // Windows system headers sometimes accidentally use stdcall without
9591 // (void) parameters, so we relax this to a warning.
9592 int DiagID =
9593 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9594 Diag(NewFD->getLocation(), DiagID)
9595 << FunctionType::getNameForCallConv(CC);
9596 }
9597 }
9598
9599 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9600 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9601 checkNonTrivialCUnion(NewFD->getReturnType(),
9602 NewFD->getReturnTypeSourceRange().getBegin(),
9603 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9604 } else {
9605 // C++11 [replacement.functions]p3:
9606 // The program's definitions shall not be specified as inline.
9607 //
9608 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9609 //
9610 // Suppress the diagnostic if the function is __attribute__((used)), since
9611 // that forces an external definition to be emitted.
9612 if (D.getDeclSpec().isInlineSpecified() &&
9613 NewFD->isReplaceableGlobalAllocationFunction() &&
9614 !NewFD->hasAttr<UsedAttr>())
9615 Diag(D.getDeclSpec().getInlineSpecLoc(),
9616 diag::ext_operator_new_delete_declared_inline)
9617 << NewFD->getDeclName();
9618
9619 // If the declarator is a template-id, translate the parser's template
9620 // argument list into our AST format.
9621 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9622 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9623 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9624 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9625 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9626 TemplateId->NumArgs);
9627 translateTemplateArguments(TemplateArgsPtr,
9628 TemplateArgs);
9629
9630 HasExplicitTemplateArgs = true;
9631
9632 if (NewFD->isInvalidDecl()) {
9633 HasExplicitTemplateArgs = false;
9634 } else if (FunctionTemplate) {
9635 // Function template with explicit template arguments.
9636 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9637 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9638
9639 HasExplicitTemplateArgs = false;
9640 } else {
9641 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 9643, __extension__ __PRETTY_FUNCTION__))
9642 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 9643, __extension__ __PRETTY_FUNCTION__))
9643 "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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 9643, __extension__ __PRETTY_FUNCTION__))
;
9644 // "friend void foo<>(int);" is an implicit specialization decl.
9645 isFunctionTemplateSpecialization = true;
9646 }
9647 } else if (isFriend && isFunctionTemplateSpecialization) {
9648 // This combination is only possible in a recovery case; the user
9649 // wrote something like:
9650 // template <> friend void foo(int);
9651 // which we're recovering from as if the user had written:
9652 // friend void foo<>(int);
9653 // Go ahead and fake up a template id.
9654 HasExplicitTemplateArgs = true;
9655 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9656 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9657 }
9658
9659 // We do not add HD attributes to specializations here because
9660 // they may have different constexpr-ness compared to their
9661 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9662 // may end up with different effective targets. Instead, a
9663 // specialization inherits its target attributes from its template
9664 // in the CheckFunctionTemplateSpecialization() call below.
9665 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9666 maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9667
9668 // If it's a friend (and only if it's a friend), it's possible
9669 // that either the specialized function type or the specialized
9670 // template is dependent, and therefore matching will fail. In
9671 // this case, don't check the specialization yet.
9672 if (isFunctionTemplateSpecialization && isFriend &&
9673 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9674 TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
9675 TemplateArgs.arguments()))) {
9676 assert(HasExplicitTemplateArgs &&(static_cast <bool> (HasExplicitTemplateArgs &&
"friend function specialization without template args") ? void
(0) : __assert_fail ("HasExplicitTemplateArgs && \"friend function specialization without template args\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 9677, __extension__ __PRETTY_FUNCTION__))
9677 "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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 9677, __extension__ __PRETTY_FUNCTION__))
;
9678 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9679 Previous))
9680 NewFD->setInvalidDecl();
9681 } else if (isFunctionTemplateSpecialization) {
9682 if (CurContext->isDependentContext() && CurContext->isRecord()
9683 && !isFriend) {
9684 isDependentClassScopeExplicitSpecialization = true;
9685 } else if (!NewFD->isInvalidDecl() &&
9686 CheckFunctionTemplateSpecialization(
9687 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9688 Previous))
9689 NewFD->setInvalidDecl();
9690
9691 // C++ [dcl.stc]p1:
9692 // A storage-class-specifier shall not be specified in an explicit
9693 // specialization (14.7.3)
9694 FunctionTemplateSpecializationInfo *Info =
9695 NewFD->getTemplateSpecializationInfo();
9696 if (Info && SC != SC_None) {
9697 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9698 Diag(NewFD->getLocation(),
9699 diag::err_explicit_specialization_inconsistent_storage_class)
9700 << SC
9701 << FixItHint::CreateRemoval(
9702 D.getDeclSpec().getStorageClassSpecLoc());
9703
9704 else
9705 Diag(NewFD->getLocation(),
9706 diag::ext_explicit_specialization_storage_class)
9707 << FixItHint::CreateRemoval(
9708 D.getDeclSpec().getStorageClassSpecLoc());
9709 }
9710 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9711 if (CheckMemberSpecialization(NewFD, Previous))
9712 NewFD->setInvalidDecl();
9713 }
9714
9715 // Perform semantic checking on the function declaration.
9716 if (!isDependentClassScopeExplicitSpecialization) {
9717 if (!NewFD->isInvalidDecl() && NewFD->isMain())
9718 CheckMain(NewFD, D.getDeclSpec());
9719
9720 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9721 CheckMSVCRTEntryPoint(NewFD);
9722
9723 if (!NewFD->isInvalidDecl())
9724 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9725 isMemberSpecialization));
9726 else if (!Previous.empty())
9727 // Recover gracefully from an invalid redeclaration.
9728 D.setRedeclaration(true);
9729 }
9730
9731 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 9733, __extension__ __PRETTY_FUNCTION__))
9732 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 9733, __extension__ __PRETTY_FUNCTION__))
9733 "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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 9733, __extension__ __PRETTY_FUNCTION__))
;
9734
9735 NamedDecl *PrincipalDecl = (FunctionTemplate
9736 ? cast<NamedDecl>(FunctionTemplate)
9737 : NewFD);
9738
9739 if (isFriend && NewFD->getPreviousDecl()) {
9740 AccessSpecifier Access = AS_public;
9741 if (!NewFD->isInvalidDecl())
9742 Access = NewFD->getPreviousDecl()->getAccess();
9743
9744 NewFD->setAccess(Access);
9745 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9746 }
9747
9748 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9749 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9750 PrincipalDecl->setNonMemberOperator();
9751
9752 // If we have a function template, check the template parameter
9753 // list. This will check and merge default template arguments.
9754 if (FunctionTemplate) {
9755 FunctionTemplateDecl *PrevTemplate =
9756 FunctionTemplate->getPreviousDecl();
9757 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9758 PrevTemplate ? PrevTemplate->getTemplateParameters()
9759 : nullptr,
9760 D.getDeclSpec().isFriendSpecified()
9761 ? (D.isFunctionDefinition()
9762 ? TPC_FriendFunctionTemplateDefinition
9763 : TPC_FriendFunctionTemplate)
9764 : (D.getCXXScopeSpec().isSet() &&
9765 DC && DC->isRecord() &&
9766 DC->isDependentContext())
9767 ? TPC_ClassTemplateMember
9768 : TPC_FunctionTemplate);
9769 }
9770
9771 if (NewFD->isInvalidDecl()) {
9772 // Ignore all the rest of this.
9773 } else if (!D.isRedeclaration()) {
9774 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9775 AddToScope };
9776 // Fake up an access specifier if it's supposed to be a class member.
9777 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9778 NewFD->setAccess(AS_public);
9779
9780 // Qualified decls generally require a previous declaration.
9781 if (D.getCXXScopeSpec().isSet()) {
9782 // ...with the major exception of templated-scope or
9783 // dependent-scope friend declarations.
9784
9785 // TODO: we currently also suppress this check in dependent
9786 // contexts because (1) the parameter depth will be off when
9787 // matching friend templates and (2) we might actually be
9788 // selecting a friend based on a dependent factor. But there
9789 // are situations where these conditions don't apply and we
9790 // can actually do this check immediately.
9791 //
9792 // Unless the scope is dependent, it's always an error if qualified
9793 // redeclaration lookup found nothing at all. Diagnose that now;
9794 // nothing will diagnose that error later.
9795 if (isFriend &&
9796 (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9797 (!Previous.empty() && CurContext->isDependentContext()))) {
9798 // ignore these
9799 } else if (NewFD->isCPUDispatchMultiVersion() ||
9800 NewFD->isCPUSpecificMultiVersion()) {
9801 // ignore this, we allow the redeclaration behavior here to create new
9802 // versions of the function.
9803 } else {
9804 // The user tried to provide an out-of-line definition for a
9805 // function that is a member of a class or namespace, but there
9806 // was no such member function declared (C++ [class.mfct]p2,
9807 // C++ [namespace.memdef]p2). For example:
9808 //
9809 // class X {
9810 // void f() const;
9811 // };
9812 //
9813 // void X::f() { } // ill-formed
9814 //
9815 // Complain about this problem, and attempt to suggest close
9816 // matches (e.g., those that differ only in cv-qualifiers and
9817 // whether the parameter types are references).
9818
9819 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9820 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9821 AddToScope = ExtraArgs.AddToScope;
9822 return Result;
9823 }
9824 }
9825
9826 // Unqualified local friend declarations are required to resolve
9827 // to something.
9828 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9829 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9830 *this, Previous, NewFD, ExtraArgs, true, S)) {
9831 AddToScope = ExtraArgs.AddToScope;
9832 return Result;
9833 }
9834 }
9835 } else if (!D.isFunctionDefinition() &&
9836 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9837 !isFriend && !isFunctionTemplateSpecialization &&
9838 !isMemberSpecialization) {
9839 // An out-of-line member function declaration must also be a
9840 // definition (C++ [class.mfct]p2).
9841 // Note that this is not the case for explicit specializations of
9842 // function templates or member functions of class templates, per
9843 // C++ [temp.expl.spec]p2. We also allow these declarations as an
9844 // extension for compatibility with old SWIG code which likes to
9845 // generate them.
9846 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9847 << D.getCXXScopeSpec().getRange();
9848 }
9849 }
9850
9851 // If this is the first declaration of a library builtin function, add
9852 // attributes as appropriate.
9853 if (!D.isRedeclaration() &&
9854 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
9855 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
9856 if (unsigned BuiltinID = II->getBuiltinID()) {
9857 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
9858 // Validate the type matches unless this builtin is specified as
9859 // matching regardless of its declared type.
9860 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
9861 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9862 } else {
9863 ASTContext::GetBuiltinTypeError Error;
9864 LookupNecessaryTypesForBuiltin(S, BuiltinID);
9865 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
9866
9867 if (!Error && !BuiltinType.isNull() &&
9868 Context.hasSameFunctionTypeIgnoringExceptionSpec(
9869 NewFD->getType(), BuiltinType))
9870 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9871 }
9872 } else if (BuiltinID == Builtin::BI__GetExceptionInfo &&
9873 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9874 // FIXME: We should consider this a builtin only in the std namespace.
9875 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9876 }
9877 }
9878 }
9879 }
9880
9881 ProcessPragmaWeak(S, NewFD);
9882 checkAttributesAfterMerging(*this, *NewFD);
9883
9884 AddKnownFunctionAttributes(NewFD);
9885
9886 if (NewFD->hasAttr<OverloadableAttr>() &&
9887 !NewFD->getType()->getAs<FunctionProtoType>()) {
9888 Diag(NewFD->getLocation(),
9889 diag::err_attribute_overloadable_no_prototype)
9890 << NewFD;
9891
9892 // Turn this into a variadic function with no parameters.
9893 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9894 FunctionProtoType::ExtProtoInfo EPI(
9895 Context.getDefaultCallingConvention(true, false));
9896 EPI.Variadic = true;
9897 EPI.ExtInfo = FT->getExtInfo();
9898
9899 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9900 NewFD->setType(R);
9901 }
9902
9903 // If there's a #pragma GCC visibility in scope, and this isn't a class
9904 // member, set the visibility of this function.
9905 if (!DC->isRecord() && NewFD->isExternallyVisible())
9906 AddPushedVisibilityAttribute(NewFD);
9907
9908 // If there's a #pragma clang arc_cf_code_audited in scope, consider
9909 // marking the function.
9910 AddCFAuditedAttribute(NewFD);
9911
9912 // If this is a function definition, check if we have to apply optnone due to
9913 // a pragma.
9914 if(D.isFunctionDefinition())
9915 AddRangeBasedOptnone(NewFD);
9916
9917 // If this is the first declaration of an extern C variable, update
9918 // the map of such variables.
9919 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9920 isIncompleteDeclExternC(*this, NewFD))
9921 RegisterLocallyScopedExternCDecl(NewFD, S);
9922
9923 // Set this FunctionDecl's range up to the right paren.
9924 NewFD->setRangeEnd(D.getSourceRange().getEnd());
9925
9926 if (D.isRedeclaration() && !Previous.empty()) {
9927 NamedDecl *Prev = Previous.getRepresentativeDecl();
9928 checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9929 isMemberSpecialization ||
9930 isFunctionTemplateSpecialization,
9931 D.isFunctionDefinition());
9932 }
9933
9934 if (getLangOpts().CUDA) {
9935 IdentifierInfo *II = NewFD->getIdentifier();
9936 if (II && II->isStr(getCudaConfigureFuncName()) &&
9937 !NewFD->isInvalidDecl() &&
9938 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9939 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
9940 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9941 << getCudaConfigureFuncName();
9942 Context.setcudaConfigureCallDecl(NewFD);
9943 }
9944
9945 // Variadic functions, other than a *declaration* of printf, are not allowed
9946 // in device-side CUDA code, unless someone passed
9947 // -fcuda-allow-variadic-functions.
9948 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9949 (NewFD->hasAttr<CUDADeviceAttr>() ||
9950 NewFD->hasAttr<CUDAGlobalAttr>()) &&
9951 !(II && II->isStr("printf") && NewFD->isExternC() &&
9952 !D.isFunctionDefinition())) {
9953 Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9954 }
9955 }
9956
9957 MarkUnusedFileScopedDecl(NewFD);
9958
9959
9960
9961 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
9962 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9963 if ((getLangOpts().OpenCLVersion >= 120)
9964 && (SC == SC_Static)) {
9965 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9966 D.setInvalidType();
9967 }
9968
9969 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9970 if (!NewFD->getReturnType()->isVoidType()) {
9971 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9972 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9973 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9974 : FixItHint());
9975 D.setInvalidType();
9976 }
9977
9978 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9979 for (auto Param : NewFD->parameters())
9980 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9981
9982 if (getLangOpts().OpenCLCPlusPlus) {
9983 if (DC->isRecord()) {
9984 Diag(D.getIdentifierLoc(), diag::err_method_kernel);
9985 D.setInvalidType();
9986 }
9987 if (FunctionTemplate) {
9988 Diag(D.getIdentifierLoc(), diag::err_template_kernel);
9989 D.setInvalidType();
9990 }
9991 }
9992 }
9993
9994 if (getLangOpts().CPlusPlus) {
9995 if (FunctionTemplate) {
9996 if (NewFD->isInvalidDecl())
9997 FunctionTemplate->setInvalidDecl();
9998 return FunctionTemplate;
9999 }
10000
10001 if (isMemberSpecialization && !NewFD->isInvalidDecl())
10002 CompleteMemberSpecialization(NewFD, Previous);
10003 }
10004
10005 for (const ParmVarDecl *Param : NewFD->parameters()) {
10006 QualType PT = Param->getType();
10007
10008 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10009 // types.
10010 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
10011 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10012 QualType ElemTy = PipeTy->getElementType();
10013 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
10014 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
10015 D.setInvalidType();
10016 }
10017 }
10018 }
10019 }
10020
10021 // Here we have an function template explicit specialization at class scope.
10022 // The actual specialization will be postponed to template instatiation
10023 // time via the ClassScopeFunctionSpecializationDecl node.
10024 if (isDependentClassScopeExplicitSpecialization) {
10025 ClassScopeFunctionSpecializationDecl *NewSpec =
10026 ClassScopeFunctionSpecializationDecl::Create(
10027 Context, CurContext, NewFD->getLocation(),
10028 cast<CXXMethodDecl>(NewFD),
10029 HasExplicitTemplateArgs, TemplateArgs);
10030 CurContext->addDecl(NewSpec);
10031 AddToScope = false;
10032 }
10033
10034 // Diagnose availability attributes. Availability cannot be used on functions
10035 // that are run during load/unload.
10036 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
10037 if (NewFD->hasAttr<ConstructorAttr>()) {
10038 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10039 << 1;
10040 NewFD->dropAttr<AvailabilityAttr>();
10041 }
10042 if (NewFD->hasAttr<DestructorAttr>()) {
10043 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10044 << 2;
10045 NewFD->dropAttr<AvailabilityAttr>();
10046 }
10047 }
10048
10049 // Diagnose no_builtin attribute on function declaration that are not a
10050 // definition.
10051 // FIXME: We should really be doing this in
10052 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10053 // the FunctionDecl and at this point of the code
10054 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10055 // because Sema::ActOnStartOfFunctionDef has not been called yet.
10056 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
10057 switch (D.getFunctionDefinitionKind()) {
10058 case FunctionDefinitionKind::Defaulted:
10059 case FunctionDefinitionKind::Deleted:
10060 Diag(NBA->getLocation(),
10061 diag::err_attribute_no_builtin_on_defaulted_deleted_function)
10062 << NBA->getSpelling();
10063 break;
10064 case FunctionDefinitionKind::Declaration:
10065 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10066 << NBA->getSpelling();
10067 break;
10068 case FunctionDefinitionKind::Definition:
10069 break;
10070 }
10071
10072 return NewFD;
10073}
10074
10075/// Return a CodeSegAttr from a containing class. The Microsoft docs say
10076/// when __declspec(code_seg) "is applied to a class, all member functions of
10077/// the class and nested classes -- this includes compiler-generated special
10078/// member functions -- are put in the specified segment."
10079/// The actual behavior is a little more complicated. The Microsoft compiler
10080/// won't check outer classes if there is an active value from #pragma code_seg.
10081/// The CodeSeg is always applied from the direct parent but only from outer
10082/// classes when the #pragma code_seg stack is empty. See:
10083/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10084/// available since MS has removed the page.
10085static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
10086 const auto *Method = dyn_cast<CXXMethodDecl>(FD);
10087 if (!Method)
10088 return nullptr;
10089 const CXXRecordDecl *Parent = Method->getParent();
10090 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10091 Attr *NewAttr = SAttr->clone(S.getASTContext());
10092 NewAttr->setImplicit(true);
10093 return NewAttr;
10094 }
10095
10096 // The Microsoft compiler won't check outer classes for the CodeSeg
10097 // when the #pragma code_seg stack is active.
10098 if (S.CodeSegStack.CurrentValue)
10099 return nullptr;
10100
10101 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
10102 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10103 Attr *NewAttr = SAttr->clone(S.getASTContext());
10104 NewAttr->setImplicit(true);
10105 return NewAttr;
10106 }
10107 }
10108 return nullptr;
10109}
10110
10111/// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
10112/// containing class. Otherwise it will return implicit SectionAttr if the
10113/// function is a definition and there is an active value on CodeSegStack
10114/// (from the current #pragma code-seg value).
10115///
10116/// \param FD Function being declared.
10117/// \param IsDefinition Whether it is a definition or just a declarartion.
10118/// \returns A CodeSegAttr or SectionAttr to apply to the function or
10119/// nullptr if no attribute should be added.
10120Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
10121 bool IsDefinition) {
10122 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
10123 return A;
10124 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
10125 CodeSegStack.CurrentValue)
10126 return SectionAttr::CreateImplicit(
10127 getASTContext(), CodeSegStack.CurrentValue->getString(),
10128 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
10129 SectionAttr::Declspec_allocate);
10130 return nullptr;
10131}
10132
10133/// Determines if we can perform a correct type check for \p D as a
10134/// redeclaration of \p PrevDecl. If not, we can generally still perform a
10135/// best-effort check.
10136///
10137/// \param NewD The new declaration.
10138/// \param OldD The old declaration.
10139/// \param NewT The portion of the type of the new declaration to check.
10140/// \param OldT The portion of the type of the old declaration to check.
10141bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
10142 QualType NewT, QualType OldT) {
10143 if (!NewD->getLexicalDeclContext()->isDependentContext())
64
Assuming the condition is true
65
Taking true branch
10144 return true;
66
Returning the value 1, which participates in a condition later
10145
10146 // For dependently-typed local extern declarations and friends, we can't
10147 // perform a correct type check in general until instantiation:
10148 //
10149 // int f();
10150 // template<typename T> void g() { T f(); }
10151 //
10152 // (valid if g() is only instantiated with T = int).
10153 if (NewT->isDependentType() &&
10154 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
10155 return false;
10156
10157 // Similarly, if the previous declaration was a dependent local extern
10158 // declaration, we don't really know its type yet.
10159 if (OldT->isDependentType() && OldD->isLocalExternDecl())
10160 return false;
10161
10162 return true;
10163}
10164
10165/// Checks if the new declaration declared in dependent context must be
10166/// put in the same redeclaration chain as the specified declaration.
10167///
10168/// \param D Declaration that is checked.
10169/// \param PrevDecl Previous declaration found with proper lookup method for the
10170/// same declaration name.
10171/// \returns True if D must be added to the redeclaration chain which PrevDecl
10172/// belongs to.
10173///
10174bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
10175 if (!D->getLexicalDeclContext()->isDependentContext())
10176 return true;
10177
10178 // Don't chain dependent friend function definitions until instantiation, to
10179 // permit cases like
10180 //
10181 // void func();
10182 // template<typename T> class C1 { friend void func() {} };
10183 // template<typename T> class C2 { friend void func() {} };
10184 //
10185 // ... which is valid if only one of C1 and C2 is ever instantiated.
10186 //
10187 // FIXME: This need only apply to function definitions. For now, we proxy
10188 // this by checking for a file-scope function. We do not want this to apply
10189 // to friend declarations nominating member functions, because that gets in
10190 // the way of access checks.
10191 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
10192 return false;
10193
10194 auto *VD = dyn_cast<ValueDecl>(D);
10195 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
10196 return !VD || !PrevVD ||
10197 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
10198 PrevVD->getType());
10199}
10200
10201/// Check the target attribute of the function for MultiVersion
10202/// validity.
10203///
10204/// Returns true if there was an error, false otherwise.
10205static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
10206 const auto *TA = FD->getAttr<TargetAttr>();
10207 assert(TA && "MultiVersion Candidate requires a target attribute")(static_cast <bool> (TA && "MultiVersion Candidate requires a target attribute"
) ? void (0) : __assert_fail ("TA && \"MultiVersion Candidate requires a target attribute\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 10207, __extension__ __PRETTY_FUNCTION__))
;
10208 ParsedTargetAttr ParseInfo = TA->parse();
10209 const TargetInfo &TargetInfo = S.Context.getTargetInfo();
10210 enum ErrType { Feature = 0, Architecture = 1 };
10211
10212 if (!ParseInfo.Architecture.empty() &&
10213 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
10214 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10215 << Architecture << ParseInfo.Architecture;
10216 return true;
10217 }
10218
10219 for (const auto &Feat : ParseInfo.Features) {
10220 auto BareFeat = StringRef{Feat}.substr(1);
10221 if (Feat[0] == '-') {
10222 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10223 << Feature << ("no-" + BareFeat).str();
10224 return true;
10225 }
10226
10227 if (!TargetInfo.validateCpuSupports(BareFeat) ||
10228 !TargetInfo.isValidFeatureName(BareFeat)) {
10229 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10230 << Feature << BareFeat;
10231 return true;
10232 }
10233 }
10234 return false;
10235}
10236
10237// Provide a white-list of attributes that are allowed to be combined with
10238// multiversion functions.
10239static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
10240 MultiVersionKind MVType) {
10241 // Note: this list/diagnosis must match the list in
10242 // checkMultiversionAttributesAllSame.
10243 switch (Kind) {
10244 default:
10245 return false;
10246 case attr::Used:
10247 return MVType == MultiVersionKind::Target;
10248 case attr::NonNull:
10249 case attr::NoThrow:
10250 return true;
10251 }
10252}
10253
10254static bool checkNonMultiVersionCompatAttributes(Sema &S,
10255 const FunctionDecl *FD,
10256 const FunctionDecl *CausedFD,
10257 MultiVersionKind MVType) {
10258 bool IsCPUSpecificCPUDispatchMVType =
10259 MVType == MultiVersionKind::CPUDispatch ||
10260 MVType == MultiVersionKind::CPUSpecific;
10261 const auto Diagnose = [FD, CausedFD, IsCPUSpecificCPUDispatchMVType](
10262 Sema &S, const Attr *A) {
10263 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
10264 << IsCPUSpecificCPUDispatchMVType << A;
10265 if (CausedFD)
10266 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
10267 return true;
10268 };
10269
10270 for (const Attr *A : FD->attrs()) {
10271 switch (A->getKind()) {
10272 case attr::CPUDispatch:
10273 case attr::CPUSpecific:
10274 if (MVType != MultiVersionKind::CPUDispatch &&
10275 MVType != MultiVersionKind::CPUSpecific)
10276 return Diagnose(S, A);
10277 break;
10278 case attr::Target:
10279 if (MVType != MultiVersionKind::Target)
10280 return Diagnose(S, A);
10281 break;
10282 default:
10283 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType))
10284 return Diagnose(S, A);
10285 break;
10286 }
10287 }
10288 return false;
10289}
10290
10291bool Sema::areMultiversionVariantFunctionsCompatible(
10292 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10293 const PartialDiagnostic &NoProtoDiagID,
10294 const PartialDiagnosticAt &NoteCausedDiagIDAt,
10295 const PartialDiagnosticAt &NoSupportDiagIDAt,
10296 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10297 bool ConstexprSupported, bool CLinkageMayDiffer) {
10298 enum DoesntSupport {
10299 FuncTemplates = 0,
10300 VirtFuncs = 1,
10301 DeducedReturn = 2,
10302 Constructors = 3,
10303 Destructors = 4,
10304 DeletedFuncs = 5,
10305 DefaultedFuncs = 6,
10306 ConstexprFuncs = 7,
10307 ConstevalFuncs = 8,
10308 };
10309 enum Different {
10310 CallingConv = 0,
10311 ReturnType = 1,
10312 ConstexprSpec = 2,
10313 InlineSpec = 3,
10314 StorageClass = 4,
10315 Linkage = 5,
10316 };
10317
10318 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
10319 !OldFD->getType()->getAs<FunctionProtoType>()) {
10320 Diag(OldFD->getLocation(), NoProtoDiagID);
10321 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10322 return true;
10323 }
10324
10325 if (NoProtoDiagID.getDiagID() != 0 &&
10326 !NewFD->getType()->getAs<FunctionProtoType>())
10327 return Diag(NewFD->getLocation(), NoProtoDiagID);
10328
10329 if (!TemplatesSupported &&
10330 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10331 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10332 << FuncTemplates;
10333
10334 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
10335 if (NewCXXFD->isVirtual())
10336 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10337 << VirtFuncs;
10338
10339 if (isa<CXXConstructorDecl>(NewCXXFD))
10340 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10341 << Constructors;
10342
10343 if (isa<CXXDestructorDecl>(NewCXXFD))
10344 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10345 << Destructors;
10346 }
10347
10348 if (NewFD->isDeleted())
10349 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10350 << DeletedFuncs;
10351
10352 if (NewFD->isDefaulted())
10353 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10354 << DefaultedFuncs;
10355
10356 if (!ConstexprSupported && NewFD->isConstexpr())
10357 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10358 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
10359
10360 QualType NewQType = Context.getCanonicalType(NewFD->getType());
10361 const auto *NewType = cast<FunctionType>(NewQType);
10362 QualType NewReturnType = NewType->getReturnType();
10363
10364 if (NewReturnType->isUndeducedType())
10365 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10366 << DeducedReturn;
10367
10368 // Ensure the return type is identical.
10369 if (OldFD) {
10370 QualType OldQType = Context.getCanonicalType(OldFD->getType());
10371 const auto *OldType = cast<FunctionType>(OldQType);
10372 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
10373 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
10374
10375 if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
10376 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
10377
10378 QualType OldReturnType = OldType->getReturnType();
10379
10380 if (OldReturnType != NewReturnType)
10381 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
10382
10383 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
10384 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
10385
10386 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
10387 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
10388
10389 if (OldFD->getStorageClass() != NewFD->getStorageClass())
10390 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass;
10391
10392 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
10393 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
10394
10395 if (CheckEquivalentExceptionSpec(
10396 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
10397 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
10398 return true;
10399 }
10400 return false;
10401}
10402
10403static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
10404 const FunctionDecl *NewFD,
10405 bool CausesMV,
10406 MultiVersionKind MVType) {
10407 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10408 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10409 if (OldFD)
10410 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10411 return true;
10412 }
10413
10414 bool IsCPUSpecificCPUDispatchMVType =
10415 MVType == MultiVersionKind::CPUDispatch ||
10416 MVType == MultiVersionKind::CPUSpecific;
10417
10418 if (CausesMV && OldFD &&
10419 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVType))
10420 return true;
10421
10422 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVType))
10423 return true;
10424
10425 // Only allow transition to MultiVersion if it hasn't been used.
10426 if (OldFD && CausesMV && OldFD->isUsed(false))
10427 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10428
10429 return S.areMultiversionVariantFunctionsCompatible(
10430 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
10431 PartialDiagnosticAt(NewFD->getLocation(),
10432 S.PDiag(diag::note_multiversioning_caused_here)),
10433 PartialDiagnosticAt(NewFD->getLocation(),
10434 S.PDiag(diag::err_multiversion_doesnt_support)
10435 << IsCPUSpecificCPUDispatchMVType),
10436 PartialDiagnosticAt(NewFD->getLocation(),
10437 S.PDiag(diag::err_multiversion_diff)),
10438 /*TemplatesSupported=*/false,
10439 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType,
10440 /*CLinkageMayDiffer=*/false);
10441}
10442
10443/// Check the validity of a multiversion function declaration that is the
10444/// first of its kind. Also sets the multiversion'ness' of the function itself.
10445///
10446/// This sets NewFD->isInvalidDecl() to true if there was an error.
10447///
10448/// Returns true if there was an error, false otherwise.
10449static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10450 MultiVersionKind MVType,
10451 const TargetAttr *TA) {
10452 assert(MVType != MultiVersionKind::None &&(static_cast <bool> (MVType != MultiVersionKind::None &&
"Function lacks multiversion attribute") ? void (0) : __assert_fail
("MVType != MultiVersionKind::None && \"Function lacks multiversion attribute\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 10453, __extension__ __PRETTY_FUNCTION__))
10453 "Function lacks multiversion attribute")(static_cast <bool> (MVType != MultiVersionKind::None &&
"Function lacks multiversion attribute") ? void (0) : __assert_fail
("MVType != MultiVersionKind::None && \"Function lacks multiversion attribute\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 10453, __extension__ __PRETTY_FUNCTION__))
;
10454
10455 // Target only causes MV if it is default, otherwise this is a normal
10456 // function.
10457 if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
10458 return false;
10459
10460 if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10461 FD->setInvalidDecl();
10462 return true;
10463 }
10464
10465 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
10466 FD->setInvalidDecl();
10467 return true;
10468 }
10469
10470 FD->setIsMultiVersion();
10471 return false;
10472}
10473
10474static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10475 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10476 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10477 return true;
10478 }
10479
10480 return false;
10481}
10482
10483static bool CheckTargetCausesMultiVersioning(
10484 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10485 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10486 LookupResult &Previous) {
10487 const auto *OldTA = OldFD->getAttr<TargetAttr>();
10488 ParsedTargetAttr NewParsed = NewTA->parse();
10489 // Sort order doesn't matter, it just needs to be consistent.
10490 llvm::sort(NewParsed.Features);
10491
10492 // If the old decl is NOT MultiVersioned yet, and we don't cause that
10493 // to change, this is a simple redeclaration.
10494 if (!NewTA->isDefaultVersion() &&
10495 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10496 return false;
10497
10498 // Otherwise, this decl causes MultiVersioning.
10499 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10500 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10501 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10502 NewFD->setInvalidDecl();
10503 return true;
10504 }
10505
10506 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10507 MultiVersionKind::Target)) {
10508 NewFD->setInvalidDecl();
10509 return true;
10510 }
10511
10512 if (CheckMultiVersionValue(S, NewFD)) {
10513 NewFD->setInvalidDecl();
10514 return true;
10515 }
10516
10517 // If this is 'default', permit the forward declaration.
10518 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10519 Redeclaration = true;
10520 OldDecl = OldFD;
10521 OldFD->setIsMultiVersion();
10522 NewFD->setIsMultiVersion();
10523 return false;
10524 }
10525
10526 if (CheckMultiVersionValue(S, OldFD)) {
10527 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10528 NewFD->setInvalidDecl();
10529 return true;
10530 }
10531
10532 ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10533
10534 if (OldParsed == NewParsed) {
10535 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10536 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10537 NewFD->setInvalidDecl();
10538 return true;
10539 }
10540
10541 for (const auto *FD : OldFD->redecls()) {
10542 const auto *CurTA = FD->getAttr<TargetAttr>();
10543 // We allow forward declarations before ANY multiversioning attributes, but
10544 // nothing after the fact.
10545 if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10546 (!CurTA || CurTA->isInherited())) {
10547 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10548 << 0;
10549 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10550 NewFD->setInvalidDecl();
10551 return true;
10552 }
10553 }
10554
10555 OldFD->setIsMultiVersion();
10556 NewFD->setIsMultiVersion();
10557 Redeclaration = false;
10558 MergeTypeWithPrevious = false;
10559 OldDecl = nullptr;
10560 Previous.clear();
10561 return false;
10562}
10563
10564/// Check the validity of a new function declaration being added to an existing
10565/// multiversioned declaration collection.
10566static bool CheckMultiVersionAdditionalDecl(
10567 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10568 MultiVersionKind NewMVType, const TargetAttr *NewTA,
10569 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10570 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10571 LookupResult &Previous) {
10572
10573 MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
10574 // Disallow mixing of multiversioning types.
10575 if ((OldMVType == MultiVersionKind::Target &&
10576 NewMVType != MultiVersionKind::Target) ||
10577 (NewMVType == MultiVersionKind::Target &&
10578 OldMVType != MultiVersionKind::Target)) {
10579 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10580 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10581 NewFD->setInvalidDecl();
10582 return true;
10583 }
10584
10585 ParsedTargetAttr NewParsed;
10586 if (NewTA) {
10587 NewParsed = NewTA->parse();
10588 llvm::sort(NewParsed.Features);
10589 }
10590
10591 bool UseMemberUsingDeclRules =
10592 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10593
10594 // Next, check ALL non-overloads to see if this is a redeclaration of a
10595 // previous member of the MultiVersion set.
10596 for (NamedDecl *ND : Previous) {
10597 FunctionDecl *CurFD = ND->getAsFunction();
10598 if (!CurFD)
10599 continue;
10600 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10601 continue;
10602
10603 if (NewMVType == MultiVersionKind::Target) {
10604 const auto *CurTA = CurFD->getAttr<TargetAttr>();
10605 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10606 NewFD->setIsMultiVersion();
10607 Redeclaration = true;
10608 OldDecl = ND;
10609 return false;
10610 }
10611
10612 ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10613 if (CurParsed == NewParsed) {
10614 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10615 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10616 NewFD->setInvalidDecl();
10617 return true;
10618 }
10619 } else {
10620 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10621 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10622 // Handle CPUDispatch/CPUSpecific versions.
10623 // Only 1 CPUDispatch function is allowed, this will make it go through
10624 // the redeclaration errors.
10625 if (NewMVType == MultiVersionKind::CPUDispatch &&
10626 CurFD->hasAttr<CPUDispatchAttr>()) {
10627 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10628 std::equal(
10629 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10630 NewCPUDisp->cpus_begin(),
10631 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10632 return Cur->getName() == New->getName();
10633 })) {
10634 NewFD->setIsMultiVersion();
10635 Redeclaration = true;
10636 OldDecl = ND;
10637 return false;
10638 }
10639
10640 // If the declarations don't match, this is an error condition.
10641 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10642 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10643 NewFD->setInvalidDecl();
10644 return true;
10645 }
10646 if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10647
10648 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10649 std::equal(
10650 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10651 NewCPUSpec->cpus_begin(),
10652 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10653 return Cur->getName() == New->getName();
10654 })) {
10655 NewFD->setIsMultiVersion();
10656 Redeclaration = true;
10657 OldDecl = ND;
10658 return false;
10659 }
10660
10661 // Only 1 version of CPUSpecific is allowed for each CPU.
10662 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10663 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10664 if (CurII == NewII) {
10665 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10666 << NewII;
10667 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10668 NewFD->setInvalidDecl();
10669 return true;
10670 }
10671 }
10672 }
10673 }
10674 // If the two decls aren't the same MVType, there is no possible error
10675 // condition.
10676 }
10677 }
10678
10679 // Else, this is simply a non-redecl case. Checking the 'value' is only
10680 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10681 // handled in the attribute adding step.
10682 if (NewMVType == MultiVersionKind::Target &&
10683 CheckMultiVersionValue(S, NewFD)) {
10684 NewFD->setInvalidDecl();
10685 return true;
10686 }
10687
10688 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10689 !OldFD->isMultiVersion(), NewMVType)) {
10690 NewFD->setInvalidDecl();
10691 return true;
10692 }
10693
10694 // Permit forward declarations in the case where these two are compatible.
10695 if (!OldFD->isMultiVersion()) {
10696 OldFD->setIsMultiVersion();
10697 NewFD->setIsMultiVersion();
10698 Redeclaration = true;
10699 OldDecl = OldFD;
10700 return false;
10701 }
10702
10703 NewFD->setIsMultiVersion();
10704 Redeclaration = false;
10705 MergeTypeWithPrevious = false;
10706 OldDecl = nullptr;
10707 Previous.clear();
10708 return false;
10709}
10710
10711
10712/// Check the validity of a mulitversion function declaration.
10713/// Also sets the multiversion'ness' of the function itself.
10714///
10715/// This sets NewFD->isInvalidDecl() to true if there was an error.
10716///
10717/// Returns true if there was an error, false otherwise.
10718static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10719 bool &Redeclaration, NamedDecl *&OldDecl,
10720 bool &MergeTypeWithPrevious,
10721 LookupResult &Previous) {
10722 const auto *NewTA = NewFD->getAttr<TargetAttr>();
10723 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10724 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10725
10726 // Mixing Multiversioning types is prohibited.
10727 if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
10728 (NewCPUDisp && NewCPUSpec)) {
10729 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10730 NewFD->setInvalidDecl();
10731 return true;
10732 }
10733
10734 MultiVersionKind MVType = NewFD->getMultiVersionKind();
10735
10736 // Main isn't allowed to become a multiversion function, however it IS
10737 // permitted to have 'main' be marked with the 'target' optimization hint.
10738 if (NewFD->isMain()) {
10739 if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
10740 MVType == MultiVersionKind::CPUDispatch ||
10741 MVType == MultiVersionKind::CPUSpecific) {
10742 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10743 NewFD->setInvalidDecl();
10744 return true;
10745 }
10746 return false;
10747 }
10748
10749 if (!OldDecl || !OldDecl->getAsFunction() ||
10750 OldDecl->getDeclContext()->getRedeclContext() !=
10751 NewFD->getDeclContext()->getRedeclContext()) {
10752 // If there's no previous declaration, AND this isn't attempting to cause
10753 // multiversioning, this isn't an error condition.
10754 if (MVType == MultiVersionKind::None)
10755 return false;
10756 return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
10757 }
10758
10759 FunctionDecl *OldFD = OldDecl->getAsFunction();
10760
10761 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
10762 return false;
10763
10764 if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
10765 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10766 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10767 NewFD->setInvalidDecl();
10768 return true;
10769 }
10770
10771 // Handle the target potentially causes multiversioning case.
10772 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10773 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10774 Redeclaration, OldDecl,
10775 MergeTypeWithPrevious, Previous);
10776
10777 // At this point, we have a multiversion function decl (in OldFD) AND an
10778 // appropriate attribute in the current function decl. Resolve that these are
10779 // still compatible with previous declarations.
10780 return CheckMultiVersionAdditionalDecl(
10781 S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
10782 OldDecl, MergeTypeWithPrevious, Previous);
10783}
10784
10785/// Perform semantic checking of a new function declaration.
10786///
10787/// Performs semantic analysis of the new function declaration
10788/// NewFD. This routine performs all semantic checking that does not
10789/// require the actual declarator involved in the declaration, and is
10790/// used both for the declaration of functions as they are parsed
10791/// (called via ActOnDeclarator) and for the declaration of functions
10792/// that have been instantiated via C++ template instantiation (called
10793/// via InstantiateDecl).
10794///
10795/// \param IsMemberSpecialization whether this new function declaration is
10796/// a member specialization (that replaces any definition provided by the
10797/// previous declaration).
10798///
10799/// This sets NewFD->isInvalidDecl() to true if there was an error.
10800///
10801/// \returns true if the function declaration is a redeclaration.
10802bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10803 LookupResult &Previous,
10804 bool IsMemberSpecialization) {
10805 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 10806, __extension__ __PRETTY_FUNCTION__))
10806 "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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 10806, __extension__ __PRETTY_FUNCTION__))
;
10807
10808 // Determine whether the type of this function should be merged with
10809 // a previous visible declaration. This never happens for functions in C++,
10810 // and always happens in C if the previous declaration was visible.
10811 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10812 !Previous.isShadowed();
10813
10814 bool Redeclaration = false;
10815 NamedDecl *OldDecl = nullptr;
10816 bool MayNeedOverloadableChecks = false;
10817
10818 // Merge or overload the declaration with an existing declaration of
10819 // the same name, if appropriate.
10820 if (!Previous.empty()) {
10821 // Determine whether NewFD is an overload of PrevDecl or
10822 // a declaration that requires merging. If it's an overload,
10823 // there's no more work to do here; we'll just add the new
10824 // function to the scope.
10825 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10826 NamedDecl *Candidate = Previous.getRepresentativeDecl();
10827 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10828 Redeclaration = true;
10829 OldDecl = Candidate;
10830 }
10831 } else {
10832 MayNeedOverloadableChecks = true;
10833 switch (CheckOverload(S, NewFD, Previous, OldDecl,
10834 /*NewIsUsingDecl*/ false)) {
10835 case Ovl_Match:
10836 Redeclaration = true;
10837 break;
10838
10839 case Ovl_NonFunction:
10840 Redeclaration = true;
10841 break;
10842
10843 case Ovl_Overload:
10844 Redeclaration = false;
10845 break;
10846 }
10847 }
10848 }
10849
10850 // Check for a previous extern "C" declaration with this name.
10851 if (!Redeclaration &&
10852 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10853 if (!Previous.empty()) {
10854 // This is an extern "C" declaration with the same name as a previous
10855 // declaration, and thus redeclares that entity...
10856 Redeclaration = true;
10857 OldDecl = Previous.getFoundDecl();
10858 MergeTypeWithPrevious = false;
10859
10860 // ... except in the presence of __attribute__((overloadable)).
10861 if (OldDecl->hasAttr<OverloadableAttr>() ||
10862 NewFD->hasAttr<OverloadableAttr>()) {
10863 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10864 MayNeedOverloadableChecks = true;
10865 Redeclaration = false;
10866 OldDecl = nullptr;
10867 }
10868 }
10869 }
10870 }
10871
10872 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10873 MergeTypeWithPrevious, Previous))
10874 return Redeclaration;
10875
10876 // PPC MMA non-pointer types are not allowed as function return types.
10877 if (Context.getTargetInfo().getTriple().isPPC64() &&
10878 CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
10879 NewFD->setInvalidDecl();
10880 }
10881
10882 // C++11 [dcl.constexpr]p8:
10883 // A constexpr specifier for a non-static member function that is not
10884 // a constructor declares that member function to be const.
10885 //
10886 // This needs to be delayed until we know whether this is an out-of-line
10887 // definition of a static member function.
10888 //
10889 // This rule is not present in C++1y, so we produce a backwards
10890 // compatibility warning whenever it happens in C++11.
10891 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10892 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10893 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10894 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
10895 CXXMethodDecl *OldMD = nullptr;
10896 if (OldDecl)
10897 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10898 if (!OldMD || !OldMD->isStatic()) {
10899 const FunctionProtoType *FPT =
10900 MD->getType()->castAs<FunctionProtoType>();
10901 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10902 EPI.TypeQuals.addConst();
10903 MD->setType(Context.getFunctionType(FPT->getReturnType(),
10904 FPT->getParamTypes(), EPI));
10905
10906 // Warn that we did this, if we're not performing template instantiation.
10907 // In that case, we'll have warned already when the template was defined.
10908 if (!inTemplateInstantiation()) {
10909 SourceLocation AddConstLoc;
10910 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10911 .IgnoreParens().getAs<FunctionTypeLoc>())
10912 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10913
10914 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10915 << FixItHint::CreateInsertion(AddConstLoc, " const");
10916 }
10917 }
10918 }
10919
10920 if (Redeclaration) {
10921 // NewFD and OldDecl represent declarations that need to be
10922 // merged.
10923 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10924 NewFD->setInvalidDecl();
10925 return Redeclaration;
10926 }
10927
10928 Previous.clear();
10929 Previous.addDecl(OldDecl);
10930
10931 if (FunctionTemplateDecl *OldTemplateDecl =
10932 dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10933 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10934 FunctionTemplateDecl *NewTemplateDecl
10935 = NewFD->getDescribedFunctionTemplate();
10936 assert(NewTemplateDecl && "Template/non-template mismatch")(static_cast <bool> (NewTemplateDecl && "Template/non-template mismatch"
) ? void (0) : __assert_fail ("NewTemplateDecl && \"Template/non-template mismatch\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 10936, __extension__ __PRETTY_FUNCTION__))
;
10937
10938 // The call to MergeFunctionDecl above may have created some state in
10939 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10940 // can add it as a redeclaration.
10941 NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10942
10943 NewFD->setPreviousDeclaration(OldFD);
10944 if (NewFD->isCXXClassMember()) {
10945 NewFD->setAccess(OldTemplateDecl->getAccess());
10946 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10947 }
10948
10949 // If this is an explicit specialization of a member that is a function
10950 // template, mark it as a member specialization.
10951 if (IsMemberSpecialization &&
10952 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10953 NewTemplateDecl->setMemberSpecialization();
10954 assert(OldTemplateDecl->isMemberSpecialization())(static_cast <bool> (OldTemplateDecl->isMemberSpecialization
()) ? void (0) : __assert_fail ("OldTemplateDecl->isMemberSpecialization()"
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 10954, __extension__ __PRETTY_FUNCTION__))
;
10955 // Explicit specializations of a member template do not inherit deleted
10956 // status from the parent member template that they are specializing.
10957 if (OldFD->isDeleted()) {
10958 // FIXME: This assert will not hold in the presence of modules.
10959 assert(OldFD->getCanonicalDecl() == OldFD)(static_cast <bool> (OldFD->getCanonicalDecl() == OldFD
) ? void (0) : __assert_fail ("OldFD->getCanonicalDecl() == OldFD"
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 10959, __extension__ __PRETTY_FUNCTION__))
;
10960 // FIXME: We need an update record for this AST mutation.
10961 OldFD->setDeletedAsWritten(false);
10962 }
10963 }
10964
10965 } else {
10966 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10967 auto *OldFD = cast<FunctionDecl>(OldDecl);
10968 // This needs to happen first so that 'inline' propagates.
10969 NewFD->setPreviousDeclaration(OldFD);
10970 if (NewFD->isCXXClassMember())
10971 NewFD->setAccess(OldFD->getAccess());
10972 }
10973 }
10974 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10975 !NewFD->getAttr<OverloadableAttr>()) {
10976 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 10981, __extension__ __PRETTY_FUNCTION__))
10977 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 10981, __extension__ __PRETTY_FUNCTION__))
10978 [](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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 10981, __extension__ __PRETTY_FUNCTION__))
10979 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 10981, __extension__ __PRETTY_FUNCTION__))
10980 })) &&(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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 10981, __extension__ __PRETTY_FUNCTION__))
10981 "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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 10981, __extension__ __PRETTY_FUNCTION__))
;
10982
10983 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10984 const auto *FD = dyn_cast<FunctionDecl>(ND);
10985 return FD && !FD->hasAttr<OverloadableAttr>();
10986 });
10987
10988 if (OtherUnmarkedIter != Previous.end()) {
10989 Diag(NewFD->getLocation(),
10990 diag::err_attribute_overloadable_multiple_unmarked_overloads);
10991 Diag((*OtherUnmarkedIter)->getLocation(),
10992 diag::note_attribute_overloadable_prev_overload)
10993 << false;
10994
10995 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10996 }
10997 }
10998
10999 if (LangOpts.OpenMP)
11000 ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
11001
11002 // Semantic checking for this function declaration (in isolation).
11003
11004 if (getLangOpts().CPlusPlus) {
11005 // C++-specific checks.
11006 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
11007 CheckConstructor(Constructor);
11008 } else if (CXXDestructorDecl *Destructor =
11009 dyn_cast<CXXDestructorDecl>(NewFD)) {
11010 CXXRecordDecl *Record = Destructor->getParent();
11011 QualType ClassType = Context.getTypeDeclType(Record);
11012
11013 // FIXME: Shouldn't we be able to perform this check even when the class
11014 // type is dependent? Both gcc and edg can handle that.
11015 if (!ClassType->isDependentType()) {
11016 DeclarationName Name
11017 = Context.DeclarationNames.getCXXDestructorName(
11018 Context.getCanonicalType(ClassType));
11019 if (NewFD->getDeclName() != Name) {
11020 Diag(NewFD->getLocation(), diag::err_destructor_name);
11021 NewFD->setInvalidDecl();
11022 return Redeclaration;
11023 }
11024 }
11025 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
11026 if (auto *TD = Guide->getDescribedFunctionTemplate())
11027 CheckDeductionGuideTemplate(TD);
11028
11029 // A deduction guide is not on the list of entities that can be
11030 // explicitly specialized.
11031 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
11032 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
11033 << /*explicit specialization*/ 1;
11034 }
11035
11036 // Find any virtual functions that this function overrides.
11037 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
11038 if (!Method->isFunctionTemplateSpecialization() &&
11039 !Method->getDescribedFunctionTemplate() &&
11040 Method->isCanonicalDecl()) {
11041 AddOverriddenMethods(Method->getParent(), Method);
11042 }
11043 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
11044 // C++2a [class.virtual]p6
11045 // A virtual method shall not have a requires-clause.
11046 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
11047 diag::err_constrained_virtual_method);
11048
11049 if (Method->isStatic())
11050 checkThisInStaticMemberFunctionType(Method);
11051 }
11052
11053 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
11054 ActOnConversionDeclarator(Conversion);
11055
11056 // Extra checking for C++ overloaded operators (C++ [over.oper]).
11057 if (NewFD->isOverloadedOperator() &&
11058 CheckOverloadedOperatorDeclaration(NewFD)) {
11059 NewFD->setInvalidDecl();
11060 return Redeclaration;
11061 }
11062
11063 // Extra checking for C++0x literal operators (C++0x [over.literal]).
11064 if (NewFD->getLiteralIdentifier() &&
11065 CheckLiteralOperatorDeclaration(NewFD)) {
11066 NewFD->setInvalidDecl();
11067 return Redeclaration;
11068 }
11069
11070 // In C++, check default arguments now that we have merged decls. Unless
11071 // the lexical context is the class, because in this case this is done
11072 // during delayed parsing anyway.
11073 if (!CurContext->isRecord())
11074 CheckCXXDefaultArguments(NewFD);
11075
11076 // If this function is declared as being extern "C", then check to see if
11077 // the function returns a UDT (class, struct, or union type) that is not C
11078 // compatible, and if it does, warn the user.
11079 // But, issue any diagnostic on the first declaration only.
11080 if (Previous.empty() && NewFD->isExternC()) {
11081 QualType R = NewFD->getReturnType();
11082 if (R->isIncompleteType() && !R->isVoidType())
11083 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
11084 << NewFD << R;
11085 else if (!R.isPODType(Context) && !R->isVoidType() &&
11086 !R->isObjCObjectPointerType())
11087 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
11088 }
11089
11090 // C++1z [dcl.fct]p6:
11091 // [...] whether the function has a non-throwing exception-specification
11092 // [is] part of the function type
11093 //
11094 // This results in an ABI break between C++14 and C++17 for functions whose
11095 // declared type includes an exception-specification in a parameter or
11096 // return type. (Exception specifications on the function itself are OK in
11097 // most cases, and exception specifications are not permitted in most other
11098 // contexts where they could make it into a mangling.)
11099 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
11100 auto HasNoexcept = [&](QualType T) -> bool {
11101 // Strip off declarator chunks that could be between us and a function
11102 // type. We don't need to look far, exception specifications are very
11103 // restricted prior to C++17.
11104 if (auto *RT = T->getAs<ReferenceType>())
11105 T = RT->getPointeeType();
11106 else if (T->isAnyPointerType())
11107 T = T->getPointeeType();
11108 else if (auto *MPT = T->getAs<MemberPointerType>())
11109 T = MPT->getPointeeType();
11110 if (auto *FPT = T->getAs<FunctionProtoType>())
11111 if (FPT->isNothrow())
11112 return true;
11113 return false;
11114 };
11115
11116 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
11117 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
11118 for (QualType T : FPT->param_types())
11119 AnyNoexcept |= HasNoexcept(T);
11120 if (AnyNoexcept)
11121 Diag(NewFD->getLocation(),
11122 diag::warn_cxx17_compat_exception_spec_in_signature)
11123 << NewFD;
11124 }
11125
11126 if (!Redeclaration && LangOpts.CUDA)
11127 checkCUDATargetOverload(NewFD, Previous);
11128 }
11129 return Redeclaration;
11130}
11131
11132void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
11133 // C++11 [basic.start.main]p3:
11134 // A program that [...] declares main to be inline, static or
11135 // constexpr is ill-formed.
11136 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
11137 // appear in a declaration of main.
11138 // static main is not an error under C99, but we should warn about it.
11139 // We accept _Noreturn main as an extension.
11140 if (FD->getStorageClass() == SC_Static)
11141 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
11142 ? diag::err_static_main : diag::warn_static_main)
11143 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
11144 if (FD->isInlineSpecified())
11145 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
11146 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
11147 if (DS.isNoreturnSpecified()) {
11148 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
11149 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
11150 Diag(NoreturnLoc, diag::ext_noreturn_main);
11151 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
11152 << FixItHint::CreateRemoval(NoreturnRange);
11153 }
11154 if (FD->isConstexpr()) {
11155 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
11156 << FD->isConsteval()
11157 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
11158 FD->setConstexprKind(ConstexprSpecKind::Unspecified);
11159 }
11160
11161 if (getLangOpts().OpenCL) {
11162 Diag(FD->getLocation(), diag::err_opencl_no_main)
11163 << FD->hasAttr<OpenCLKernelAttr>();
11164 FD->setInvalidDecl();
11165 return;
11166 }
11167
11168 QualType T = FD->getType();
11169 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 11169, __extension__ __PRETTY_FUNCTION__))
;
11170 const FunctionType* FT = T->castAs<FunctionType>();
11171
11172 // Set default calling convention for main()
11173 if (FT->getCallConv() != CC_C) {
11174 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
11175 FD->setType(QualType(FT, 0));
11176 T = Context.getCanonicalType(FD->getType());
11177 }
11178
11179 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
11180 // In C with GNU extensions we allow main() to have non-integer return
11181 // type, but we should warn about the extension, and we disable the
11182 // implicit-return-zero rule.
11183
11184 // GCC in C mode accepts qualified 'int'.
11185 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
11186 FD->setHasImplicitReturnZero(true);
11187 else {
11188 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
11189 SourceRange RTRange = FD->getReturnTypeSourceRange();
11190 if (RTRange.isValid())
11191 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
11192 << FixItHint::CreateReplacement(RTRange, "int");
11193 }
11194 } else {
11195 // In C and C++, main magically returns 0 if you fall off the end;
11196 // set the flag which tells us that.
11197 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
11198
11199 // All the standards say that main() should return 'int'.
11200 if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
11201 FD->setHasImplicitReturnZero(true);
11202 else {
11203 // Otherwise, this is just a flat-out error.
11204 SourceRange RTRange = FD->getReturnTypeSourceRange();
11205 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
11206 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
11207 : FixItHint());
11208 FD->setInvalidDecl(true);
11209 }
11210 }
11211
11212 // Treat protoless main() as nullary.
11213 if (isa<FunctionNoProtoType>(FT)) return;
11214
11215 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
11216 unsigned nparams = FTP->getNumParams();
11217 assert(FD->getNumParams() == nparams)(static_cast <bool> (FD->getNumParams() == nparams) ?
void (0) : __assert_fail ("FD->getNumParams() == nparams"
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 11217, __extension__ __PRETTY_FUNCTION__))
;
11218
11219 bool HasExtraParameters = (nparams > 3);
11220
11221 if (FTP->isVariadic()) {
11222 Diag(FD->getLocation(), diag::ext_variadic_main);
11223 // FIXME: if we had information about the location of the ellipsis, we
11224 // could add a FixIt hint to remove it as a parameter.
11225 }
11226
11227 // Darwin passes an undocumented fourth argument of type char**. If
11228 // other platforms start sprouting these, the logic below will start
11229 // getting shifty.
11230 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
11231 HasExtraParameters = false;
11232
11233 if (HasExtraParameters) {
11234 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
11235 FD->setInvalidDecl(true);
11236 nparams = 3;
11237 }
11238
11239 // FIXME: a lot of the following diagnostics would be improved
11240 // if we had some location information about types.
11241
11242 QualType CharPP =
11243 Context.getPointerType(Context.getPointerType(Context.CharTy));
11244 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
11245
11246 for (unsigned i = 0; i < nparams; ++i) {
11247 QualType AT = FTP->getParamType(i);
11248
11249 bool mismatch = true;
11250
11251 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
11252 mismatch = false;
11253 else if (Expected[i] == CharPP) {
11254 // As an extension, the following forms are okay:
11255 // char const **
11256 // char const * const *
11257 // char * const *
11258
11259 QualifierCollector qs;
11260 const PointerType* PT;
11261 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
11262 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
11263 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
11264 Context.CharTy)) {
11265 qs.removeConst();
11266 mismatch = !qs.empty();
11267 }
11268 }
11269
11270 if (mismatch) {
11271 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
11272 // TODO: suggest replacing given type with expected type
11273 FD->setInvalidDecl(true);
11274 }
11275 }
11276
11277 if (nparams == 1 && !FD->isInvalidDecl()) {
11278 Diag(FD->getLocation(), diag::warn_main_one_arg);
11279 }
11280
11281 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11282 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11283 FD->setInvalidDecl();
11284 }
11285}
11286
11287static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
11288
11289 // Default calling convention for main and wmain is __cdecl
11290 if (FD->getName() == "main" || FD->getName() == "wmain")
11291 return false;
11292
11293 // Default calling convention for MinGW is __cdecl
11294 const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
11295 if (T.isWindowsGNUEnvironment())
11296 return false;
11297
11298 // Default calling convention for WinMain, wWinMain and DllMain
11299 // is __stdcall on 32 bit Windows
11300 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
11301 return true;
11302
11303 return false;
11304}
11305
11306void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
11307 QualType T = FD->getType();
11308 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 11308, __extension__ __PRETTY_FUNCTION__))
;
11309 const FunctionType *FT = T->castAs<FunctionType>();
11310
11311 // Set an implicit return of 'zero' if the function can return some integral,
11312 // enumeration, pointer or nullptr type.
11313 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
11314 FT->getReturnType()->isAnyPointerType() ||
11315 FT->getReturnType()->isNullPtrType())
11316 // DllMain is exempt because a return value of zero means it failed.
11317 if (FD->getName() != "DllMain")
11318 FD->setHasImplicitReturnZero(true);
11319
11320 // Explicity specified calling conventions are applied to MSVC entry points
11321 if (!hasExplicitCallingConv(T)) {
11322 if (isDefaultStdCall(FD, *this)) {
11323 if (FT->getCallConv() != CC_X86StdCall) {
11324 FT = Context.adjustFunctionType(
11325 FT, FT->getExtInfo().withCallingConv(CC_X86StdCall));
11326 FD->setType(QualType(FT, 0));
11327 }
11328 } else if (FT->getCallConv() != CC_C) {
11329 FT = Context.adjustFunctionType(FT,
11330 FT->getExtInfo().withCallingConv(CC_C));
11331 FD->setType(QualType(FT, 0));
11332 }
11333 }
11334
11335 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11336 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11337 FD->setInvalidDecl();
11338 }
11339}
11340
11341bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
11342 // FIXME: Need strict checking. In C89, we need to check for
11343 // any assignment, increment, decrement, function-calls, or
11344 // commas outside of a sizeof. In C99, it's the same list,
11345 // except that the aforementioned are allowed in unevaluated
11346 // expressions. Everything else falls under the
11347 // "may accept other forms of constant expressions" exception.
11348 //
11349 // Regular C++ code will not end up here (exceptions: language extensions,
11350 // OpenCL C++ etc), so the constant expression rules there don't matter.
11351 if (Init->isValueDependent()) {
11352 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.\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 11353, __extension__ __PRETTY_FUNCTION__))
11353 "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.\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 11353, __extension__ __PRETTY_FUNCTION__))
;
11354 return true;
11355 }
11356 const Expr *Culprit;
11357 if (Init->isConstantInitializer(Context, false, &Culprit))
11358 return false;
11359 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
11360 << Culprit->getSourceRange();
11361 return true;
11362}
11363
11364namespace {
11365 // Visits an initialization expression to see if OrigDecl is evaluated in
11366 // its own initialization and throws a warning if it does.
11367 class SelfReferenceChecker
11368 : public EvaluatedExprVisitor<SelfReferenceChecker> {
11369 Sema &S;
11370 Decl *OrigDecl;
11371 bool isRecordType;
11372 bool isPODType;
11373 bool isReferenceType;
11374
11375 bool isInitList;
11376 llvm::SmallVector<unsigned, 4> InitFieldIndex;
11377
11378 public:
11379 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
11380
11381 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
11382 S(S), OrigDecl(OrigDecl) {
11383 isPODType = false;
11384 isRecordType = false;
11385 isReferenceType = false;
11386 isInitList = false;
11387 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
11388 isPODType = VD->getType().isPODType(S.Context);
11389 isRecordType = VD->getType()->isRecordType();
11390 isReferenceType = VD->getType()->isReferenceType();
11391 }
11392 }
11393
11394 // For most expressions, just call the visitor. For initializer lists,
11395 // track the index of the field being initialized since fields are
11396 // initialized in order allowing use of previously initialized fields.
11397 void CheckExpr(Expr *E) {
11398 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
11399 if (!InitList) {
11400 Visit(E);
11401 return;
11402 }
11403
11404 // Track and increment the index here.
11405 isInitList = true;
11406 InitFieldIndex.push_back(0);
11407 for (auto Child : InitList->children()) {
11408 CheckExpr(cast<Expr>(Child));
11409 ++InitFieldIndex.back();
11410 }
11411 InitFieldIndex.pop_back();
11412 }
11413
11414 // Returns true if MemberExpr is checked and no further checking is needed.
11415 // Returns false if additional checking is required.
11416 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
11417 llvm::SmallVector<FieldDecl*, 4> Fields;
11418 Expr *Base = E;
11419 bool ReferenceField = false;
11420
11421 // Get the field members used.
11422 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11423 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
11424 if (!FD)
11425 return false;
11426 Fields.push_back(FD);
11427 if (FD->getType()->isReferenceType())
11428 ReferenceField = true;
11429 Base = ME->getBase()->IgnoreParenImpCasts();
11430 }
11431
11432 // Keep checking only if the base Decl is the same.
11433 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
11434 if (!DRE || DRE->getDecl() != OrigDecl)
11435 return false;
11436
11437 // A reference field can be bound to an unininitialized field.
11438 if (CheckReference && !ReferenceField)
11439 return true;
11440
11441 // Convert FieldDecls to their index number.
11442 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
11443 for (const FieldDecl *I : llvm::reverse(Fields))
11444 UsedFieldIndex.push_back(I->getFieldIndex());
11445
11446 // See if a warning is needed by checking the first difference in index
11447 // numbers. If field being used has index less than the field being
11448 // initialized, then the use is safe.
11449 for (auto UsedIter = UsedFieldIndex.begin(),
11450 UsedEnd = UsedFieldIndex.end(),
11451 OrigIter = InitFieldIndex.begin(),
11452 OrigEnd = InitFieldIndex.end();
11453 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
11454 if (*UsedIter < *OrigIter)
11455 return true;
11456 if (*UsedIter > *OrigIter)
11457 break;
11458 }
11459
11460 // TODO: Add a different warning which will print the field names.
11461 HandleDeclRefExpr(DRE);
11462 return true;
11463 }
11464
11465 // For most expressions, the cast is directly above the DeclRefExpr.
11466 // For conditional operators, the cast can be outside the conditional
11467 // operator if both expressions are DeclRefExpr's.
11468 void HandleValue(Expr *E) {
11469 E = E->IgnoreParens();
11470 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11471 HandleDeclRefExpr(DRE);
11472 return;
11473 }
11474
11475 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11476 Visit(CO->getCond());
11477 HandleValue(CO->getTrueExpr());
11478 HandleValue(CO->getFalseExpr());
11479 return;
11480 }
11481
11482 if (BinaryConditionalOperator *BCO =
11483 dyn_cast<BinaryConditionalOperator>(E)) {
11484 Visit(BCO->getCond());
11485 HandleValue(BCO->getFalseExpr());
11486 return;
11487 }
11488
11489 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11490 HandleValue(OVE->getSourceExpr());
11491 return;
11492 }
11493
11494 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11495 if (BO->getOpcode() == BO_Comma) {
11496 Visit(BO->getLHS());
11497 HandleValue(BO->getRHS());
11498 return;
11499 }
11500 }
11501
11502 if (isa<MemberExpr>(E)) {
11503 if (isInitList) {
11504 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11505 false /*CheckReference*/))
11506 return;
11507 }
11508
11509 Expr *Base = E->IgnoreParenImpCasts();
11510 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11511 // Check for static member variables and don't warn on them.
11512 if (!isa<FieldDecl>(ME->getMemberDecl()))
11513 return;
11514 Base = ME->getBase()->IgnoreParenImpCasts();
11515 }
11516 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11517 HandleDeclRefExpr(DRE);
11518 return;
11519 }
11520
11521 Visit(E);
11522 }
11523
11524 // Reference types not handled in HandleValue are handled here since all
11525 // uses of references are bad, not just r-value uses.
11526 void VisitDeclRefExpr(DeclRefExpr *E) {
11527 if (isReferenceType)
11528 HandleDeclRefExpr(E);
11529 }
11530
11531 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11532 if (E->getCastKind() == CK_LValueToRValue) {
11533 HandleValue(E->getSubExpr());
11534 return;
11535 }
11536
11537 Inherited::VisitImplicitCastExpr(E);
11538 }
11539
11540 void VisitMemberExpr(MemberExpr *E) {
11541 if (isInitList) {
11542 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11543 return;
11544 }
11545
11546 // Don't warn on arrays since they can be treated as pointers.
11547 if (E->getType()->canDecayToPointerType()) return;
11548
11549 // Warn when a non-static method call is followed by non-static member
11550 // field accesses, which is followed by a DeclRefExpr.
11551 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11552 bool Warn = (MD && !MD->isStatic());
11553 Expr *Base = E->getBase()->IgnoreParenImpCasts();
11554 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11555 if (!isa<FieldDecl>(ME->getMemberDecl()))
11556 Warn = false;
11557 Base = ME->getBase()->IgnoreParenImpCasts();
11558 }
11559
11560 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11561 if (Warn)
11562 HandleDeclRefExpr(DRE);
11563 return;
11564 }
11565
11566 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11567 // Visit that expression.
11568 Visit(Base);
11569 }
11570
11571 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11572 Expr *Callee = E->getCallee();
11573
11574 if (isa<UnresolvedLookupExpr>(Callee))
11575 return Inherited::VisitCXXOperatorCallExpr(E);
11576
11577 Visit(Callee);
11578 for (auto Arg: E->arguments())
11579 HandleValue(Arg->IgnoreParenImpCasts());
11580 }
11581
11582 void VisitUnaryOperator(UnaryOperator *E) {
11583 // For POD record types, addresses of its own members are well-defined.
11584 if (E->getOpcode() == UO_AddrOf && isRecordType &&
11585 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11586 if (!isPODType)
11587 HandleValue(E->getSubExpr());
11588 return;
11589 }
11590
11591 if (E->isIncrementDecrementOp()) {
11592 HandleValue(E->getSubExpr());
11593 return;
11594 }
11595
11596 Inherited::VisitUnaryOperator(E);
11597 }
11598
11599 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11600
11601 void VisitCXXConstructExpr(CXXConstructExpr *E) {
11602 if (E->getConstructor()->isCopyConstructor()) {
11603 Expr *ArgExpr = E->getArg(0);
11604 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11605 if (ILE->getNumInits() == 1)
11606 ArgExpr = ILE->getInit(0);
11607 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11608 if (ICE->getCastKind() == CK_NoOp)
11609 ArgExpr = ICE->getSubExpr();
11610 HandleValue(ArgExpr);
11611 return;
11612 }
11613 Inherited::VisitCXXConstructExpr(E);
11614 }
11615
11616 void VisitCallExpr(CallExpr *E) {
11617 // Treat std::move as a use.
11618 if (E->isCallToStdMove()) {
11619 HandleValue(E->getArg(0));
11620 return;
11621 }
11622
11623 Inherited::VisitCallExpr(E);
11624 }
11625
11626 void VisitBinaryOperator(BinaryOperator *E) {
11627 if (E->isCompoundAssignmentOp()) {
11628 HandleValue(E->getLHS());
11629 Visit(E->getRHS());
11630 return;
11631 }
11632
11633 Inherited::VisitBinaryOperator(E);
11634 }
11635
11636 // A custom visitor for BinaryConditionalOperator is needed because the
11637 // regular visitor would check the condition and true expression separately
11638 // but both point to the same place giving duplicate diagnostics.
11639 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11640 Visit(E->getCond());
11641 Visit(E->getFalseExpr());
11642 }
11643
11644 void HandleDeclRefExpr(DeclRefExpr *DRE) {
11645 Decl* ReferenceDecl = DRE->getDecl();
11646 if (OrigDecl != ReferenceDecl) return;
11647 unsigned diag;
11648 if (isReferenceType) {
11649 diag = diag::warn_uninit_self_reference_in_reference_init;
11650 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11651 diag = diag::warn_static_self_reference_in_init;
11652 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11653 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11654 DRE->getDecl()->getType()->isRecordType()) {
11655 diag = diag::warn_uninit_self_reference_in_init;
11656 } else {
11657 // Local variables will be handled by the CFG analysis.
11658 return;
11659 }
11660
11661 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11662 S.PDiag(diag)
11663 << DRE->getDecl() << OrigDecl->getLocation()
11664 << DRE->getSourceRange());
11665 }
11666 };
11667
11668 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
11669 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11670 bool DirectInit) {
11671 // Parameters arguments are occassionially constructed with itself,
11672 // for instance, in recursive functions. Skip them.
11673 if (isa<ParmVarDecl>(OrigDecl))
11674 return;
11675
11676 E = E->IgnoreParens();
11677
11678 // Skip checking T a = a where T is not a record or reference type.
11679 // Doing so is a way to silence uninitialized warnings.
11680 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11681 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11682 if (ICE->getCastKind() == CK_LValueToRValue)
11683 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11684 if (DRE->getDecl() == OrigDecl)
11685 return;
11686
11687 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11688 }
11689} // end anonymous namespace
11690
11691namespace {
11692 // Simple wrapper to add the name of a variable or (if no variable is
11693 // available) a DeclarationName into a diagnostic.
11694 struct VarDeclOrName {
11695 VarDecl *VDecl;
11696 DeclarationName Name;
11697
11698 friend const Sema::SemaDiagnosticBuilder &
11699 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11700 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11701 }
11702 };
11703} // end anonymous namespace
11704
11705QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11706 DeclarationName Name, QualType Type,
11707 TypeSourceInfo *TSI,
11708 SourceRange Range, bool DirectInit,
11709 Expr *Init) {
11710 bool IsInitCapture = !VDecl;
11711 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 11712, __extension__ __PRETTY_FUNCTION__))
11712 "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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 11712, __extension__ __PRETTY_FUNCTION__))
;
11713
11714 VarDeclOrName VN{VDecl, Name};
11715
11716 DeducedType *Deduced = Type->getContainedDeducedType();
11717 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 11717, __extension__ __PRETTY_FUNCTION__))
;
11718
11719 // C++11 [dcl.spec.auto]p3
11720 if (!Init) {
11721 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?\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 11721, __extension__ __PRETTY_FUNCTION__))
;
11722
11723 // Except for class argument deduction, and then for an initializing
11724 // declaration only, i.e. no static at class scope or extern.
11725 if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11726 VDecl->hasExternalStorage() ||
11727 VDecl->isStaticDataMember()) {
11728 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11729 << VDecl->getDeclName() << Type;
11730 return QualType();
11731 }
11732 }
11733
11734 ArrayRef<Expr*> DeduceInits;
11735 if (Init)
11736 DeduceInits = Init;
11737
11738 if (DirectInit) {
11739 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
11740 DeduceInits = PL->exprs();
11741 }
11742
11743 if (isa<DeducedTemplateSpecializationType>(Deduced)) {
11744 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?\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 11744, __extension__ __PRETTY_FUNCTION__))
;
11745 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11746 InitializationKind Kind = InitializationKind::CreateForInit(
11747 VDecl->getLocation(), DirectInit, Init);
11748 // FIXME: Initialization should not be taking a mutable list of inits.
11749 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
11750 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
11751 InitsCopy);
11752 }
11753
11754 if (DirectInit) {
11755 if (auto *IL = dyn_cast<InitListExpr>(Init))
11756 DeduceInits = IL->inits();
11757 }
11758
11759 // Deduction only works if we have exactly one source expression.
11760 if (DeduceInits.empty()) {
11761 // It isn't possible to write this directly, but it is possible to
11762 // end up in this situation with "auto x(some_pack...);"
11763 Diag(Init->getBeginLoc(), IsInitCapture
11764 ? diag::err_init_capture_no_expression
11765 : diag::err_auto_var_init_no_expression)
11766 << VN << Type << Range;
11767 return QualType();
11768 }
11769
11770 if (DeduceInits.size() > 1) {
11771 Diag(DeduceInits[1]->getBeginLoc(),
11772 IsInitCapture ? diag::err_init_capture_multiple_expressions
11773 : diag::err_auto_var_init_multiple_expressions)
11774 << VN << Type << Range;
11775 return QualType();
11776 }
11777
11778 Expr *DeduceInit = DeduceInits[0];
11779 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11780 Diag(Init->getBeginLoc(), IsInitCapture
11781 ? diag::err_init_capture_paren_braces
11782 : diag::err_auto_var_init_paren_braces)
11783 << isa<InitListExpr>(Init) << VN << Type << Range;
11784 return QualType();
11785 }
11786
11787 // Expressions default to 'id' when we're in a debugger.
11788 bool DefaultedAnyToId = false;
11789 if (getLangOpts().DebuggerCastResultToId &&
11790 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11791 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11792 if (Result.isInvalid()) {
11793 return QualType();
11794 }
11795 Init = Result.get();
11796 DefaultedAnyToId = true;
11797 }
11798
11799 // C++ [dcl.decomp]p1:
11800 // If the assignment-expression [...] has array type A and no ref-qualifier
11801 // is present, e has type cv A
11802 if (VDecl && isa<DecompositionDecl>(VDecl) &&
11803 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11804 DeduceInit->getType()->isConstantArrayType())
11805 return Context.getQualifiedType(DeduceInit->getType(),
11806 Type.getQualifiers());
11807
11808 QualType DeducedType;
11809 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11810 if (!IsInitCapture)
11811 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11812 else if (isa<InitListExpr>(Init))
11813 Diag(Range.getBegin(),
11814 diag::err_init_capture_deduction_failure_from_init_list)
11815 << VN
11816 << (DeduceInit->getType().isNull() ? TSI->getType()
11817 : DeduceInit->getType())
11818 << DeduceInit->getSourceRange();
11819 else
11820 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11821 << VN << TSI->getType()
11822 << (DeduceInit->getType().isNull() ? TSI->getType()
11823 : DeduceInit->getType())
11824 << DeduceInit->getSourceRange();
11825 }
11826
11827 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11828 // 'id' instead of a specific object type prevents most of our usual
11829 // checks.
11830 // We only want to warn outside of template instantiations, though:
11831 // inside a template, the 'id' could have come from a parameter.
11832 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11833 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11834 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11835 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11836 }
11837
11838 return DeducedType;
11839}
11840
11841bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11842 Expr *Init) {
11843 assert(!Init || !Init->containsErrors())(static_cast <bool> (!Init || !Init->containsErrors(
)) ? void (0) : __assert_fail ("!Init || !Init->containsErrors()"
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 11843, __extension__ __PRETTY_FUNCTION__))
;
11844 QualType DeducedType = deduceVarTypeFromInitializer(
11845 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11846 VDecl->getSourceRange(), DirectInit, Init);
11847 if (DeducedType.isNull()) {
11848 VDecl->setInvalidDecl();
11849 return true;
11850 }
11851
11852 VDecl->setType(DeducedType);
11853 assert(VDecl->isLinkageValid())(static_cast <bool> (VDecl->isLinkageValid()) ? void
(0) : __assert_fail ("VDecl->isLinkageValid()", "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 11853, __extension__ __PRETTY_FUNCTION__))
;
11854
11855 // In ARC, infer lifetime.
11856 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11857 VDecl->setInvalidDecl();
11858
11859 if (getLangOpts().OpenCL)
11860 deduceOpenCLAddressSpace(VDecl);
11861
11862 // If this is a redeclaration, check that the type we just deduced matches
11863 // the previously declared type.
11864 if (VarDecl *Old = VDecl->getPreviousDecl()) {
11865 // We never need to merge the type, because we cannot form an incomplete
11866 // array of auto, nor deduce such a type.
11867 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11868 }
11869
11870 // Check the deduced type is valid for a variable declaration.
11871 CheckVariableDeclarationType(VDecl);
11872 return VDecl->isInvalidDecl();
11873}
11874
11875void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
11876 SourceLocation Loc) {
11877 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
11878 Init = EWC->getSubExpr();
11879
11880 if (auto *CE = dyn_cast<ConstantExpr>(Init))
11881 Init = CE->getSubExpr();
11882
11883 QualType InitType = Init->getType();
11884 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 11886, __extension__ __PRETTY_FUNCTION__))
11885 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 11886, __extension__ __PRETTY_FUNCTION__))
11886 "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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 11886, __extension__ __PRETTY_FUNCTION__))
;
11887 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
11888 for (auto I : ILE->inits()) {
11889 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
11890 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
11891 continue;
11892 SourceLocation SL = I->getExprLoc();
11893 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
11894 }
11895 return;
11896 }
11897
11898 if (isa<ImplicitValueInitExpr>(Init)) {
11899 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11900 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
11901 NTCUK_Init);
11902 } else {
11903 // Assume all other explicit initializers involving copying some existing
11904 // object.
11905 // TODO: ignore any explicit initializers where we can guarantee
11906 // copy-elision.
11907 if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
11908 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
11909 }
11910}
11911
11912namespace {
11913
11914bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
11915 // Ignore unavailable fields. A field can be marked as unavailable explicitly
11916 // in the source code or implicitly by the compiler if it is in a union
11917 // defined in a system header and has non-trivial ObjC ownership
11918 // qualifications. We don't want those fields to participate in determining
11919 // whether the containing union is non-trivial.
11920 return FD->hasAttr<UnavailableAttr>();
11921}
11922
11923struct DiagNonTrivalCUnionDefaultInitializeVisitor
11924 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11925 void> {
11926 using Super =
11927 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11928 void>;
11929
11930 DiagNonTrivalCUnionDefaultInitializeVisitor(
11931 QualType OrigTy, SourceLocation OrigLoc,
11932 Sema::NonTrivialCUnionContext UseContext, Sema &S)
11933 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11934
11935 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
11936 const FieldDecl *FD, bool InNonTrivialUnion) {
11937 if (const auto *AT = S.Context.getAsArrayType(QT))
11938 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11939 InNonTrivialUnion);
11940 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
11941 }
11942
11943 void visitARCStrong(QualType QT, const FieldDecl *FD,
11944 bool InNonTrivialUnion) {
11945 if (InNonTrivialUnion)
11946 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11947 << 1 << 0 << QT << FD->getName();
11948 }
11949
11950 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11951 if (InNonTrivialUnion)
11952 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11953 << 1 << 0 << QT << FD->getName();
11954 }
11955
11956 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11957 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11958 if (RD->isUnion()) {
11959 if (OrigLoc.isValid()) {
11960 bool IsUnion = false;
11961 if (auto *OrigRD = OrigTy->getAsRecordDecl())
11962 IsUnion = OrigRD->isUnion();
11963 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11964 << 0 << OrigTy << IsUnion << UseContext;
11965 // Reset OrigLoc so that this diagnostic is emitted only once.
11966 OrigLoc = SourceLocation();
11967 }
11968 InNonTrivialUnion = true;
11969 }
11970
11971 if (InNonTrivialUnion)
11972 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11973 << 0 << 0 << QT.getUnqualifiedType() << "";
11974
11975 for (const FieldDecl *FD : RD->fields())
11976 if (!shouldIgnoreForRecordTriviality(FD))
11977 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11978 }
11979
11980 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11981
11982 // The non-trivial C union type or the struct/union type that contains a
11983 // non-trivial C union.
11984 QualType OrigTy;
11985 SourceLocation OrigLoc;
11986 Sema::NonTrivialCUnionContext UseContext;
11987 Sema &S;
11988};
11989
11990struct DiagNonTrivalCUnionDestructedTypeVisitor
11991 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
11992 using Super =
11993 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
11994
11995 DiagNonTrivalCUnionDestructedTypeVisitor(
11996 QualType OrigTy, SourceLocation OrigLoc,
11997 Sema::NonTrivialCUnionContext UseContext, Sema &S)
11998 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11999
12000 void visitWithKind(QualType::DestructionKind DK, QualType QT,
12001 const FieldDecl *FD, bool InNonTrivialUnion) {
12002 if (const auto *AT = S.Context.getAsArrayType(QT))
12003 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12004 InNonTrivialUnion);
12005 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
12006 }
12007
12008 void visitARCStrong(QualType QT, const FieldDecl *FD,
12009 bool InNonTrivialUnion) {
12010 if (InNonTrivialUnion)
12011 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12012 << 1 << 1 << QT << FD->getName();
12013 }
12014
12015 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12016 if (InNonTrivialUnion)
12017 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12018 << 1 << 1 << QT << FD->getName();
12019 }
12020
12021 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12022 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12023 if (RD->isUnion()) {
12024 if (OrigLoc.isValid()) {
12025 bool IsUnion = false;
12026 if (auto *OrigRD = OrigTy->getAsRecordDecl())
12027 IsUnion = OrigRD->isUnion();
12028 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12029 << 1 << OrigTy << IsUnion << UseContext;
12030 // Reset OrigLoc so that this diagnostic is emitted only once.
12031 OrigLoc = SourceLocation();
12032 }
12033 InNonTrivialUnion = true;
12034 }
12035
12036 if (InNonTrivialUnion)
12037 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12038 << 0 << 1 << QT.getUnqualifiedType() << "";
12039
12040 for (const FieldDecl *FD : RD->fields())
12041 if (!shouldIgnoreForRecordTriviality(FD))
12042 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12043 }
12044
12045 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12046 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
12047 bool InNonTrivialUnion) {}
12048
12049 // The non-trivial C union type or the struct/union type that contains a
12050 // non-trivial C union.
12051 QualType OrigTy;
12052 SourceLocation OrigLoc;
12053 Sema::NonTrivialCUnionContext UseContext;
12054 Sema &S;
12055};
12056
12057struct DiagNonTrivalCUnionCopyVisitor
12058 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
12059 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
12060
12061 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
12062 Sema::NonTrivialCUnionContext UseContext,
12063 Sema &S)
12064 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12065
12066 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
12067 const FieldDecl *FD, bool InNonTrivialUnion) {
12068 if (const auto *AT = S.Context.getAsArrayType(QT))
12069 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12070 InNonTrivialUnion);
12071 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
12072 }
12073
12074 void visitARCStrong(QualType QT, const FieldDecl *FD,
12075 bool InNonTrivialUnion) {
12076 if (InNonTrivialUnion)
12077 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12078 << 1 << 2 << QT << FD->getName();
12079 }
12080
12081 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12082 if (InNonTrivialUnion)
12083 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12084 << 1 << 2 << QT << FD->getName();
12085 }
12086
12087 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12088 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12089 if (RD->isUnion()) {
12090 if (OrigLoc.isValid()) {
12091 bool IsUnion = false;
12092 if (auto *OrigRD = OrigTy->getAsRecordDecl())
12093 IsUnion = OrigRD->isUnion();
12094 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12095 << 2 << OrigTy << IsUnion << UseContext;
12096 // Reset OrigLoc so that this diagnostic is emitted only once.
12097 OrigLoc = SourceLocation();
12098 }
12099 InNonTrivialUnion = true;
12100 }
12101
12102 if (InNonTrivialUnion)
12103 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12104 << 0 << 2 << QT.getUnqualifiedType() << "";
12105
12106 for (const FieldDecl *FD : RD->fields())
12107 if (!shouldIgnoreForRecordTriviality(FD))
12108 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12109 }
12110
12111 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
12112 const FieldDecl *FD, bool InNonTrivialUnion) {}
12113 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12114 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
12115 bool InNonTrivialUnion) {}
12116
12117 // The non-trivial C union type or the struct/union type that contains a
12118 // non-trivial C union.
12119 QualType OrigTy;
12120 SourceLocation OrigLoc;
12121 Sema::NonTrivialCUnionContext UseContext;
12122 Sema &S;
12123};
12124
12125} // namespace
12126
12127void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
12128 NonTrivialCUnionContext UseContext,
12129 unsigned NonTrivialKind) {
12130 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 12133, __extension__ __PRETTY_FUNCTION__))
12131 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 12133, __extension__ __PRETTY_FUNCTION__))
12132 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 12133, __extension__ __PRETTY_FUNCTION__))
12133 "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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 12133, __extension__ __PRETTY_FUNCTION__))
;
12134
12135 if ((NonTrivialKind & NTCUK_Init) &&
12136 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12137 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
12138 .visit(QT, nullptr, false);
12139 if ((NonTrivialKind & NTCUK_Destruct) &&
12140 QT.hasNonTrivialToPrimitiveDestructCUnion())
12141 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
12142 .visit(QT, nullptr, false);
12143 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
12144 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
12145 .visit(QT, nullptr, false);
12146}
12147
12148/// AddInitializerToDecl - Adds the initializer Init to the
12149/// declaration dcl. If DirectInit is true, this is C++ direct
12150/// initialization rather than copy initialization.
12151void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
12152 // If there is no declaration, there was an error parsing it. Just ignore
12153 // the initializer.
12154 if (!RealDecl || RealDecl->isInvalidDecl()) {
12155 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
12156 return;
12157 }
12158
12159 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
12160 // Pure-specifiers are handled in ActOnPureSpecifier.
12161 Diag(Method->getLocation(), diag::err_member_function_initialization)
12162 << Method->getDeclName() << Init->getSourceRange();
12163 Method->setInvalidDecl();
12164 return;
12165 }
12166
12167 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
12168 if (!VDecl) {
12169 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 12169, __extension__ __PRETTY_FUNCTION__))
;
12170 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
12171 RealDecl->setInvalidDecl();
12172 return;
12173 }
12174
12175 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
12176 if (VDecl->getType()->isUndeducedType()) {
12177 // Attempt typo correction early so that the type of the init expression can
12178 // be deduced based on the chosen correction if the original init contains a
12179 // TypoExpr.
12180 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
12181 if (!Res.isUsable()) {
12182 // There are unresolved typos in Init, just drop them.
12183 // FIXME: improve the recovery strategy to preserve the Init.
12184 RealDecl->setInvalidDecl();
12185 return;
12186 }
12187 if (Res.get()->containsErrors()) {
12188 // Invalidate the decl as we don't know the type for recovery-expr yet.
12189 RealDecl->setInvalidDecl();
12190 VDecl->setInit(Res.get());
12191 return;
12192 }
12193 Init = Res.get();
12194
12195 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
12196 return;
12197 }
12198
12199 // dllimport cannot be used on variable definitions.
12200 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
12201 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
12202 VDecl->setInvalidDecl();
12203 return;
12204 }
12205
12206 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
12207 // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
12208 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
12209 VDecl->setInvalidDecl();
12210 return;
12211 }
12212
12213 if (!VDecl->getType()->isDependentType()) {
12214 // A definition must end up with a complete type, which means it must be
12215 // complete with the restriction that an array type might be completed by
12216 // the initializer; note that later code assumes this restriction.
12217 QualType BaseDeclType = VDecl->getType();
12218 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
12219 BaseDeclType = Array->getElementType();
12220 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
12221 diag::err_typecheck_decl_incomplete_type)) {
12222 RealDecl->setInvalidDecl();
12223 return;
12224 }
12225
12226 // The variable can not have an abstract class type.
12227 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
12228 diag::err_abstract_type_in_decl,
12229 AbstractVariableType))
12230 VDecl->setInvalidDecl();
12231 }
12232
12233 // If adding the initializer will turn this declaration into a definition,
12234 // and we already have a definition for this variable, diagnose or otherwise
12235 // handle the situation.
12236 if (VarDecl *Def = VDecl->getDefinition())
12237 if (Def != VDecl &&
12238 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
12239 !VDecl->isThisDeclarationADemotedDefinition() &&
12240 checkVarDeclRedefinition(Def, VDecl))
12241 return;
12242
12243 if (getLangOpts().CPlusPlus) {
12244 // C++ [class.static.data]p4
12245 // If a static data member is of const integral or const
12246 // enumeration type, its declaration in the class definition can
12247 // specify a constant-initializer which shall be an integral
12248 // constant expression (5.19). In that case, the member can appear
12249 // in integral constant expressions. The member shall still be
12250 // defined in a namespace scope if it is used in the program and the
12251 // namespace scope definition shall not contain an initializer.
12252 //
12253 // We already performed a redefinition check above, but for static
12254 // data members we also need to check whether there was an in-class
12255 // declaration with an initializer.
12256 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
12257 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
12258 << VDecl->getDeclName();
12259 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
12260 diag::note_previous_initializer)
12261 << 0;
12262 return;
12263 }
12264
12265 if (VDecl->hasLocalStorage())
12266 setFunctionHasBranchProtectedScope();
12267
12268 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
12269 VDecl->setInvalidDecl();
12270 return;
12271 }
12272 }
12273
12274 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
12275 // a kernel function cannot be initialized."
12276 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
12277 Diag(VDecl->getLocation(), diag::err_local_cant_init);
12278 VDecl->setInvalidDecl();
12279 return;
12280 }
12281
12282 // The LoaderUninitialized attribute acts as a definition (of undef).
12283 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
12284 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
12285 VDecl->setInvalidDecl();
12286 return;
12287 }
12288
12289 // Get the decls type and save a reference for later, since
12290 // CheckInitializerTypes may change it.
12291 QualType DclT = VDecl->getType(), SavT = DclT;
12292
12293 // Expressions default to 'id' when we're in a debugger
12294 // and we are assigning it to a variable of Objective-C pointer type.
12295 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
12296 Init->getType() == Context.UnknownAnyTy) {
12297 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12298 if (Result.isInvalid()) {
12299 VDecl->setInvalidDecl();
12300 return;
12301 }
12302 Init = Result.get();
12303 }
12304
12305 // Perform the initialization.
12306 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
12307 if (!VDecl->isInvalidDecl()) {
12308 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12309 InitializationKind Kind = InitializationKind::CreateForInit(
12310 VDecl->getLocation(), DirectInit, Init);
12311
12312 MultiExprArg Args = Init;
12313 if (CXXDirectInit)
12314 Args = MultiExprArg(CXXDirectInit->getExprs(),
12315 CXXDirectInit->getNumExprs());
12316
12317 // Try to correct any TypoExprs in the initialization arguments.
12318 for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
12319 ExprResult Res = CorrectDelayedTyposInExpr(
12320 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
12321 [this, Entity, Kind](Expr *E) {
12322 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
12323 return Init.Failed() ? ExprError() : E;
12324 });
12325 if (Res.isInvalid()) {
12326 VDecl->setInvalidDecl();
12327 } else if (Res.get() != Args[Idx]) {
12328 Args[Idx] = Res.get();
12329 }
12330 }
12331 if (VDecl->isInvalidDecl())
12332 return;
12333
12334 InitializationSequence InitSeq(*this, Entity, Kind, Args,
12335 /*TopLevelOfInitList=*/false,
12336 /*TreatUnavailableAsInvalid=*/false);
12337 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
12338 if (Result.isInvalid()) {
12339 // If the provied initializer fails to initialize the var decl,
12340 // we attach a recovery expr for better recovery.
12341 auto RecoveryExpr =
12342 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
12343 if (RecoveryExpr.get())
12344 VDecl->setInit(RecoveryExpr.get());
12345 return;
12346 }
12347
12348 Init = Result.getAs<Expr>();
12349 }
12350
12351 // Check for self-references within variable initializers.
12352 // Variables declared within a function/method body (except for references)
12353 // are handled by a dataflow analysis.
12354 // This is undefined behavior in C++, but valid in C.
12355 if (getLangOpts().CPlusPlus)
12356 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
12357 VDecl->getType()->isReferenceType())
12358 CheckSelfReference(*this, RealDecl, Init, DirectInit);
12359
12360 // If the type changed, it means we had an incomplete type that was
12361 // completed by the initializer. For example:
12362 // int ary[] = { 1, 3, 5 };
12363 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
12364 if (!VDecl->isInvalidDecl() && (DclT != SavT))
12365 VDecl->setType(DclT);
12366
12367 if (!VDecl->isInvalidDecl()) {
12368 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
12369
12370 if (VDecl->hasAttr<BlocksAttr>())
12371 checkRetainCycles(VDecl, Init);
12372
12373 // It is safe to assign a weak reference into a strong variable.
12374 // Although this code can still have problems:
12375 // id x = self.weakProp;
12376 // id y = self.weakProp;
12377 // we do not warn to warn spuriously when 'x' and 'y' are on separate
12378 // paths through the function. This should be revisited if
12379 // -Wrepeated-use-of-weak is made flow-sensitive.
12380 if (FunctionScopeInfo *FSI = getCurFunction())
12381 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
12382 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
12383 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12384 Init->getBeginLoc()))
12385 FSI->markSafeWeakUse(Init);
12386 }
12387
12388 // The initialization is usually a full-expression.
12389 //
12390 // FIXME: If this is a braced initialization of an aggregate, it is not
12391 // an expression, and each individual field initializer is a separate
12392 // full-expression. For instance, in:
12393 //
12394 // struct Temp { ~Temp(); };
12395 // struct S { S(Temp); };
12396 // struct T { S a, b; } t = { Temp(), Temp() }
12397 //
12398 // we should destroy the first Temp before constructing the second.
12399 ExprResult Result =
12400 ActOnFinishFullExpr(Init, VDecl->getLocation(),
12401 /*DiscardedValue*/ false, VDecl->isConstexpr());
12402 if (Result.isInvalid()) {
12403 VDecl->setInvalidDecl();
12404 return;
12405 }
12406 Init = Result.get();
12407
12408 // Attach the initializer to the decl.
12409 VDecl->setInit(Init);
12410
12411 if (VDecl->isLocalVarDecl()) {
12412 // Don't check the initializer if the declaration is malformed.
12413 if (VDecl->isInvalidDecl()) {
12414 // do nothing
12415
12416 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
12417 // This is true even in C++ for OpenCL.
12418 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
12419 CheckForConstantInitializer(Init, DclT);
12420
12421 // Otherwise, C++ does not restrict the initializer.
12422 } else if (getLangOpts().CPlusPlus) {
12423 // do nothing
12424
12425 // C99 6.7.8p4: All the expressions in an initializer for an object that has
12426 // static storage duration shall be constant expressions or string literals.
12427 } else if (VDecl->getStorageClass() == SC_Static) {
12428 CheckForConstantInitializer(Init, DclT);
12429
12430 // C89 is stricter than C99 for aggregate initializers.
12431 // C89 6.5.7p3: All the expressions [...] in an initializer list
12432 // for an object that has aggregate or union type shall be
12433 // constant expressions.
12434 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
12435 isa<InitListExpr>(Init)) {
12436 const Expr *Culprit;
12437 if (!Init->isConstantInitializer(Context, false, &Culprit)) {
12438 Diag(Culprit->getExprLoc(),
12439 diag::ext_aggregate_init_not_constant)
12440 << Culprit->getSourceRange();
12441 }
12442 }
12443
12444 if (auto *E = dyn_cast<ExprWithCleanups>(Init))
12445 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
12446 if (VDecl->hasLocalStorage())
12447 BE->getBlockDecl()->setCanAvoidCopyToHeap();
12448 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
12449 VDecl->getLexicalDeclContext()->isRecord()) {
12450 // This is an in-class initialization for a static data member, e.g.,
12451 //
12452 // struct S {
12453 // static const int value = 17;
12454 // };
12455
12456 // C++ [class.mem]p4:
12457 // A member-declarator can contain a constant-initializer only
12458 // if it declares a static member (9.4) of const integral or
12459 // const enumeration type, see 9.4.2.
12460 //
12461 // C++11 [class.static.data]p3:
12462 // If a non-volatile non-inline const static data member is of integral
12463 // or enumeration type, its declaration in the class definition can
12464 // specify a brace-or-equal-initializer in which every initializer-clause
12465 // that is an assignment-expression is a constant expression. A static
12466 // data member of literal type can be declared in the class definition
12467 // with the constexpr specifier; if so, its declaration shall specify a
12468 // brace-or-equal-initializer in which every initializer-clause that is
12469 // an assignment-expression is a constant expression.
12470
12471 // Do nothing on dependent types.
12472 if (DclT->isDependentType()) {
12473
12474 // Allow any 'static constexpr' members, whether or not they are of literal
12475 // type. We separately check that every constexpr variable is of literal
12476 // type.
12477 } else if (VDecl->isConstexpr()) {
12478
12479 // Require constness.
12480 } else if (!DclT.isConstQualified()) {
12481 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12482 << Init->getSourceRange();
12483 VDecl->setInvalidDecl();
12484
12485 // We allow integer constant expressions in all cases.
12486 } else if (DclT->isIntegralOrEnumerationType()) {
12487 // Check whether the expression is a constant expression.
12488 SourceLocation Loc;
12489 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12490 // In C++11, a non-constexpr const static data member with an
12491 // in-class initializer cannot be volatile.
12492 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12493 else if (Init->isValueDependent())
12494 ; // Nothing to check.
12495 else if (Init->isIntegerConstantExpr(Context, &Loc))
12496 ; // Ok, it's an ICE!
12497 else if (Init->getType()->isScopedEnumeralType() &&
12498 Init->isCXX11ConstantExpr(Context))
12499 ; // Ok, it is a scoped-enum constant expression.
12500 else if (Init->isEvaluatable(Context)) {
12501 // If we can constant fold the initializer through heroics, accept it,
12502 // but report this as a use of an extension for -pedantic.
12503 Diag(Loc, diag::ext_in_class_initializer_non_constant)
12504 << Init->getSourceRange();
12505 } else {
12506 // Otherwise, this is some crazy unknown case. Report the issue at the
12507 // location provided by the isIntegerConstantExpr failed check.
12508 Diag(Loc, diag::err_in_class_initializer_non_constant)
12509 << Init->getSourceRange();
12510 VDecl->setInvalidDecl();
12511 }
12512
12513 // We allow foldable floating-point constants as an extension.
12514 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12515 // In C++98, this is a GNU extension. In C++11, it is not, but we support
12516 // it anyway and provide a fixit to add the 'constexpr'.
12517 if (getLangOpts().CPlusPlus11) {
12518 Diag(VDecl->getLocation(),
12519 diag::ext_in_class_initializer_float_type_cxx11)
12520 << DclT << Init->getSourceRange();
12521 Diag(VDecl->getBeginLoc(),
12522 diag::note_in_class_initializer_float_type_cxx11)
12523 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12524 } else {
12525 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12526 << DclT << Init->getSourceRange();
12527
12528 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12529 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12530 << Init->getSourceRange();
12531 VDecl->setInvalidDecl();
12532 }
12533 }
12534
12535 // Suggest adding 'constexpr' in C++11 for literal types.
12536 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12537 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12538 << DclT << Init->getSourceRange()
12539 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12540 VDecl->setConstexpr(true);
12541
12542 } else {
12543 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12544 << DclT << Init->getSourceRange();
12545 VDecl->setInvalidDecl();
12546 }
12547 } else if (VDecl->isFileVarDecl()) {
12548 // In C, extern is typically used to avoid tentative definitions when
12549 // declaring variables in headers, but adding an intializer makes it a
12550 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12551 // In C++, extern is often used to give implictly static const variables
12552 // external linkage, so don't warn in that case. If selectany is present,
12553 // this might be header code intended for C and C++ inclusion, so apply the
12554 // C++ rules.
12555 if (VDecl->getStorageClass() == SC_Extern &&
12556 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12557 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12558 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12559 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12560 Diag(VDecl->getLocation(), diag::warn_extern_init);
12561
12562 // In Microsoft C++ mode, a const variable defined in namespace scope has
12563 // external linkage by default if the variable is declared with
12564 // __declspec(dllexport).
12565 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12566 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12567 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12568 VDecl->setStorageClass(SC_Extern);
12569
12570 // C99 6.7.8p4. All file scoped initializers need to be constant.
12571 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12572 CheckForConstantInitializer(Init, DclT);
12573 }
12574
12575 QualType InitType = Init->getType();
12576 if (!InitType.isNull() &&
12577 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12578 InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12579 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12580
12581 // We will represent direct-initialization similarly to copy-initialization:
12582 // int x(1); -as-> int x = 1;
12583 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12584 //
12585 // Clients that want to distinguish between the two forms, can check for
12586 // direct initializer using VarDecl::getInitStyle().
12587 // A major benefit is that clients that don't particularly care about which
12588 // exactly form was it (like the CodeGen) can handle both cases without
12589 // special case code.
12590
12591 // C++ 8.5p11:
12592 // The form of initialization (using parentheses or '=') is generally
12593 // insignificant, but does matter when the entity being initialized has a
12594 // class type.
12595 if (CXXDirectInit) {
12596 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.\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 12596, __extension__ __PRETTY_FUNCTION__))
;
12597 VDecl->setInitStyle(VarDecl::CallInit);
12598 } else if (DirectInit) {
12599 // This must be list-initialization. No other way is direct-initialization.
12600 VDecl->setInitStyle(VarDecl::ListInit);
12601 }
12602
12603 if (LangOpts.OpenMP && VDecl->isFileVarDecl())
12604 DeclsToCheckForDeferredDiags.insert(VDecl);
12605 CheckCompleteVariableDeclaration(VDecl);
12606}
12607
12608/// ActOnInitializerError - Given that there was an error parsing an
12609/// initializer for the given declaration, try to return to some form
12610/// of sanity.
12611void Sema::ActOnInitializerError(Decl *D) {
12612 // Our main concern here is re-establishing invariants like "a
12613 // variable's type is either dependent or complete".
12614 if (!D || D->isInvalidDecl()) return;
12615
12616 VarDecl *VD = dyn_cast<VarDecl>(D);
12617 if (!VD) return;
12618
12619 // Bindings are not usable if we can't make sense of the initializer.
12620 if (auto *DD = dyn_cast<DecompositionDecl>(D))
12621 for (auto *BD : DD->bindings())
12622 BD->setInvalidDecl();
12623
12624 // Auto types are meaningless if we can't make sense of the initializer.
12625 if (VD->getType()->isUndeducedType()) {
12626 D->setInvalidDecl();
12627 return;
12628 }
12629
12630 QualType Ty = VD->getType();
12631 if (Ty->isDependentType()) return;
12632
12633 // Require a complete type.
12634 if (RequireCompleteType(VD->getLocation(),
12635 Context.getBaseElementType(Ty),
12636 diag::err_typecheck_decl_incomplete_type)) {
12637 VD->setInvalidDecl();
12638 return;
12639 }
12640
12641 // Require a non-abstract type.
12642 if (RequireNonAbstractType(VD->getLocation(), Ty,
12643 diag::err_abstract_type_in_decl,
12644 AbstractVariableType)) {
12645 VD->setInvalidDecl();
12646 return;
12647 }
12648
12649 // Don't bother complaining about constructors or destructors,
12650 // though.
12651}
12652
12653void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
12654 // If there is no declaration, there was an error parsing it. Just ignore it.
12655 if (!RealDecl)
12656 return;
12657
12658 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12659 QualType Type = Var->getType();
12660
12661 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
12662 if (isa<DecompositionDecl>(RealDecl)) {
12663 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12664 Var->setInvalidDecl();
12665 return;
12666 }
12667
12668 if (Type->isUndeducedType() &&
12669 DeduceVariableDeclarationType(Var, false, nullptr))
12670 return;
12671
12672 // C++11 [class.static.data]p3: A static data member can be declared with
12673 // the constexpr specifier; if so, its declaration shall specify
12674 // a brace-or-equal-initializer.
12675 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12676 // the definition of a variable [...] or the declaration of a static data
12677 // member.
12678 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12679 !Var->isThisDeclarationADemotedDefinition()) {
12680 if (Var->isStaticDataMember()) {
12681 // C++1z removes the relevant rule; the in-class declaration is always
12682 // a definition there.
12683 if (!getLangOpts().CPlusPlus17 &&
12684 !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12685 Diag(Var->getLocation(),
12686 diag::err_constexpr_static_mem_var_requires_init)
12687 << Var;
12688 Var->setInvalidDecl();
12689 return;
12690 }
12691 } else {
12692 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12693 Var->setInvalidDecl();
12694 return;
12695 }
12696 }
12697
12698 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12699 // be initialized.
12700 if (!Var->isInvalidDecl() &&
12701 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12702 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12703 bool HasConstExprDefaultConstructor = false;
12704 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12705 for (auto *Ctor : RD->ctors()) {
12706 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
12707 Ctor->getMethodQualifiers().getAddressSpace() ==
12708 LangAS::opencl_constant) {
12709 HasConstExprDefaultConstructor = true;
12710 }
12711 }
12712 }
12713 if (!HasConstExprDefaultConstructor) {
12714 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12715 Var->setInvalidDecl();
12716 return;
12717 }
12718 }
12719
12720 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
12721 if (Var->getStorageClass() == SC_Extern) {
12722 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
12723 << Var;
12724 Var->setInvalidDecl();
12725 return;
12726 }
12727 if (RequireCompleteType(Var->getLocation(), Var->getType(),
12728 diag::err_typecheck_decl_incomplete_type)) {
12729 Var->setInvalidDecl();
12730 return;
12731 }
12732 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12733 if (!RD->hasTrivialDefaultConstructor()) {
12734 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
12735 Var->setInvalidDecl();
12736 return;
12737 }
12738 }
12739 // The declaration is unitialized, no need for further checks.
12740 return;
12741 }
12742
12743 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
12744 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
12745 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12746 checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
12747 NTCUC_DefaultInitializedObject, NTCUK_Init);
12748
12749
12750 switch (DefKind) {
12751 case VarDecl::Definition:
12752 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
12753 break;
12754
12755 // We have an out-of-line definition of a static data member
12756 // that has an in-class initializer, so we type-check this like
12757 // a declaration.
12758 //
12759 LLVM_FALLTHROUGH[[gnu::fallthrough]];
12760
12761 case VarDecl::DeclarationOnly:
12762 // It's only a declaration.
12763
12764 // Block scope. C99 6.7p7: If an identifier for an object is
12765 // declared with no linkage (C99 6.2.2p6), the type for the
12766 // object shall be complete.
12767 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
12768 !Var->hasLinkage() && !Var->isInvalidDecl() &&
12769 RequireCompleteType(Var->getLocation(), Type,
12770 diag::err_typecheck_decl_incomplete_type))
12771 Var->setInvalidDecl();
12772
12773 // Make sure that the type is not abstract.
12774 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12775 RequireNonAbstractType(Var->getLocation(), Type,
12776 diag::err_abstract_type_in_decl,
12777 AbstractVariableType))
12778 Var->setInvalidDecl();
12779 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12780 Var->getStorageClass() == SC_PrivateExtern) {
12781 Diag(Var->getLocation(), diag::warn_private_extern);
12782 Diag(Var->getLocation(), diag::note_private_extern);
12783 }
12784
12785 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
12786 !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
12787 ExternalDeclarations.push_back(Var);
12788
12789 return;
12790
12791 case VarDecl::TentativeDefinition:
12792 // File scope. C99 6.9.2p2: A declaration of an identifier for an
12793 // object that has file scope without an initializer, and without a
12794 // storage-class specifier or with the storage-class specifier "static",
12795 // constitutes a tentative definition. Note: A tentative definition with
12796 // external linkage is valid (C99 6.2.2p5).
12797 if (!Var->isInvalidDecl()) {
12798 if (const IncompleteArrayType *ArrayT
12799 = Context.getAsIncompleteArrayType(Type)) {
12800 if (RequireCompleteSizedType(
12801 Var->getLocation(), ArrayT->getElementType(),
12802 diag::err_array_incomplete_or_sizeless_type))
12803 Var->setInvalidDecl();
12804 } else if (Var->getStorageClass() == SC_Static) {
12805 // C99 6.9.2p3: If the declaration of an identifier for an object is
12806 // a tentative definition and has internal linkage (C99 6.2.2p3), the
12807 // declared type shall not be an incomplete type.
12808 // NOTE: code such as the following
12809 // static struct s;
12810 // struct s { int a; };
12811 // is accepted by gcc. Hence here we issue a warning instead of
12812 // an error and we do not invalidate the static declaration.
12813 // NOTE: to avoid multiple warnings, only check the first declaration.
12814 if (Var->isFirstDecl())
12815 RequireCompleteType(Var->getLocation(), Type,
12816 diag::ext_typecheck_decl_incomplete_type);
12817 }
12818 }
12819
12820 // Record the tentative definition; we're done.
12821 if (!Var->isInvalidDecl())
12822 TentativeDefinitions.push_back(Var);
12823 return;
12824 }
12825
12826 // Provide a specific diagnostic for uninitialized variable
12827 // definitions with incomplete array type.
12828 if (Type->isIncompleteArrayType()) {
12829 Diag(Var->getLocation(),
12830 diag::err_typecheck_incomplete_array_needs_initializer);
12831 Var->setInvalidDecl();
12832 return;
12833 }
12834
12835 // Provide a specific diagnostic for uninitialized variable
12836 // definitions with reference type.
12837 if (Type->isReferenceType()) {
12838 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
12839 << Var << SourceRange(Var->getLocation(), Var->getLocation());
12840 Var->setInvalidDecl();
12841 return;
12842 }
12843
12844 // Do not attempt to type-check the default initializer for a
12845 // variable with dependent type.
12846 if (Type->isDependentType())
12847 return;
12848
12849 if (Var->isInvalidDecl())
12850 return;
12851
12852 if (!Var->hasAttr<AliasAttr>()) {
12853 if (RequireCompleteType(Var->getLocation(),
12854 Context.getBaseElementType(Type),
12855 diag::err_typecheck_decl_incomplete_type)) {
12856 Var->setInvalidDecl();
12857 return;
12858 }
12859 } else {
12860 return;
12861 }
12862
12863 // The variable can not have an abstract class type.
12864 if (RequireNonAbstractType(Var->getLocation(), Type,
12865 diag::err_abstract_type_in_decl,
12866 AbstractVariableType)) {
12867 Var->setInvalidDecl();
12868 return;
12869 }
12870
12871 // Check for jumps past the implicit initializer. C++0x
12872 // clarifies that this applies to a "variable with automatic
12873 // storage duration", not a "local variable".
12874 // C++11 [stmt.dcl]p3
12875 // A program that jumps from a point where a variable with automatic
12876 // storage duration is not in scope to a point where it is in scope is
12877 // ill-formed unless the variable has scalar type, class type with a
12878 // trivial default constructor and a trivial destructor, a cv-qualified
12879 // version of one of these types, or an array of one of the preceding
12880 // types and is declared without an initializer.
12881 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
12882 if (const RecordType *Record
12883 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
12884 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
12885 // Mark the function (if we're in one) for further checking even if the
12886 // looser rules of C++11 do not require such checks, so that we can
12887 // diagnose incompatibilities with C++98.
12888 if (!CXXRecord->isPOD())
12889 setFunctionHasBranchProtectedScope();
12890 }
12891 }
12892 // In OpenCL, we can't initialize objects in the __local address space,
12893 // even implicitly, so don't synthesize an implicit initializer.
12894 if (getLangOpts().OpenCL &&
12895 Var->getType().getAddressSpace() == LangAS::opencl_local)
12896 return;
12897 // C++03 [dcl.init]p9:
12898 // If no initializer is specified for an object, and the
12899 // object is of (possibly cv-qualified) non-POD class type (or
12900 // array thereof), the object shall be default-initialized; if
12901 // the object is of const-qualified type, the underlying class
12902 // type shall have a user-declared default
12903 // constructor. Otherwise, if no initializer is specified for
12904 // a non- static object, the object and its subobjects, if
12905 // any, have an indeterminate initial value); if the object
12906 // or any of its subobjects are of const-qualified type, the
12907 // program is ill-formed.
12908 // C++0x [dcl.init]p11:
12909 // If no initializer is specified for an object, the object is
12910 // default-initialized; [...].
12911 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
12912 InitializationKind Kind
12913 = InitializationKind::CreateDefault(Var->getLocation());
12914
12915 InitializationSequence InitSeq(*this, Entity, Kind, None);
12916 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
12917
12918 if (Init.get()) {
12919 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
12920 // This is important for template substitution.
12921 Var->setInitStyle(VarDecl::CallInit);
12922 } else if (Init.isInvalid()) {
12923 // If default-init fails, attach a recovery-expr initializer to track
12924 // that initialization was attempted and failed.
12925 auto RecoveryExpr =
12926 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
12927 if (RecoveryExpr.get())
12928 Var->setInit(RecoveryExpr.get());
12929 }
12930
12931 CheckCompleteVariableDeclaration(Var);
12932 }
12933}
12934
12935void Sema::ActOnCXXForRangeDecl(Decl *D) {
12936 // If there is no declaration, there was an error parsing it. Ignore it.
12937 if (!D)
12938 return;
12939
12940 VarDecl *VD = dyn_cast<VarDecl>(D);
12941 if (!VD) {
12942 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
12943 D->setInvalidDecl();
12944 return;
12945 }
12946
12947 VD->setCXXForRangeDecl(true);
12948
12949 // for-range-declaration cannot be given a storage class specifier.
12950 int Error = -1;
12951 switch (VD->getStorageClass()) {
12952 case SC_None:
12953 break;
12954 case SC_Extern:
12955 Error = 0;
12956 break;
12957 case SC_Static:
12958 Error = 1;
12959 break;
12960 case SC_PrivateExtern:
12961 Error = 2;
12962 break;
12963 case SC_Auto:
12964 Error = 3;
12965 break;
12966 case SC_Register:
12967 Error = 4;
12968 break;
12969 }
12970
12971 // for-range-declaration cannot be given a storage class specifier con't.
12972 switch (VD->getTSCSpec()) {
12973 case TSCS_thread_local:
12974 Error = 6;
12975 break;
12976 case TSCS___thread:
12977 case TSCS__Thread_local:
12978 case TSCS_unspecified:
12979 break;
12980 }
12981
12982 if (Error != -1) {
12983 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
12984 << VD << Error;
12985 D->setInvalidDecl();
12986 }
12987}
12988
12989StmtResult
12990Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
12991 IdentifierInfo *Ident,
12992 ParsedAttributes &Attrs,
12993 SourceLocation AttrEnd) {
12994 // C++1y [stmt.iter]p1:
12995 // A range-based for statement of the form
12996 // for ( for-range-identifier : for-range-initializer ) statement
12997 // is equivalent to
12998 // for ( auto&& for-range-identifier : for-range-initializer ) statement
12999 DeclSpec DS(Attrs.getPool().getFactory());
13000
13001 const char *PrevSpec;
13002 unsigned DiagID;
13003 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
13004 getPrintingPolicy());
13005
13006 Declarator D(DS, DeclaratorContext::ForInit);
13007 D.SetIdentifier(Ident, IdentLoc);
13008 D.takeAttributes(Attrs, AttrEnd);
13009
13010 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
13011 IdentLoc);
13012 Decl *Var = ActOnDeclarator(S, D);
13013 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
13014 FinalizeDeclaration(Var);
13015 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
13016 AttrEnd.isValid() ? AttrEnd : IdentLoc);
13017}
13018
13019void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
13020 if (var->isInvalidDecl()) return;
13021
13022 MaybeAddCUDAConstantAttr(var);
13023
13024 if (getLangOpts().OpenCL) {
13025 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
13026 // initialiser
13027 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
13028 !var->hasInit()) {
13029 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
13030 << 1 /*Init*/;
13031 var->setInvalidDecl();
13032 return;
13033 }
13034 }
13035
13036 // In Objective-C, don't allow jumps past the implicit initialization of a
13037 // local retaining variable.
13038 if (getLangOpts().ObjC &&
13039 var->hasLocalStorage()) {
13040 switch (var->getType().getObjCLifetime()) {
13041 case Qualifiers::OCL_None:
13042 case Qualifiers::OCL_ExplicitNone:
13043 case Qualifiers::OCL_Autoreleasing:
13044 break;
13045
13046 case Qualifiers::OCL_Weak:
13047 case Qualifiers::OCL_Strong:
13048 setFunctionHasBranchProtectedScope();
13049 break;
13050 }
13051 }
13052
13053 if (var->hasLocalStorage() &&
13054 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
13055 setFunctionHasBranchProtectedScope();
13056
13057 // Warn about externally-visible variables being defined without a
13058 // prior declaration. We only want to do this for global
13059 // declarations, but we also specifically need to avoid doing it for
13060 // class members because the linkage of an anonymous class can
13061 // change if it's later given a typedef name.
13062 if (var->isThisDeclarationADefinition() &&
13063 var->getDeclContext()->getRedeclContext()->isFileContext() &&
13064 var->isExternallyVisible() && var->hasLinkage() &&
13065 !var->isInline() && !var->getDescribedVarTemplate() &&
13066 !isa<VarTemplatePartialSpecializationDecl>(var) &&
13067 !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
13068 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
13069 var->getLocation())) {
13070 // Find a previous declaration that's not a definition.
13071 VarDecl *prev = var->getPreviousDecl();
13072 while (prev && prev->isThisDeclarationADefinition())
13073 prev = prev->getPreviousDecl();
13074
13075 if (!prev) {
13076 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
13077 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
13078 << /* variable */ 0;
13079 }
13080 }
13081
13082 // Cache the result of checking for constant initialization.
13083 Optional<bool> CacheHasConstInit;
13084 const Expr *CacheCulprit = nullptr;
13085 auto checkConstInit = [&]() mutable {
13086 if (!CacheHasConstInit)
13087 CacheHasConstInit = var->getInit()->isConstantInitializer(
13088 Context, var->getType()->isReferenceType(), &CacheCulprit);
13089 return *CacheHasConstInit;
13090 };
13091
13092 if (var->getTLSKind() == VarDecl::TLS_Static) {
13093 if (var->getType().isDestructedType()) {
13094 // GNU C++98 edits for __thread, [basic.start.term]p3:
13095 // The type of an object with thread storage duration shall not
13096 // have a non-trivial destructor.
13097 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
13098 if (getLangOpts().CPlusPlus11)
13099 Diag(var->getLocation(), diag::note_use_thread_local);
13100 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
13101 if (!checkConstInit()) {
13102 // GNU C++98 edits for __thread, [basic.start.init]p4:
13103 // An object of thread storage duration shall not require dynamic
13104 // initialization.
13105 // FIXME: Need strict checking here.
13106 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
13107 << CacheCulprit->getSourceRange();
13108 if (getLangOpts().CPlusPlus11)
13109 Diag(var->getLocation(), diag::note_use_thread_local);
13110 }
13111 }
13112 }
13113
13114
13115 if (!var->getType()->isStructureType() && var->hasInit() &&
13116 isa<InitListExpr>(var->getInit())) {
13117 const auto *ILE = cast<InitListExpr>(var->getInit());
13118 unsigned NumInits = ILE->getNumInits();
13119 if (NumInits > 2)
13120 for (unsigned I = 0; I < NumInits; ++I) {
13121 const auto *Init = ILE->getInit(I);
13122 if (!Init)
13123 break;
13124 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13125 if (!SL)
13126 break;
13127
13128 unsigned NumConcat = SL->getNumConcatenated();
13129 // Diagnose missing comma in string array initialization.
13130 // Do not warn when all the elements in the initializer are concatenated
13131 // together. Do not warn for macros too.
13132 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
13133 bool OnlyOneMissingComma = true;
13134 for (unsigned J = I + 1; J < NumInits; ++J) {
13135 const auto *Init = ILE->getInit(J);
13136 if (!Init)
13137 break;
13138 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13139 if (!SLJ || SLJ->getNumConcatenated() > 1) {
13140 OnlyOneMissingComma = false;
13141 break;
13142 }
13143 }
13144
13145 if (OnlyOneMissingComma) {
13146 SmallVector<FixItHint, 1> Hints;
13147 for (unsigned i = 0; i < NumConcat - 1; ++i)
13148 Hints.push_back(FixItHint::CreateInsertion(
13149 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
13150
13151 Diag(SL->getStrTokenLoc(1),
13152 diag::warn_concatenated_literal_array_init)
13153 << Hints;
13154 Diag(SL->getBeginLoc(),
13155 diag::note_concatenated_string_literal_silence);
13156 }
13157 // In any case, stop now.
13158 break;
13159 }
13160 }
13161 }
13162
13163
13164 QualType type = var->getType();
13165
13166 if (var->hasAttr<BlocksAttr>())
13167 getCurFunction()->addByrefBlockVar(var);
13168
13169 Expr *Init = var->getInit();
13170 bool GlobalStorage = var->hasGlobalStorage();
13171 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
13172 QualType baseType = Context.getBaseElementType(type);
13173 bool HasConstInit = true;
13174
13175 // Check whether the initializer is sufficiently constant.
13176 if (getLangOpts().CPlusPlus && !type->isDependentType() && Init &&
13177 !Init->isValueDependent() &&
13178 (GlobalStorage || var->isConstexpr() ||
13179 var->mightBeUsableInConstantExpressions(Context))) {
13180 // If this variable might have a constant initializer or might be usable in
13181 // constant expressions, check whether or not it actually is now. We can't
13182 // do this lazily, because the result might depend on things that change
13183 // later, such as which constexpr functions happen to be defined.
13184 SmallVector<PartialDiagnosticAt, 8> Notes;
13185 if (!getLangOpts().CPlusPlus11) {
13186 // Prior to C++11, in contexts where a constant initializer is required,
13187 // the set of valid constant initializers is described by syntactic rules
13188 // in [expr.const]p2-6.
13189 // FIXME: Stricter checking for these rules would be useful for constinit /
13190 // -Wglobal-constructors.
13191 HasConstInit = checkConstInit();
13192
13193 // Compute and cache the constant value, and remember that we have a
13194 // constant initializer.
13195 if (HasConstInit) {
13196 (void)var->checkForConstantInitialization(Notes);
13197 Notes.clear();
13198 } else if (CacheCulprit) {
13199 Notes.emplace_back(CacheCulprit->getExprLoc(),
13200 PDiag(diag::note_invalid_subexpr_in_const_expr));
13201 Notes.back().second << CacheCulprit->getSourceRange();
13202 }
13203 } else {
13204 // Evaluate the initializer to see if it's a constant initializer.
13205 HasConstInit = var->checkForConstantInitialization(Notes);
13206 }
13207
13208 if (HasConstInit) {
13209 // FIXME: Consider replacing the initializer with a ConstantExpr.
13210 } else if (var->isConstexpr()) {
13211 SourceLocation DiagLoc = var->getLocation();
13212 // If the note doesn't add any useful information other than a source
13213 // location, fold it into the primary diagnostic.
13214 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13215 diag::note_invalid_subexpr_in_const_expr) {
13216 DiagLoc = Notes[0].first;
13217 Notes.clear();
13218 }
13219 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
13220 << var << Init->getSourceRange();
13221 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
13222 Diag(Notes[I].first, Notes[I].second);
13223 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
13224 auto *Attr = var->getAttr<ConstInitAttr>();
13225 Diag(var->getLocation(), diag::err_require_constant_init_failed)
13226 << Init->getSourceRange();
13227 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
13228 << Attr->getRange() << Attr->isConstinit();
13229 for (auto &it : Notes)
13230 Diag(it.first, it.second);
13231 } else if (IsGlobal &&
13232 !getDiagnostics().isIgnored(diag::warn_global_constructor,
13233 var->getLocation())) {
13234 // Warn about globals which don't have a constant initializer. Don't
13235 // warn about globals with a non-trivial destructor because we already
13236 // warned about them.
13237 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
13238 if (!(RD && !RD->hasTrivialDestructor())) {
13239 // checkConstInit() here permits trivial default initialization even in
13240 // C++11 onwards, where such an initializer is not a constant initializer
13241 // but nonetheless doesn't require a global constructor.
13242 if (!checkConstInit())
13243 Diag(var->getLocation(), diag::warn_global_constructor)
13244 << Init->getSourceRange();
13245 }
13246 }
13247 }
13248
13249 // Apply section attributes and pragmas to global variables.
13250 if (GlobalStorage && var->isThisDeclarationADefinition() &&
13251 !inTemplateInstantiation()) {
13252 PragmaStack<StringLiteral *> *Stack = nullptr;
13253 int SectionFlags = ASTContext::PSF_Read;
13254 if (var->getType().isConstQualified()) {
13255 if (HasConstInit)
13256 Stack = &ConstSegStack;
13257 else {
13258 Stack = &BSSSegStack;
13259 SectionFlags |= ASTContext::PSF_Write;
13260 }
13261 } else if (var->hasInit() && HasConstInit) {
13262 Stack = &DataSegStack;
13263 SectionFlags |= ASTContext::PSF_Write;
13264 } else {
13265 Stack = &BSSSegStack;
13266 SectionFlags |= ASTContext::PSF_Write;
13267 }
13268 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
13269 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
13270 SectionFlags |= ASTContext::PSF_Implicit;
13271 UnifySection(SA->getName(), SectionFlags, var);
13272 } else if (Stack->CurrentValue) {
13273 SectionFlags |= ASTContext::PSF_Implicit;
13274 auto SectionName = Stack->CurrentValue->getString();
13275 var->addAttr(SectionAttr::CreateImplicit(
13276 Context, SectionName, Stack->CurrentPragmaLocation,
13277 AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
13278 if (UnifySection(SectionName, SectionFlags, var))
13279 var->dropAttr<SectionAttr>();
13280 }
13281
13282 // Apply the init_seg attribute if this has an initializer. If the
13283 // initializer turns out to not be dynamic, we'll end up ignoring this
13284 // attribute.
13285 if (CurInitSeg && var->getInit())
13286 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
13287 CurInitSegLoc,
13288 AttributeCommonInfo::AS_Pragma));
13289 }
13290
13291 // All the following checks are C++ only.
13292 if (!getLangOpts().CPlusPlus) {
13293 // If this variable must be emitted, add it as an initializer for the
13294 // current module.
13295 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13296 Context.addModuleInitializer(ModuleScopes.back().Module, var);
13297 return;
13298 }
13299
13300 // Require the destructor.
13301 if (!type->isDependentType())
13302 if (const RecordType *recordType = baseType->getAs<RecordType>())
13303 FinalizeVarWithDestructor(var, recordType);
13304
13305 // If this variable must be emitted, add it as an initializer for the current
13306 // module.
13307 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13308 Context.addModuleInitializer(ModuleScopes.back().Module, var);
13309
13310 // Build the bindings if this is a structured binding declaration.
13311 if (auto *DD = dyn_cast<DecompositionDecl>(var))
13312 CheckCompleteDecompositionDeclaration(DD);
13313}
13314
13315/// Check if VD needs to be dllexport/dllimport due to being in a
13316/// dllexport/import function.
13317void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
13318 assert(VD->isStaticLocal())(static_cast <bool> (VD->isStaticLocal()) ? void (0)
: __assert_fail ("VD->isStaticLocal()", "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 13318, __extension__ __PRETTY_FUNCTION__))
;
13319
13320 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13321
13322 // Find outermost function when VD is in lambda function.
13323 while (FD && !getDLLAttr(FD) &&
13324 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
13325 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
13326 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
13327 }
13328
13329 if (!FD)
13330 return;
13331
13332 // Static locals inherit dll attributes from their function.
13333 if (Attr *A = getDLLAttr(FD)) {
13334 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
13335 NewAttr->setInherited(true);
13336 VD->addAttr(NewAttr);
13337 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
13338 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
13339 NewAttr->setInherited(true);
13340 VD->addAttr(NewAttr);
13341
13342 // Export this function to enforce exporting this static variable even
13343 // if it is not used in this compilation unit.
13344 if (!FD->hasAttr<DLLExportAttr>())
13345 FD->addAttr(NewAttr);
13346
13347 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
13348 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
13349 NewAttr->setInherited(true);
13350 VD->addAttr(NewAttr);
13351 }
13352}
13353
13354/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
13355/// any semantic actions necessary after any initializer has been attached.
13356void Sema::FinalizeDeclaration(Decl *ThisDecl) {
13357 // Note that we are no longer parsing the initializer for this declaration.
13358 ParsingInitForAutoVars.erase(ThisDecl);
13359
13360 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
13361 if (!VD)
13362 return;
13363
13364 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
13365 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
13366 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
13367 if (PragmaClangBSSSection.Valid)
13368 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
13369 Context, PragmaClangBSSSection.SectionName,
13370 PragmaClangBSSSection.PragmaLocation,
13371 AttributeCommonInfo::AS_Pragma));
13372 if (PragmaClangDataSection.Valid)
13373 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
13374 Context, PragmaClangDataSection.SectionName,
13375 PragmaClangDataSection.PragmaLocation,
13376 AttributeCommonInfo::AS_Pragma));
13377 if (PragmaClangRodataSection.Valid)
13378 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
13379 Context, PragmaClangRodataSection.SectionName,
13380 PragmaClangRodataSection.PragmaLocation,
13381 AttributeCommonInfo::AS_Pragma));
13382 if (PragmaClangRelroSection.Valid)
13383 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
13384 Context, PragmaClangRelroSection.SectionName,
13385 PragmaClangRelroSection.PragmaLocation,
13386 AttributeCommonInfo::AS_Pragma));
13387 }
13388
13389 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
13390 for (auto *BD : DD->bindings()) {
13391 FinalizeDeclaration(BD);
13392 }
13393 }
13394
13395 checkAttributesAfterMerging(*this, *VD);
13396
13397 // Perform TLS alignment check here after attributes attached to the variable
13398 // which may affect the alignment have been processed. Only perform the check
13399 // if the target has a maximum TLS alignment (zero means no constraints).
13400 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
13401 // Protect the check so that it's not performed on dependent types and
13402 // dependent alignments (we can't determine the alignment in that case).
13403 if (VD->getTLSKind() && !VD->hasDependentAlignment()) {
13404 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
13405 if (Context.getDeclAlign(VD) > MaxAlignChars) {
13406 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
13407 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
13408 << (unsigned)MaxAlignChars.getQuantity();
13409 }
13410 }
13411 }
13412
13413 if (VD->isStaticLocal())
13414 CheckStaticLocalForDllExport(VD);
13415
13416 // Perform check for initializers of device-side global variables.
13417 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
13418 // 7.5). We must also apply the same checks to all __shared__
13419 // variables whether they are local or not. CUDA also allows
13420 // constant initializers for __constant__ and __device__ variables.
13421 if (getLangOpts().CUDA)
13422 checkAllowedCUDAInitializer(VD);
13423
13424 // Grab the dllimport or dllexport attribute off of the VarDecl.
13425 const InheritableAttr *DLLAttr = getDLLAttr(VD);
13426
13427 // Imported static data members cannot be defined out-of-line.
13428 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
13429 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
13430 VD->isThisDeclarationADefinition()) {
13431 // We allow definitions of dllimport class template static data members
13432 // with a warning.
13433 CXXRecordDecl *Context =
13434 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
13435 bool IsClassTemplateMember =
13436 isa<ClassTemplatePartialSpecializationDecl>(Context) ||
13437 Context->getDescribedClassTemplate();
13438
13439 Diag(VD->getLocation(),
13440 IsClassTemplateMember
13441 ? diag::warn_attribute_dllimport_static_field_definition
13442 : diag::err_attribute_dllimport_static_field_definition);
13443 Diag(IA->getLocation(), diag::note_attribute);
13444 if (!IsClassTemplateMember)
13445 VD->setInvalidDecl();
13446 }
13447 }
13448
13449 // dllimport/dllexport variables cannot be thread local, their TLS index
13450 // isn't exported with the variable.
13451 if (DLLAttr && VD->getTLSKind()) {
13452 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13453 if (F && getDLLAttr(F)) {
13454 assert(VD->isStaticLocal())(static_cast <bool> (VD->isStaticLocal()) ? void (0)
: __assert_fail ("VD->isStaticLocal()", "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 13454, __extension__ __PRETTY_FUNCTION__))
;
13455 // But if this is a static local in a dlimport/dllexport function, the
13456 // function will never be inlined, which means the var would never be
13457 // imported, so having it marked import/export is safe.
13458 } else {
13459 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
13460 << DLLAttr;
13461 VD->setInvalidDecl();
13462 }
13463 }
13464
13465 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
13466 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13467 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13468 << Attr;
13469 VD->dropAttr<UsedAttr>();
13470 }
13471 }
13472 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
13473 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13474 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13475 << Attr;
13476 VD->dropAttr<RetainAttr>();
13477 }
13478 }
13479
13480 const DeclContext *DC = VD->getDeclContext();
13481 // If there's a #pragma GCC visibility in scope, and this isn't a class
13482 // member, set the visibility of this variable.
13483 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
13484 AddPushedVisibilityAttribute(VD);
13485
13486 // FIXME: Warn on unused var template partial specializations.
13487 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
13488 MarkUnusedFileScopedDecl(VD);
13489
13490 // Now we have parsed the initializer and can update the table of magic
13491 // tag values.
13492 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
13493 !VD->getType()->isIntegralOrEnumerationType())
13494 return;
13495
13496 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
13497 const Expr *MagicValueExpr = VD->getInit();
13498 if (!MagicValueExpr) {
13499 continue;
13500 }
13501 Optional<llvm::APSInt> MagicValueInt;
13502 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
13503 Diag(I->getRange().getBegin(),
13504 diag::err_type_tag_for_datatype_not_ice)
13505 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13506 continue;
13507 }
13508 if (MagicValueInt->getActiveBits() > 64) {
13509 Diag(I->getRange().getBegin(),
13510 diag::err_type_tag_for_datatype_too_large)
13511 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13512 continue;
13513 }
13514 uint64_t MagicValue = MagicValueInt->getZExtValue();
13515 RegisterTypeTagForDatatype(I->getArgumentKind(),
13516 MagicValue,
13517 I->getMatchingCType(),
13518 I->getLayoutCompatible(),
13519 I->getMustBeNull());
13520 }
13521}
13522
13523static bool hasDeducedAuto(DeclaratorDecl *DD) {
13524 auto *VD = dyn_cast<VarDecl>(DD);
13525 return VD && !VD->getType()->hasAutoForTrailingReturnType();
13526}
13527
13528Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
13529 ArrayRef<Decl *> Group) {
13530 SmallVector<Decl*, 8> Decls;
13531
13532 if (DS.isTypeSpecOwned())
13533 Decls.push_back(DS.getRepAsDecl());
13534
13535 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
13536 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
13537 bool DiagnosedMultipleDecomps = false;
13538 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
13539 bool DiagnosedNonDeducedAuto = false;
13540
13541 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13542 if (Decl *D = Group[i]) {
13543 // For declarators, there are some additional syntactic-ish checks we need
13544 // to perform.
13545 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
13546 if (!FirstDeclaratorInGroup)
13547 FirstDeclaratorInGroup = DD;
13548 if (!FirstDecompDeclaratorInGroup)
13549 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
13550 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
13551 !hasDeducedAuto(DD))
13552 FirstNonDeducedAutoInGroup = DD;
13553
13554 if (FirstDeclaratorInGroup != DD) {
13555 // A decomposition declaration cannot be combined with any other
13556 // declaration in the same group.
13557 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
13558 Diag(FirstDecompDeclaratorInGroup->getLocation(),
13559 diag::err_decomp_decl_not_alone)
13560 << FirstDeclaratorInGroup->getSourceRange()
13561 << DD->getSourceRange();
13562 DiagnosedMultipleDecomps = true;
13563 }
13564
13565 // A declarator that uses 'auto' in any way other than to declare a
13566 // variable with a deduced type cannot be combined with any other
13567 // declarator in the same group.
13568 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
13569 Diag(FirstNonDeducedAutoInGroup->getLocation(),
13570 diag::err_auto_non_deduced_not_alone)
13571 << FirstNonDeducedAutoInGroup->getType()
13572 ->hasAutoForTrailingReturnType()
13573 << FirstDeclaratorInGroup->getSourceRange()
13574 << DD->getSourceRange();
13575 DiagnosedNonDeducedAuto = true;
13576 }
13577 }
13578 }
13579
13580 Decls.push_back(D);
13581 }
13582 }
13583
13584 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
13585 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13586 handleTagNumbering(Tag, S);
13587 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13588 getLangOpts().CPlusPlus)
13589 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
13590 }
13591 }
13592
13593 return BuildDeclaratorGroup(Decls);
13594}
13595
13596/// BuildDeclaratorGroup - convert a list of declarations into a declaration
13597/// group, performing any necessary semantic checking.
13598Sema::DeclGroupPtrTy
13599Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
13600 // C++14 [dcl.spec.auto]p7: (DR1347)
13601 // If the type that replaces the placeholder type is not the same in each
13602 // deduction, the program is ill-formed.
13603 if (Group.size() > 1) {
13604 QualType Deduced;
13605 VarDecl *DeducedDecl = nullptr;
13606 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13607 VarDecl *D = dyn_cast<VarDecl>(Group[i]);
13608 if (!D || D->isInvalidDecl())
13609 break;
13610 DeducedType *DT = D->getType()->getContainedDeducedType();
13611 if (!DT || DT->getDeducedType().isNull())
13612 continue;
13613 if (Deduced.isNull()) {
13614 Deduced = DT->getDeducedType();
13615 DeducedDecl = D;
13616 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
13617 auto *AT = dyn_cast<AutoType>(DT);
13618 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
13619 diag::err_auto_different_deductions)
13620 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
13621 << DeducedDecl->getDeclName() << DT->getDeducedType()
13622 << D->getDeclName();
13623 if (DeducedDecl->hasInit())
13624 Dia << DeducedDecl->getInit()->getSourceRange();
13625 if (D->getInit())
13626 Dia << D->getInit()->getSourceRange();
13627 D->setInvalidDecl();
13628 break;
13629 }
13630 }
13631 }
13632
13633 ActOnDocumentableDecls(Group);
13634
13635 return DeclGroupPtrTy::make(
13636 DeclGroupRef::Create(Context, Group.data(), Group.size()));
13637}
13638
13639void Sema::ActOnDocumentableDecl(Decl *D) {
13640 ActOnDocumentableDecls(D);
13641}
13642
13643void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
13644 // Don't parse the comment if Doxygen diagnostics are ignored.
13645 if (Group.empty() || !Group[0])
13646 return;
13647
13648 if (Diags.isIgnored(diag::warn_doc_param_not_found,
13649 Group[0]->getLocation()) &&
13650 Diags.isIgnored(diag::warn_unknown_comment_command_name,
13651 Group[0]->getLocation()))
13652 return;
13653
13654 if (Group.size() >= 2) {
13655 // This is a decl group. Normally it will contain only declarations
13656 // produced from declarator list. But in case we have any definitions or
13657 // additional declaration references:
13658 // 'typedef struct S {} S;'
13659 // 'typedef struct S *S;'
13660 // 'struct S *pS;'
13661 // FinalizeDeclaratorGroup adds these as separate declarations.
13662 Decl *MaybeTagDecl = Group[0];
13663 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
13664 Group = Group.slice(1);
13665 }
13666 }
13667
13668 // FIMXE: We assume every Decl in the group is in the same file.
13669 // This is false when preprocessor constructs the group from decls in
13670 // different files (e. g. macros or #include).
13671 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
13672}
13673
13674/// Common checks for a parameter-declaration that should apply to both function
13675/// parameters and non-type template parameters.
13676void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
13677 // Check that there are no default arguments inside the type of this
13678 // parameter.
13679 if (getLangOpts().CPlusPlus)
13680 CheckExtraCXXDefaultArguments(D);
13681
13682 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
13683 if (D.getCXXScopeSpec().isSet()) {
13684 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
13685 << D.getCXXScopeSpec().getRange();
13686 }
13687
13688 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
13689 // simple identifier except [...irrelevant cases...].
13690 switch (D.getName().getKind()) {
13691 case UnqualifiedIdKind::IK_Identifier:
13692 break;
13693
13694 case UnqualifiedIdKind::IK_OperatorFunctionId:
13695 case UnqualifiedIdKind::IK_ConversionFunctionId:
13696 case UnqualifiedIdKind::IK_LiteralOperatorId:
13697 case UnqualifiedIdKind::IK_ConstructorName:
13698 case UnqualifiedIdKind::IK_DestructorName:
13699 case UnqualifiedIdKind::IK_ImplicitSelfParam:
13700 case UnqualifiedIdKind::IK_DeductionGuideName:
13701 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
13702 << GetNameForDeclarator(D).getName();
13703 break;
13704
13705 case UnqualifiedIdKind::IK_TemplateId:
13706 case UnqualifiedIdKind::IK_ConstructorTemplateId:
13707 // GetNameForDeclarator would not produce a useful name in this case.
13708 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
13709 break;
13710 }
13711}
13712
13713/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
13714/// to introduce parameters into function prototype scope.
13715Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
13716 const DeclSpec &DS = D.getDeclSpec();
13717
13718 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
13719
13720 // C++03 [dcl.stc]p2 also permits 'auto'.
13721 StorageClass SC = SC_None;
13722 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
13723 SC = SC_Register;
13724 // In C++11, the 'register' storage class specifier is deprecated.
13725 // In C++17, it is not allowed, but we tolerate it as an extension.
13726 if (getLangOpts().CPlusPlus11) {
13727 Diag(DS.getStorageClassSpecLoc(),
13728 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
13729 : diag::warn_deprecated_register)
13730 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
13731 }
13732 } else if (getLangOpts().CPlusPlus &&
13733 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
13734 SC = SC_Auto;
13735 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
13736 Diag(DS.getStorageClassSpecLoc(),
13737 diag::err_invalid_storage_class_in_func_decl);
13738 D.getMutableDeclSpec().ClearStorageClassSpecs();
13739 }
13740
13741 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
13742 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
13743 << DeclSpec::getSpecifierName(TSCS);
13744 if (DS.isInlineSpecified())
13745 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
13746 << getLangOpts().CPlusPlus17;
13747 if (DS.hasConstexprSpecifier())
13748 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
13749 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
13750
13751 DiagnoseFunctionSpecifiers(DS);
13752
13753 CheckFunctionOrTemplateParamDeclarator(S, D);
13754
13755 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13756 QualType parmDeclType = TInfo->getType();
13757
13758 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
13759 IdentifierInfo *II = D.getIdentifier();
13760 if (II) {
13761 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
13762 ForVisibleRedeclaration);
13763 LookupName(R, S);
13764 if (R.isSingleResult()) {
13765 NamedDecl *PrevDecl = R.getFoundDecl();
13766 if (PrevDecl->isTemplateParameter()) {
13767 // Maybe we will complain about the shadowed template parameter.
13768 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13769 // Just pretend that we didn't see the previous declaration.
13770 PrevDecl = nullptr;
13771 } else if (S->isDeclScope(PrevDecl)) {
13772 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
13773 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13774
13775 // Recover by removing the name
13776 II = nullptr;
13777 D.SetIdentifier(nullptr, D.getIdentifierLoc());
13778 D.setInvalidType(true);
13779 }
13780 }
13781 }
13782
13783 // Temporarily put parameter variables in the translation unit, not
13784 // the enclosing context. This prevents them from accidentally
13785 // looking like class members in C++.
13786 ParmVarDecl *New =
13787 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
13788 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
13789
13790 if (D.isInvalidType())
13791 New->setInvalidDecl();
13792
13793 assert(S->isFunctionPrototypeScope())(static_cast <bool> (S->isFunctionPrototypeScope()) ?
void (0) : __assert_fail ("S->isFunctionPrototypeScope()"
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 13793, __extension__ __PRETTY_FUNCTION__))
;
13794 assert(S->getFunctionPrototypeDepth() >= 1)(static_cast <bool> (S->getFunctionPrototypeDepth() >=
1) ? void (0) : __assert_fail ("S->getFunctionPrototypeDepth() >= 1"
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 13794, __extension__ __PRETTY_FUNCTION__))
;
13795 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
13796 S->getNextFunctionPrototypeIndex());
13797
13798 // Add the parameter declaration into this scope.
13799 S->AddDecl(New);
13800 if (II)
13801 IdResolver.AddDecl(New);
13802
13803 ProcessDeclAttributes(S, New, D);
13804
13805 if (D.getDeclSpec().isModulePrivateSpecified())
13806 Diag(New->getLocation(), diag::err_module_private_local)
13807 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13808 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13809
13810 if (New->hasAttr<BlocksAttr>()) {
13811 Diag(New->getLocation(), diag::err_block_on_nonlocal);
13812 }
13813
13814 if (getLangOpts().OpenCL)
13815 deduceOpenCLAddressSpace(New);
13816
13817 return New;
13818}
13819
13820/// Synthesizes a variable for a parameter arising from a
13821/// typedef.
13822ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
13823 SourceLocation Loc,
13824 QualType T) {
13825 /* FIXME: setting StartLoc == Loc.
13826 Would it be worth to modify callers so as to provide proper source
13827 location for the unnamed parameters, embedding the parameter's type? */
13828 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
13829 T, Context.getTrivialTypeSourceInfo(T, Loc),
13830 SC_None, nullptr);
13831 Param->setImplicit();
13832 return Param;
13833}
13834
13835void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
13836 // Don't diagnose unused-parameter errors in template instantiations; we
13837 // will already have done so in the template itself.
13838 if (inTemplateInstantiation())
13839 return;
13840
13841 for (const ParmVarDecl *Parameter : Parameters) {
13842 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
13843 !Parameter->hasAttr<UnusedAttr>()) {
13844 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
13845 << Parameter->getDeclName();
13846 }
13847 }
13848}
13849
13850void Sema::DiagnoseSizeOfParametersAndReturnValue(
13851 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
13852 if (LangOpts.NumLargeByValueCopy == 0) // No check.
13853 return;
13854
13855 // Warn if the return value is pass-by-value and larger than the specified
13856 // threshold.
13857 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
13858 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
13859 if (Size > LangOpts.NumLargeByValueCopy)
13860 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
13861 }
13862
13863 // Warn if any parameter is pass-by-value and larger than the specified
13864 // threshold.
13865 for (const ParmVarDecl *Parameter : Parameters) {
13866 QualType T = Parameter->getType();
13867 if (T->isDependentType() || !T.isPODType(Context))
13868 continue;
13869 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
13870 if (Size > LangOpts.NumLargeByValueCopy)
13871 Diag(Parameter->getLocation(), diag::warn_parameter_size)
13872 << Parameter << Size;
13873 }
13874}
13875
13876ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
13877 SourceLocation NameLoc, IdentifierInfo *Name,
13878 QualType T, TypeSourceInfo *TSInfo,
13879 StorageClass SC) {
13880 // In ARC, infer a lifetime qualifier for appropriate parameter types.
13881 if (getLangOpts().ObjCAutoRefCount &&
13882 T.getObjCLifetime() == Qualifiers::OCL_None &&
13883 T->isObjCLifetimeType()) {
13884
13885 Qualifiers::ObjCLifetime lifetime;
13886
13887 // Special cases for arrays:
13888 // - if it's const, use __unsafe_unretained
13889 // - otherwise, it's an error
13890 if (T->isArrayType()) {
13891 if (!T.isConstQualified()) {
13892 if (DelayedDiagnostics.shouldDelayDiagnostics())
13893 DelayedDiagnostics.add(
13894 sema::DelayedDiagnostic::makeForbiddenType(
13895 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
13896 else
13897 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
13898 << TSInfo->getTypeLoc().getSourceRange();
13899 }
13900 lifetime = Qualifiers::OCL_ExplicitNone;
13901 } else {
13902 lifetime = T->getObjCARCImplicitLifetime();
13903 }
13904 T = Context.getLifetimeQualifiedType(T, lifetime);
13905 }
13906
13907 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
13908 Context.getAdjustedParameterType(T),
13909 TSInfo, SC, nullptr);
13910
13911 // Make a note if we created a new pack in the scope of a lambda, so that
13912 // we know that references to that pack must also be expanded within the
13913 // lambda scope.
13914 if (New->isParameterPack())
13915 if (auto *LSI = getEnclosingLambda())
13916 LSI->LocalPacks.push_back(New);
13917
13918 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
13919 New->getType().hasNonTrivialToPrimitiveCopyCUnion())
13920 checkNonTrivialCUnion(New->getType(), New->getLocation(),
13921 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
13922
13923 // Parameters can not be abstract class types.
13924 // For record types, this is done by the AbstractClassUsageDiagnoser once
13925 // the class has been completely parsed.
13926 if (!CurContext->isRecord() &&
13927 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
13928 AbstractParamType))
13929 New->setInvalidDecl();
13930
13931 // Parameter declarators cannot be interface types. All ObjC objects are
13932 // passed by reference.
13933 if (T->isObjCObjectType()) {
13934 SourceLocation TypeEndLoc =
13935 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
13936 Diag(NameLoc,
13937 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
13938 << FixItHint::CreateInsertion(TypeEndLoc, "*");
13939 T = Context.getObjCObjectPointerType(T);
13940 New->setType(T);
13941 }
13942
13943 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
13944 // duration shall not be qualified by an address-space qualifier."
13945 // Since all parameters have automatic store duration, they can not have
13946 // an address space.
13947 if (T.getAddressSpace() != LangAS::Default &&
13948 // OpenCL allows function arguments declared to be an array of a type
13949 // to be qualified with an address space.
13950 !(getLangOpts().OpenCL &&
13951 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
13952 Diag(NameLoc, diag::err_arg_with_address_space);
13953 New->setInvalidDecl();
13954 }
13955
13956 // PPC MMA non-pointer types are not allowed as function argument types.
13957 if (Context.getTargetInfo().getTriple().isPPC64() &&
13958 CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
13959 New->setInvalidDecl();
13960 }
13961
13962 return New;
13963}
13964
13965void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
13966 SourceLocation LocAfterDecls) {
13967 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
13968
13969 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
13970 // for a K&R function.
13971 if (!FTI.hasPrototype) {
13972 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
13973 --i;
13974 if (FTI.Params[i].Param == nullptr) {
13975 SmallString<256> Code;
13976 llvm::raw_svector_ostream(Code)
13977 << " int " << FTI.Params[i].Ident->getName() << ";\n";
13978 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
13979 << FTI.Params[i].Ident
13980 << FixItHint::CreateInsertion(LocAfterDecls, Code);
13981
13982 // Implicitly declare the argument as type 'int' for lack of a better
13983 // type.
13984 AttributeFactory attrs;
13985 DeclSpec DS(attrs);
13986 const char* PrevSpec; // unused
13987 unsigned DiagID; // unused
13988 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
13989 DiagID, Context.getPrintingPolicy());
13990 // Use the identifier location for the type source range.
13991 DS.SetRangeStart(FTI.Params[i].IdentLoc);
13992 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
13993 Declarator ParamD(DS, DeclaratorContext::KNRTypeList);
13994 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
13995 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
13996 }
13997 }
13998 }
13999}
14000
14001Decl *
14002Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
14003 MultiTemplateParamsArg TemplateParameterLists,
14004 SkipBodyInfo *SkipBody) {
14005 assert(getCurFunctionDecl() == nullptr && "Function parsing confused")(static_cast <bool> (getCurFunctionDecl() == nullptr &&
"Function parsing confused") ? void (0) : __assert_fail ("getCurFunctionDecl() == nullptr && \"Function parsing confused\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 14005, __extension__ __PRETTY_FUNCTION__))
;
14006 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!\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 14006, __extension__ __PRETTY_FUNCTION__))
;
14007 Scope *ParentScope = FnBodyScope->getParent();
14008
14009 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
14010 // we define a non-templated function definition, we will create a declaration
14011 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
14012 // The base function declaration will have the equivalent of an `omp declare
14013 // variant` annotation which specifies the mangled definition as a
14014 // specialization function under the OpenMP context defined as part of the
14015 // `omp begin declare variant`.
14016 SmallVector<FunctionDecl *, 4> Bases;
14017 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
14018 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
14019 ParentScope, D, TemplateParameterLists, Bases);
14020
14021 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
14022 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
14023 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
14024
14025 if (!Bases.empty())
14026 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
14027
14028 return Dcl;
14029}
14030
14031void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
14032 Consumer.HandleInlineFunctionDefinition(D);
14033}
14034
14035static bool
14036ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
14037 const FunctionDecl *&PossiblePrototype) {
14038 // Don't warn about invalid declarations.
14039 if (FD->isInvalidDecl())
14040 return false;
14041
14042 // Or declarations that aren't global.
14043 if (!FD->isGlobal())
14044 return false;
14045
14046 // Don't warn about C++ member functions.
14047 if (isa<CXXMethodDecl>(FD))
14048 return false;
14049
14050 // Don't warn about 'main'.
14051 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
14052 if (IdentifierInfo *II = FD->getIdentifier())
14053 if (II->isStr("main") || II->isStr("efi_main"))
14054 return false;
14055
14056 // Don't warn about inline functions.
14057 if (FD->isInlined())
14058 return false;
14059
14060 // Don't warn about function templates.
14061 if (FD->getDescribedFunctionTemplate())
14062 return false;
14063
14064 // Don't warn about function template specializations.
14065 if (FD->isFunctionTemplateSpecialization())
14066 return false;
14067
14068 // Don't warn for OpenCL kernels.
14069 if (FD->hasAttr<OpenCLKernelAttr>())
14070 return false;
14071
14072 // Don't warn on explicitly deleted functions.
14073 if (FD->isDeleted())
14074 return false;
14075
14076 for (const FunctionDecl *Prev = FD->getPreviousDecl();
14077 Prev; Prev = Prev->getPreviousDecl()) {
14078 // Ignore any declarations that occur in function or method
14079 // scope, because they aren't visible from the header.
14080 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
14081 continue;
14082
14083 PossiblePrototype = Prev;
14084 return Prev->getType()->isFunctionNoProtoType();
14085 }
14086
14087 return true;
14088}
14089
14090void
14091Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
14092 const FunctionDecl *EffectiveDefinition,
14093 SkipBodyInfo *SkipBody) {
14094 const FunctionDecl *Definition = EffectiveDefinition;
14095 if (!Definition &&
14096 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
14097 return;
14098
14099 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
14100 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
14101 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
14102 // A merged copy of the same function, instantiated as a member of
14103 // the same class, is OK.
14104 if (declaresSameEntity(OrigFD, OrigDef) &&
14105 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
14106 cast<Decl>(FD->getLexicalDeclContext())))
14107 return;
14108 }
14109 }
14110 }
14111
14112 if (canRedefineFunction(Definition, getLangOpts()))
14113 return;
14114
14115 // Don't emit an error when this is redefinition of a typo-corrected
14116 // definition.
14117 if (TypoCorrectedFunctionDefinitions.count(Definition))
14118 return;
14119
14120 // If we don't have a visible definition of the function, and it's inline or
14121 // a template, skip the new definition.
14122 if (SkipBody && !hasVisibleDefinition(Definition) &&
14123 (Definition->getFormalLinkage() == InternalLinkage ||
14124 Definition->isInlined() ||
14125 Definition->getDescribedFunctionTemplate() ||
14126 Definition->getNumTemplateParameterLists())) {
14127 SkipBody->ShouldSkip = true;
14128 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
14129 if (auto *TD = Definition->getDescribedFunctionTemplate())
14130 makeMergedDefinitionVisible(TD);
14131 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
14132 return;
14133 }
14134
14135 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
14136 Definition->getStorageClass() == SC_Extern)
14137 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
14138 << FD << getLangOpts().CPlusPlus;
14139 else
14140 Diag(FD->getLocation(), diag::err_redefinition) << FD;
14141
14142 Diag(Definition->getLocation(), diag::note_previous_definition);
14143 FD->setInvalidDecl();
14144}
14145
14146static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
14147 Sema &S) {
14148 CXXRecordDecl *const LambdaClass = CallOperator->getParent();
14149
14150 LambdaScopeInfo *LSI = S.PushLambdaScope();
14151 LSI->CallOperator = CallOperator;
14152 LSI->Lambda = LambdaClass;
14153 LSI->ReturnType = CallOperator->getReturnType();
14154 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
14155
14156 if (LCD == LCD_None)
14157 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
14158 else if (LCD == LCD_ByCopy)
14159 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
14160 else if (LCD == LCD_ByRef)
14161 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
14162 DeclarationNameInfo DNI = CallOperator->getNameInfo();
14163
14164 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
14165 LSI->Mutable = !CallOperator->isConst();
14166
14167 // Add the captures to the LSI so they can be noted as already
14168 // captured within tryCaptureVar.
14169 auto I = LambdaClass->field_begin();
14170 for (const auto &C : LambdaClass->captures()) {
14171 if (C.capturesVariable()) {
14172 VarDecl *VD = C.getCapturedVar();
14173 if (VD->isInitCapture())
14174 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
14175 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
14176 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
14177 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
14178 /*EllipsisLoc*/C.isPackExpansion()
14179 ? C.getEllipsisLoc() : SourceLocation(),
14180 I->getType(), /*Invalid*/false);
14181
14182 } else if (C.capturesThis()) {
14183 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
14184 C.getCaptureKind() == LCK_StarThis);
14185 } else {
14186 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
14187 I->getType());
14188 }
14189 ++I;
14190 }
14191}
14192
14193Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
14194 SkipBodyInfo *SkipBody) {
14195 if (!D) {
14196 // Parsing the function declaration failed in some way. Push on a fake scope
14197 // anyway so we can try to parse the function body.
14198 PushFunctionScope();
14199 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14200 return D;
14201 }
14202
14203 FunctionDecl *FD = nullptr;
14204
14205 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
14206 FD = FunTmpl->getTemplatedDecl();
14207 else
14208 FD = cast<FunctionDecl>(D);
14209
14210 // Do not push if it is a lambda because one is already pushed when building
14211 // the lambda in ActOnStartOfLambdaDefinition().
14212 if (!isLambdaCallOperator(FD))
14213 PushExpressionEvaluationContext(
14214 FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
14215 : ExprEvalContexts.back().Context);
14216
14217 // Check for defining attributes before the check for redefinition.
14218 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
14219 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
14220 FD->dropAttr<AliasAttr>();
14221 FD->setInvalidDecl();
14222 }
14223 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
14224 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
14225 FD->dropAttr<IFuncAttr>();
14226 FD->setInvalidDecl();
14227 }
14228
14229 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
14230 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
14231 Ctor->isDefaultConstructor() &&
14232 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14233 // If this is an MS ABI dllexport default constructor, instantiate any
14234 // default arguments.
14235 InstantiateDefaultCtorDefaultArgs(Ctor);
14236 }
14237 }
14238
14239 // See if this is a redefinition. If 'will have body' (or similar) is already
14240 // set, then these checks were already performed when it was set.
14241 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
14242 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
14243 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
14244
14245 // If we're skipping the body, we're done. Don't enter the scope.
14246 if (SkipBody && SkipBody->ShouldSkip)
14247 return D;
14248 }
14249
14250 // Mark this function as "will have a body eventually". This lets users to
14251 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
14252 // this function.
14253 FD->setWillHaveBody();
14254
14255 // If we are instantiating a generic lambda call operator, push
14256 // a LambdaScopeInfo onto the function stack. But use the information
14257 // that's already been calculated (ActOnLambdaExpr) to prime the current
14258 // LambdaScopeInfo.
14259 // When the template operator is being specialized, the LambdaScopeInfo,
14260 // has to be properly restored so that tryCaptureVariable doesn't try
14261 // and capture any new variables. In addition when calculating potential
14262 // captures during transformation of nested lambdas, it is necessary to
14263 // have the LSI properly restored.
14264 if (isGenericLambdaCallOperatorSpecialization(FD)) {
14265 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!\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 14267, __extension__ __PRETTY_FUNCTION__))
14266 "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!\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 14267, __extension__ __PRETTY_FUNCTION__))
14267 "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!\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 14267, __extension__ __PRETTY_FUNCTION__))
;
14268 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
14269 } else {
14270 // Enter a new function scope
14271 PushFunctionScope();
14272 }
14273
14274 // Builtin functions cannot be defined.
14275 if (unsigned BuiltinID = FD->getBuiltinID()) {
14276 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
14277 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
14278 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
14279 FD->setInvalidDecl();
14280 }
14281 }
14282
14283 // The return type of a function definition must be complete
14284 // (C99 6.9.1p3, C++ [dcl.fct]p6).
14285 QualType ResultType = FD->getReturnType();
14286 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
14287 !FD->isInvalidDecl() &&
14288 RequireCompleteType(FD->getLocation(), ResultType,
14289 diag::err_func_def_incomplete_result))
14290 FD->setInvalidDecl();
14291
14292 if (FnBodyScope)
14293 PushDeclContext(FnBodyScope, FD);
14294
14295 // Check the validity of our function parameters
14296 CheckParmsForFunctionDef(FD->parameters(),
14297 /*CheckParameterNames=*/true);
14298
14299 // Add non-parameter declarations already in the function to the current
14300 // scope.
14301 if (FnBodyScope) {
14302 for (Decl *NPD : FD->decls()) {
14303 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
14304 if (!NonParmDecl)
14305 continue;
14306 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 14307, __extension__ __PRETTY_FUNCTION__))
14307 "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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 14307, __extension__ __PRETTY_FUNCTION__))
;
14308
14309 // If the decl has a name, make it accessible in the current scope.
14310 if (NonParmDecl->getDeclName())
14311 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
14312
14313 // Similarly, dive into enums and fish their constants out, making them
14314 // accessible in this scope.
14315 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
14316 for (auto *EI : ED->enumerators())
14317 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
14318 }
14319 }
14320 }
14321
14322 // Introduce our parameters into the function scope
14323 for (auto Param : FD->parameters()) {
14324 Param->setOwningFunction(FD);
14325
14326 // If this has an identifier, add it to the scope stack.
14327 if (Param->getIdentifier() && FnBodyScope) {
14328 CheckShadow(FnBodyScope, Param);
14329
14330 PushOnScopeChains(Param, FnBodyScope);
14331 }
14332 }
14333
14334 // Ensure that the function's exception specification is instantiated.
14335 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
14336 ResolveExceptionSpec(D->getLocation(), FPT);
14337
14338 // dllimport cannot be applied to non-inline function definitions.
14339 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
14340 !FD->isTemplateInstantiation()) {
14341 assert(!FD->hasAttr<DLLExportAttr>())(static_cast <bool> (!FD->hasAttr<DLLExportAttr>
()) ? void (0) : __assert_fail ("!FD->hasAttr<DLLExportAttr>()"
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 14341, __extension__ __PRETTY_FUNCTION__))
;
14342 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
14343 FD->setInvalidDecl();
14344 return D;
14345 }
14346 // We want to attach documentation to original Decl (which might be
14347 // a function template).
14348 ActOnDocumentableDecl(D);
14349 if (getCurLexicalContext()->isObjCContainer() &&
14350 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
14351 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
14352 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
14353
14354 return D;
14355}
14356
14357/// Given the set of return statements within a function body,
14358/// compute the variables that are subject to the named return value
14359/// optimization.
14360///
14361/// Each of the variables that is subject to the named return value
14362/// optimization will be marked as NRVO variables in the AST, and any
14363/// return statement that has a marked NRVO variable as its NRVO candidate can
14364/// use the named return value optimization.
14365///
14366/// This function applies a very simplistic algorithm for NRVO: if every return
14367/// statement in the scope of a variable has the same NRVO candidate, that
14368/// candidate is an NRVO variable.
14369void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
14370 ReturnStmt **Returns = Scope->Returns.data();
14371
14372 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
14373 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
14374 if (!NRVOCandidate->isNRVOVariable())
14375 Returns[I]->setNRVOCandidate(nullptr);
14376 }
14377 }
14378}
14379
14380bool Sema::canDelayFunctionBody(const Declarator &D) {
14381 // We can't delay parsing the body of a constexpr function template (yet).
14382 if (D.getDeclSpec().hasConstexprSpecifier())
14383 return false;
14384
14385 // We can't delay parsing the body of a function template with a deduced
14386 // return type (yet).
14387 if (D.getDeclSpec().hasAutoTypeSpec()) {
14388 // If the placeholder introduces a non-deduced trailing return type,
14389 // we can still delay parsing it.
14390 if (D.getNumTypeObjects()) {
14391 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
14392 if (Outer.Kind == DeclaratorChunk::Function &&
14393 Outer.Fun.hasTrailingReturnType()) {
14394 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
14395 return Ty.isNull() || !Ty->isUndeducedType();
14396 }
14397 }
14398 return false;
14399 }
14400
14401 return true;
14402}
14403
14404bool Sema::canSkipFunctionBody(Decl *D) {
14405 // We cannot skip the body of a function (or function template) which is
14406 // constexpr, since we may need to evaluate its body in order to parse the
14407 // rest of the file.
14408 // We cannot skip the body of a function with an undeduced return type,
14409 // because any callers of that function need to know the type.
14410 if (const FunctionDecl *FD = D->getAsFunction()) {
14411 if (FD->isConstexpr())
14412 return false;
14413 // We can't simply call Type::isUndeducedType here, because inside template
14414 // auto can be deduced to a dependent type, which is not considered
14415 // "undeduced".
14416 if (FD->getReturnType()->getContainedDeducedType())
14417 return false;
14418 }
14419 return Consumer.shouldSkipFunctionBody(D);
14420}
14421
14422Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
14423 if (!Decl)
14424 return nullptr;
14425 if (FunctionDecl *FD = Decl->getAsFunction())
14426 FD->setHasSkippedBody();
14427 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
14428 MD->setHasSkippedBody();
14429 return Decl;
14430}
14431
14432Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
14433 return ActOnFinishFunctionBody(D, BodyArg, false);
14434}
14435
14436/// RAII object that pops an ExpressionEvaluationContext when exiting a function
14437/// body.
14438class ExitFunctionBodyRAII {
14439public:
14440 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
14441 ~ExitFunctionBodyRAII() {
14442 if (!IsLambda)
14443 S.PopExpressionEvaluationContext();
14444 }
14445
14446private:
14447 Sema &S;
14448 bool IsLambda = false;
14449};
14450
14451static void diagnoseImplicitlyRetainedSelf(Sema &S) {
14452 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
14453
14454 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
14455 if (EscapeInfo.count(BD))
14456 return EscapeInfo[BD];
14457
14458 bool R = false;
14459 const BlockDecl *CurBD = BD;
14460
14461 do {
14462 R = !CurBD->doesNotEscape();
14463 if (R)
14464 break;
14465 CurBD = CurBD->getParent()->getInnermostBlockDecl();
14466 } while (CurBD);
14467
14468 return EscapeInfo[BD] = R;
14469 };
14470
14471 // If the location where 'self' is implicitly retained is inside a escaping
14472 // block, emit a diagnostic.
14473 for (const std::pair<SourceLocation, const BlockDecl *> &P :
14474 S.ImplicitlyRetainedSelfLocs)
14475 if (IsOrNestedInEscapingBlock(P.second))
14476 S.Diag(P.first, diag::warn_implicitly_retains_self)
14477 << FixItHint::CreateInsertion(P.first, "self->");
14478}
14479
14480Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
14481 bool IsInstantiation) {
14482 FunctionScopeInfo *FSI = getCurFunction();
14483 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
14484
14485 if (FSI->UsesFPIntrin && !FD->hasAttr<StrictFPAttr>())
14486 FD->addAttr(StrictFPAttr::CreateImplicit(Context));
14487
14488 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14489 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
14490
14491 if (getLangOpts().Coroutines && FSI->isCoroutine())
14492 CheckCompletedCoroutineBody(FD, Body);
14493
14494 // Do not call PopExpressionEvaluationContext() if it is a lambda because one
14495 // is already popped when finishing the lambda in BuildLambdaExpr(). This is
14496 // meant to pop the context added in ActOnStartOfFunctionDef().
14497 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
14498
14499 if (FD) {
14500 FD->setBody(Body);
14501 FD->setWillHaveBody(false);
14502
14503 if (getLangOpts().CPlusPlus14) {
14504 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
14505 FD->getReturnType()->isUndeducedType()) {
14506 // If the function has a deduced result type but contains no 'return'
14507 // statements, the result type as written must be exactly 'auto', and
14508 // the deduced result type is 'void'.
14509 if (!FD->getReturnType()->getAs<AutoType>()) {
14510 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
14511 << FD->getReturnType();
14512 FD->setInvalidDecl();
14513 } else {
14514 // Substitute 'void' for the 'auto' in the type.
14515 TypeLoc ResultType = getReturnTypeLoc(FD);
14516 Context.adjustDeducedFunctionResultType(
14517 FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
14518 }
14519 }
14520 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
14521 // In C++11, we don't use 'auto' deduction rules for lambda call
14522 // operators because we don't support return type deduction.
14523 auto *LSI = getCurLambda();
14524 if (LSI->HasImplicitReturnType) {
14525 deduceClosureReturnType(*LSI);
14526
14527 // C++11 [expr.prim.lambda]p4:
14528 // [...] if there are no return statements in the compound-statement
14529 // [the deduced type is] the type void
14530 QualType RetType =
14531 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
14532
14533 // Update the return type to the deduced type.
14534 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
14535 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
14536 Proto->getExtProtoInfo()));
14537 }
14538 }
14539
14540 // If the function implicitly returns zero (like 'main') or is naked,
14541 // don't complain about missing return statements.
14542 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
14543 WP.disableCheckFallThrough();
14544
14545 // MSVC permits the use of pure specifier (=0) on function definition,
14546 // defined at class scope, warn about this non-standard construct.
14547 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
14548 Diag(FD->getLocation(), diag::ext_pure_function_definition);
14549
14550 if (!FD->isInvalidDecl()) {
14551 // Don't diagnose unused parameters of defaulted or deleted functions.
14552 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
14553 DiagnoseUnusedParameters(FD->parameters());
14554 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
14555 FD->getReturnType(), FD);
14556
14557 // If this is a structor, we need a vtable.
14558 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
14559 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
14560 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
14561 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
14562
14563 // Try to apply the named return value optimization. We have to check
14564 // if we can do this here because lambdas keep return statements around
14565 // to deduce an implicit return type.
14566 if (FD->getReturnType()->isRecordType() &&
14567 (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
14568 computeNRVO(Body, FSI);
14569 }
14570
14571 // GNU warning -Wmissing-prototypes:
14572 // Warn if a global function is defined without a previous
14573 // prototype declaration. This warning is issued even if the
14574 // definition itself provides a prototype. The aim is to detect
14575 // global functions that fail to be declared in header files.
14576 const FunctionDecl *PossiblePrototype = nullptr;
14577 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
14578 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
14579
14580 if (PossiblePrototype) {
14581 // We found a declaration that is not a prototype,
14582 // but that could be a zero-parameter prototype
14583 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
14584 TypeLoc TL = TI->getTypeLoc();
14585 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
14586 Diag(PossiblePrototype->getLocation(),
14587 diag::note_declaration_not_a_prototype)
14588 << (FD->getNumParams() != 0)
14589 << (FD->getNumParams() == 0
14590 ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
14591 : FixItHint{});
14592 }
14593 } else {
14594 // Returns true if the token beginning at this Loc is `const`.
14595 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
14596 const LangOptions &LangOpts) {
14597 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
14598 if (LocInfo.first.isInvalid())
14599 return false;
14600
14601 bool Invalid = false;
14602 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
14603 if (Invalid)
14604 return false;
14605
14606 if (LocInfo.second > Buffer.size())
14607 return false;
14608
14609 const char *LexStart = Buffer.data() + LocInfo.second;
14610 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
14611
14612 return StartTok.consume_front("const") &&
14613 (StartTok.empty() || isWhitespace(StartTok[0]) ||
14614 StartTok.startswith("/*") || StartTok.startswith("//"));
14615 };
14616
14617 auto findBeginLoc = [&]() {
14618 // If the return type has `const` qualifier, we want to insert
14619 // `static` before `const` (and not before the typename).
14620 if ((FD->getReturnType()->isAnyPointerType() &&
14621 FD->getReturnType()->getPointeeType().isConstQualified()) ||
14622 FD->getReturnType().isConstQualified()) {
14623 // But only do this if we can determine where the `const` is.
14624
14625 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
14626 getLangOpts()))
14627
14628 return FD->getBeginLoc();
14629 }
14630 return FD->getTypeSpecStartLoc();
14631 };
14632 Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14633 << /* function */ 1
14634 << (FD->getStorageClass() == SC_None
14635 ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
14636 : FixItHint{});
14637 }
14638
14639 // GNU warning -Wstrict-prototypes
14640 // Warn if K&R function is defined without a previous declaration.
14641 // This warning is issued only if the definition itself does not provide
14642 // a prototype. Only K&R definitions do not provide a prototype.
14643 if (!FD->hasWrittenPrototype()) {
14644 TypeSourceInfo *TI = FD->getTypeSourceInfo();
14645 TypeLoc TL = TI->getTypeLoc();
14646 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
14647 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
14648 }
14649 }
14650
14651 // Warn on CPUDispatch with an actual body.
14652 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
14653 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
14654 if (!CmpndBody->body_empty())
14655 Diag(CmpndBody->body_front()->getBeginLoc(),
14656 diag::warn_dispatch_body_ignored);
14657
14658 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
14659 const CXXMethodDecl *KeyFunction;
14660 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
14661 MD->isVirtual() &&
14662 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
14663 MD == KeyFunction->getCanonicalDecl()) {
14664 // Update the key-function state if necessary for this ABI.
14665 if (FD->isInlined() &&
14666 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
14667 Context.setNonKeyFunction(MD);
14668
14669 // If the newly-chosen key function is already defined, then we
14670 // need to mark the vtable as used retroactively.
14671 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
14672 const FunctionDecl *Definition;
14673 if (KeyFunction && KeyFunction->isDefined(Definition))
14674 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
14675 } else {
14676 // We just defined they key function; mark the vtable as used.
14677 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
14678 }
14679 }
14680 }
14681
14682 assert((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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 14683, __extension__ __PRETTY_FUNCTION__))
14683 "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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 14683, __extension__ __PRETTY_FUNCTION__))
;
14684 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
14685 assert(MD == getCurMethodDecl() && "Method parsing confused")(static_cast <bool> (MD == getCurMethodDecl() &&
"Method parsing confused") ? void (0) : __assert_fail ("MD == getCurMethodDecl() && \"Method parsing confused\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 14685, __extension__ __PRETTY_FUNCTION__))
;
14686 MD->setBody(Body);
14687 if (!MD->isInvalidDecl()) {
14688 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
14689 MD->getReturnType(), MD);
14690
14691 if (Body)
14692 computeNRVO(Body, FSI);
14693 }
14694 if (FSI->ObjCShouldCallSuper) {
14695 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
14696 << MD->getSelector().getAsString();
14697 FSI->ObjCShouldCallSuper = false;
14698 }
14699 if (FSI->ObjCWarnForNoDesignatedInitChain) {
14700 const ObjCMethodDecl *InitMethod = nullptr;
14701 bool isDesignated =
14702 MD->isDesignatedInitializerForTheInterface(&InitMethod);
14703 assert(isDesignated && InitMethod)(static_cast <bool> (isDesignated && InitMethod
) ? void (0) : __assert_fail ("isDesignated && InitMethod"
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 14703, __extension__ __PRETTY_FUNCTION__))
;
14704 (void)isDesignated;
14705
14706 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
14707 auto IFace = MD->getClassInterface();
14708 if (!IFace)
14709 return false;
14710 auto SuperD = IFace->getSuperClass();
14711 if (!SuperD)
14712 return false;
14713 return SuperD->getIdentifier() ==
14714 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
14715 };
14716 // Don't issue this warning for unavailable inits or direct subclasses
14717 // of NSObject.
14718 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
14719 Diag(MD->getLocation(),
14720 diag::warn_objc_designated_init_missing_super_call);
14721 Diag(InitMethod->getLocation(),
14722 diag::note_objc_designated_init_marked_here);
14723 }
14724 FSI->ObjCWarnForNoDesignatedInitChain = false;
14725 }
14726 if (FSI->ObjCWarnForNoInitDelegation) {
14727 // Don't issue this warning for unavaialable inits.
14728 if (!MD->isUnavailable())
14729 Diag(MD->getLocation(),
14730 diag::warn_objc_secondary_init_missing_init_call);
14731 FSI->ObjCWarnForNoInitDelegation = false;
14732 }
14733
14734 diagnoseImplicitlyRetainedSelf(*this);
14735 } else {
14736 // Parsing the function declaration failed in some way. Pop the fake scope
14737 // we pushed on.
14738 PopFunctionScopeInfo(ActivePolicy, dcl);
14739 return nullptr;
14740 }
14741
14742 if (Body && FSI->HasPotentialAvailabilityViolations)
14743 DiagnoseUnguardedAvailabilityViolations(dcl);
14744
14745 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.\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 14747, __extension__ __PRETTY_FUNCTION__))
14746 "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.\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 14747, __extension__ __PRETTY_FUNCTION__))
14747 "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.\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 14747, __extension__ __PRETTY_FUNCTION__))
;
14748
14749 // Verify and clean out per-function state.
14750 if (Body && (!FD || !FD->isDefaulted())) {
14751 // C++ constructors that have function-try-blocks can't have return
14752 // statements in the handlers of that block. (C++ [except.handle]p14)
14753 // Verify this.
14754 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
14755 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
14756
14757 // Verify that gotos and switch cases don't jump into scopes illegally.
14758 if (FSI->NeedsScopeChecking() &&
14759 !PP.isCodeCompletionEnabled())
14760 DiagnoseInvalidJumps(Body);
14761
14762 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
14763 if (!Destructor->getParent()->isDependentType())
14764 CheckDestructor(Destructor);
14765
14766 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14767 Destructor->getParent());
14768 }
14769
14770 // If any errors have occurred, clear out any temporaries that may have
14771 // been leftover. This ensures that these temporaries won't be picked up for
14772 // deletion in some later function.
14773 if (hasUncompilableErrorOccurred() ||
14774 getDiagnostics().getSuppressAllDiagnostics()) {
14775 DiscardCleanupsInEvaluationContext();
14776 }
14777 if (!hasUncompilableErrorOccurred() &&
14778 !isa<FunctionTemplateDecl>(dcl)) {
14779 // Since the body is valid, issue any analysis-based warnings that are
14780 // enabled.
14781 ActivePolicy = &WP;
14782 }
14783
14784 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
14785 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
14786 FD->setInvalidDecl();
14787
14788 if (FD && FD->hasAttr<NakedAttr>()) {
14789 for (const Stmt *S : Body->children()) {
14790 // Allow local register variables without initializer as they don't
14791 // require prologue.
14792 bool RegisterVariables = false;
14793 if (auto *DS = dyn_cast<DeclStmt>(S)) {
14794 for (const auto *Decl : DS->decls()) {
14795 if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
14796 RegisterVariables =
14797 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
14798 if (!RegisterVariables)
14799 break;
14800 }
14801 }
14802 }
14803 if (RegisterVariables)
14804 continue;
14805 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
14806 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
14807 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
14808 FD->setInvalidDecl();
14809 break;
14810 }
14811 }
14812 }
14813
14814 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 14816, __extension__ __PRETTY_FUNCTION__))
14815 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 14816, __extension__ __PRETTY_FUNCTION__))
14816 "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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 14816, __extension__ __PRETTY_FUNCTION__))
;
14817 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function")(static_cast <bool> (!Cleanup.exprNeedsCleanups() &&
"Unaccounted cleanups in function") ? void (0) : __assert_fail
("!Cleanup.exprNeedsCleanups() && \"Unaccounted cleanups in function\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 14817, __extension__ __PRETTY_FUNCTION__))
;
14818 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 14819, __extension__ __PRETTY_FUNCTION__))
14819 "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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 14819, __extension__ __PRETTY_FUNCTION__))
;
14820 }
14821
14822 if (!IsInstantiation)
14823 PopDeclContext();
14824
14825 PopFunctionScopeInfo(ActivePolicy, dcl);
14826 // If any errors have occurred, clear out any temporaries that may have
14827 // been leftover. This ensures that these temporaries won't be picked up for
14828 // deletion in some later function.
14829 if (hasUncompilableErrorOccurred()) {
14830 DiscardCleanupsInEvaluationContext();
14831 }
14832
14833 if (FD && (LangOpts.OpenMP || LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
14834 auto ES = getEmissionStatus(FD);
14835 if (ES == Sema::FunctionEmissionStatus::Emitted ||
14836 ES == Sema::FunctionEmissionStatus::Unknown)
14837 DeclsToCheckForDeferredDiags.insert(FD);
14838 }
14839
14840 return dcl;
14841}
14842
14843/// When we finish delayed parsing of an attribute, we must attach it to the
14844/// relevant Decl.
14845void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
14846 ParsedAttributes &Attrs) {
14847 // Always attach attributes to the underlying decl.
14848 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
14849 D = TD->getTemplatedDecl();
14850 ProcessDeclAttributeList(S, D, Attrs);
14851
14852 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
14853 if (Method->isStatic())
14854 checkThisInStaticMemberFunctionAttributes(Method);
14855}
14856
14857/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
14858/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
14859NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
14860 IdentifierInfo &II, Scope *S) {
14861 // Find the scope in which the identifier is injected and the corresponding
14862 // DeclContext.
14863 // FIXME: C89 does not say what happens if there is no enclosing block scope.
14864 // In that case, we inject the declaration into the translation unit scope
14865 // instead.
14866 Scope *BlockScope = S;
14867 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
14868 BlockScope = BlockScope->getParent();
14869
14870 Scope *ContextScope = BlockScope;
14871 while (!ContextScope->getEntity())
14872 ContextScope = ContextScope->getParent();
14873 ContextRAII SavedContext(*this, ContextScope->getEntity());
14874
14875 // Before we produce a declaration for an implicitly defined
14876 // function, see whether there was a locally-scoped declaration of
14877 // this name as a function or variable. If so, use that
14878 // (non-visible) declaration, and complain about it.
14879 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
14880 if (ExternCPrev) {
14881 // We still need to inject the function into the enclosing block scope so
14882 // that later (non-call) uses can see it.
14883 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
14884
14885 // C89 footnote 38:
14886 // If in fact it is not defined as having type "function returning int",
14887 // the behavior is undefined.
14888 if (!isa<FunctionDecl>(ExternCPrev) ||
14889 !Context.typesAreCompatible(
14890 cast<FunctionDecl>(ExternCPrev)->getType(),
14891 Context.getFunctionNoProtoType(Context.IntTy))) {
14892 Diag(Loc, diag::ext_use_out_of_scope_declaration)
14893 << ExternCPrev << !getLangOpts().C99;
14894 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
14895 return ExternCPrev;
14896 }
14897 }
14898
14899 // Extension in C99. Legal in C90, but warn about it.
14900 unsigned diag_id;
14901 if (II.getName().startswith("__builtin_"))
14902 diag_id = diag::warn_builtin_unknown;
14903 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
14904 else if (getLangOpts().OpenCL)
14905 diag_id = diag::err_opencl_implicit_function_decl;
14906 else if (getLangOpts().C99)
14907 diag_id = diag::ext_implicit_function_decl;
14908 else
14909 diag_id = diag::warn_implicit_function_decl;
14910 Diag(Loc, diag_id) << &II;
14911
14912 // If we found a prior declaration of this function, don't bother building
14913 // another one. We've already pushed that one into scope, so there's nothing
14914 // more to do.
14915 if (ExternCPrev)
14916 return ExternCPrev;
14917
14918 // Because typo correction is expensive, only do it if the implicit
14919 // function declaration is going to be treated as an error.
14920 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
14921 TypoCorrection Corrected;
14922 DeclFilterCCC<FunctionDecl> CCC{};
14923 if (S && (Corrected =
14924 CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
14925 S, nullptr, CCC, CTK_NonError)))
14926 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
14927 /*ErrorRecovery*/false);
14928 }
14929
14930 // Set a Declarator for the implicit definition: int foo();
14931 const char *Dummy;
14932 AttributeFactory attrFactory;
14933 DeclSpec DS(attrFactory);
14934 unsigned DiagID;
14935 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
14936 Context.getPrintingPolicy());
14937 (void)Error; // Silence warning.
14938 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!\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 14938, __extension__ __PRETTY_FUNCTION__))
;
14939 SourceLocation NoLoc;
14940 Declarator D(DS, DeclaratorContext::Block);
14941 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
14942 /*IsAmbiguous=*/false,
14943 /*LParenLoc=*/NoLoc,
14944 /*Params=*/nullptr,
14945 /*NumParams=*/0,
14946 /*EllipsisLoc=*/NoLoc,
14947 /*RParenLoc=*/NoLoc,
14948 /*RefQualifierIsLvalueRef=*/true,
14949 /*RefQualifierLoc=*/NoLoc,
14950 /*MutableLoc=*/NoLoc, EST_None,
14951 /*ESpecRange=*/SourceRange(),
14952 /*Exceptions=*/nullptr,
14953 /*ExceptionRanges=*/nullptr,
14954 /*NumExceptions=*/0,
14955 /*NoexceptExpr=*/nullptr,
14956 /*ExceptionSpecTokens=*/nullptr,
14957 /*DeclsInPrototype=*/None, Loc,
14958 Loc, D),
14959 std::move(DS.getAttributes()), SourceLocation());
14960 D.SetIdentifier(&II, Loc);
14961
14962 // Insert this function into the enclosing block scope.
14963 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
14964 FD->setImplicit();
14965
14966 AddKnownFunctionAttributes(FD);
14967
14968 return FD;
14969}
14970
14971/// If this function is a C++ replaceable global allocation function
14972/// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
14973/// adds any function attributes that we know a priori based on the standard.
14974///
14975/// We need to check for duplicate attributes both here and where user-written
14976/// attributes are applied to declarations.
14977void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
14978 FunctionDecl *FD) {
14979 if (FD->isInvalidDecl())
14980 return;
14981
14982 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
14983 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
14984 return;
14985
14986 Optional<unsigned> AlignmentParam;
14987 bool IsNothrow = false;
14988 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
14989 return;
14990
14991 // C++2a [basic.stc.dynamic.allocation]p4:
14992 // An allocation function that has a non-throwing exception specification
14993 // indicates failure by returning a null pointer value. Any other allocation
14994 // function never returns a null pointer value and indicates failure only by
14995 // throwing an exception [...]
14996 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
14997 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
14998
14999 // C++2a [basic.stc.dynamic.allocation]p2:
15000 // An allocation function attempts to allocate the requested amount of
15001 // storage. [...] If the request succeeds, the value returned by a
15002 // replaceable allocation function is a [...] pointer value p0 different
15003 // from any previously returned value p1 [...]
15004 //
15005 // However, this particular information is being added in codegen,
15006 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
15007
15008 // C++2a [basic.stc.dynamic.allocation]p2:
15009 // An allocation function attempts to allocate the requested amount of
15010 // storage. If it is successful, it returns the address of the start of a
15011 // block of storage whose length in bytes is at least as large as the
15012 // requested size.
15013 if (!FD->hasAttr<AllocSizeAttr>()) {
15014 FD->addAttr(AllocSizeAttr::CreateImplicit(
15015 Context, /*ElemSizeParam=*/ParamIdx(1, FD),
15016 /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
15017 }
15018
15019 // C++2a [basic.stc.dynamic.allocation]p3:
15020 // For an allocation function [...], the pointer returned on a successful
15021 // call shall represent the address of storage that is aligned as follows:
15022 // (3.1) If the allocation function takes an argument of type
15023 // std​::​align_­val_­t, the storage will have the alignment
15024 // specified by the value of this argument.
15025 if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) {
15026 FD->addAttr(AllocAlignAttr::CreateImplicit(
15027 Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation()));
15028 }
15029
15030 // FIXME:
15031 // C++2a [basic.stc.dynamic.allocation]p3:
15032 // For an allocation function [...], the pointer returned on a successful
15033 // call shall represent the address of storage that is aligned as follows:
15034 // (3.2) Otherwise, if the allocation function is named operator new[],
15035 // the storage is aligned for any object that does not have
15036 // new-extended alignment ([basic.align]) and is no larger than the
15037 // requested size.
15038 // (3.3) Otherwise, the storage is aligned for any object that does not
15039 // have new-extended alignment and is of the requested size.
15040}
15041
15042/// Adds any function attributes that we know a priori based on
15043/// the declaration of this function.
15044///
15045/// These attributes can apply both to implicitly-declared builtins
15046/// (like __builtin___printf_chk) or to library-declared functions
15047/// like NSLog or printf.
15048///
15049/// We need to check for duplicate attributes both here and where user-written
15050/// attributes are applied to declarations.
15051void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
15052 if (FD->isInvalidDecl())
15053 return;
15054
15055 // If this is a built-in function, map its builtin attributes to
15056 // actual attributes.
15057 if (unsigned BuiltinID = FD->getBuiltinID()) {
15058 // Handle printf-formatting attributes.
15059 unsigned FormatIdx;
15060 bool HasVAListArg;
15061 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
15062 if (!FD->hasAttr<FormatAttr>()) {
15063 const char *fmt = "printf";
15064 unsigned int NumParams = FD->getNumParams();
15065 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
15066 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
15067 fmt = "NSString";
15068 FD->addAttr(FormatAttr::CreateImplicit(Context,
15069 &Context.Idents.get(fmt),
15070 FormatIdx+1,
15071 HasVAListArg ? 0 : FormatIdx+2,
15072 FD->getLocation()));
15073 }
15074 }
15075 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
15076 HasVAListArg)) {
15077 if (!FD->hasAttr<FormatAttr>())
15078 FD->addAttr(FormatAttr::CreateImplicit(Context,
15079 &Context.Idents.get("scanf"),
15080 FormatIdx+1,
15081 HasVAListArg ? 0 : FormatIdx+2,
15082 FD->getLocation()));
15083 }
15084
15085 // Handle automatically recognized callbacks.
15086 SmallVector<int, 4> Encoding;
15087 if (!FD->hasAttr<CallbackAttr>() &&
15088 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
15089 FD->addAttr(CallbackAttr::CreateImplicit(
15090 Context, Encoding.data(), Encoding.size(), FD->getLocation()));
15091
15092 // Mark const if we don't care about errno and that is the only thing
15093 // preventing the function from being const. This allows IRgen to use LLVM
15094 // intrinsics for such functions.
15095 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
15096 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
15097 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15098
15099 // We make "fma" on some platforms const because we know it does not set
15100 // errno in those environments even though it could set errno based on the
15101 // C standard.
15102 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
15103 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
15104 !FD->hasAttr<ConstAttr>()) {
15105 switch (BuiltinID) {
15106 case Builtin::BI__builtin_fma:
15107 case Builtin::BI__builtin_fmaf:
15108 case Builtin::BI__builtin_fmal:
15109 case Builtin::BIfma:
15110 case Builtin::BIfmaf:
15111 case Builtin::BIfmal:
15112 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15113 break;
15114 default:
15115 break;
15116 }
15117 }
15118
15119 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
15120 !FD->hasAttr<ReturnsTwiceAttr>())
15121 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
15122 FD->getLocation()));
15123 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
15124 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15125 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
15126 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
15127 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
15128 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15129 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
15130 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
15131 // Add the appropriate attribute, depending on the CUDA compilation mode
15132 // and which target the builtin belongs to. For example, during host
15133 // compilation, aux builtins are __device__, while the rest are __host__.
15134 if (getLangOpts().CUDAIsDevice !=
15135 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
15136 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
15137 else
15138 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
15139 }
15140 }
15141
15142 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
15143
15144 // If C++ exceptions are enabled but we are told extern "C" functions cannot
15145 // throw, add an implicit nothrow attribute to any extern "C" function we come
15146 // across.
15147 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
15148 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
15149 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
15150 if (!FPT || FPT->getExceptionSpecType() == EST_None)
15151 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15152 }
15153
15154 IdentifierInfo *Name = FD->getIdentifier();
15155 if (!Name)
15156 return;
15157 if ((!getLangOpts().CPlusPlus &&
15158 FD->getDeclContext()->isTranslationUnit()) ||
15159 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
15160 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
15161 LinkageSpecDecl::lang_c)) {
15162 // Okay: this could be a libc/libm/Objective-C function we know
15163 // about.
15164 } else
15165 return;
15166
15167 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
15168 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
15169 // target-specific builtins, perhaps?
15170 if (!FD->hasAttr<FormatAttr>())
15171 FD->addAttr(FormatAttr::CreateImplicit(Context,
15172 &Context.Idents.get("printf"), 2,
15173 Name->isStr("vasprintf") ? 0 : 3,
15174 FD->getLocation()));
15175 }
15176
15177 if (Name->isStr("__CFStringMakeConstantString")) {
15178 // We already have a __builtin___CFStringMakeConstantString,
15179 // but builds that use -fno-constant-cfstrings don't go through that.
15180 if (!FD->hasAttr<FormatArgAttr>())
15181 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
15182 FD->getLocation()));
15183 }
15184}
15185
15186TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
15187 TypeSourceInfo *TInfo) {
15188 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 15188, __extension__ __PRETTY_FUNCTION__))
;
15189 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 15189, __extension__ __PRETTY_FUNCTION__))
;
15190
15191 if (!TInfo) {
15192 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 15192, __extension__ __PRETTY_FUNCTION__))
;
15193 TInfo = Context.getTrivialTypeSourceInfo(T);
15194 }
15195
15196 // Scope manipulation handled by caller.
15197 TypedefDecl *NewTD =
15198 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
15199 D.getIdentifierLoc(), D.getIdentifier(), TInfo);
15200
15201 // Bail out immediately if we have an invalid declaration.
15202 if (D.isInvalidType()) {
15203 NewTD->setInvalidDecl();
15204 return NewTD;
15205 }
15206
15207 if (D.getDeclSpec().isModulePrivateSpecified()) {
15208 if (CurContext->isFunctionOrMethod())
15209 Diag(NewTD->getLocation(), diag::err_module_private_local)
15210 << 2 << NewTD
15211 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15212 << FixItHint::CreateRemoval(
15213 D.getDeclSpec().getModulePrivateSpecLoc());
15214 else
15215 NewTD->setModulePrivate();
15216 }
15217
15218 // C++ [dcl.typedef]p8:
15219 // If the typedef declaration defines an unnamed class (or
15220 // enum), the first typedef-name declared by the declaration
15221 // to be that class type (or enum type) is used to denote the
15222 // class type (or enum type) for linkage purposes only.
15223 // We need to check whether the type was declared in the declaration.
15224 switch (D.getDeclSpec().getTypeSpecType()) {
15225 case TST_enum:
15226 case TST_struct:
15227 case TST_interface:
15228 case TST_union:
15229 case TST_class: {
15230 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
15231 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
15232 break;
15233 }
15234
15235 default:
15236 break;
15237 }
15238
15239 return NewTD;
15240}
15241
15242/// Check that this is a valid underlying type for an enum declaration.
15243bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
15244 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
15245 QualType T = TI->getType();
15246
15247 if (T->isDependentType())
15248 return false;
15249
15250 // This doesn't use 'isIntegralType' despite the error message mentioning
15251 // integral type because isIntegralType would also allow enum types in C.
15252 if (const BuiltinType *BT = T->getAs<BuiltinType>())
15253 if (BT->isInteger())
15254 return false;
15255
15256 if (T->isExtIntType())
15257 return false;
15258
15259 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
15260}
15261
15262/// Check whether this is a valid redeclaration of a previous enumeration.
15263/// \return true if the redeclaration was invalid.
15264bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
15265 QualType EnumUnderlyingTy, bool IsFixed,
15266 const EnumDecl *Prev) {
15267 if (IsScoped != Prev->isScoped()) {
15268 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
15269 << Prev->isScoped();
15270 Diag(Prev->getLocation(), diag::note_previous_declaration);
15271 return true;
15272 }
15273
15274 if (IsFixed && Prev->isFixed()) {
15275 if (!EnumUnderlyingTy->isDependentType() &&
15276 !Prev->getIntegerType()->isDependentType() &&
15277 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
15278 Prev->getIntegerType())) {
15279 // TODO: Highlight the underlying type of the redeclaration.
15280 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
15281 << EnumUnderlyingTy << Prev->getIntegerType();
15282 Diag(Prev->getLocation(), diag::note_previous_declaration)
15283 << Prev->getIntegerTypeRange();
15284 return true;
15285 }
15286 } else if (IsFixed != Prev->isFixed()) {
15287 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
15288 << Prev->isFixed();
15289 Diag(Prev->getLocation(), diag::note_previous_declaration);
15290 return true;
15291 }
15292
15293 return false;
15294}
15295
15296/// Get diagnostic %select index for tag kind for
15297/// redeclaration diagnostic message.
15298/// WARNING: Indexes apply to particular diagnostics only!
15299///
15300/// \returns diagnostic %select index.
15301static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
15302 switch (Tag) {
15303 case TTK_Struct: return 0;
15304 case TTK_Interface: return 1;
15305 case TTK_Class: return 2;
15306 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!")::llvm::llvm_unreachable_internal("Invalid tag kind for redecl diagnostic!"
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 15306)
;
15307 }
15308}
15309
15310/// Determine if tag kind is a class-key compatible with
15311/// class for redeclaration (class, struct, or __interface).
15312///
15313/// \returns true iff the tag kind is compatible.
15314static bool isClassCompatTagKind(TagTypeKind Tag)
15315{
15316 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
15317}
15318
15319Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
15320 TagTypeKind TTK) {
15321 if (isa<TypedefDecl>(PrevDecl))
15322 return NTK_Typedef;
15323 else if (isa<TypeAliasDecl>(PrevDecl))
15324 return NTK_TypeAlias;
15325 else if (isa<ClassTemplateDecl>(PrevDecl))
15326 return NTK_Template;
15327 else if (isa<TypeAliasTemplateDecl>(PrevDecl))
15328 return NTK_TypeAliasTemplate;
15329 else if (isa<TemplateTemplateParmDecl>(PrevDecl))
15330 return NTK_TemplateTemplateArgument;
15331 switch (TTK) {
15332 case TTK_Struct:
15333 case TTK_Interface:
15334 case TTK_Class:
15335 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
15336 case TTK_Union:
15337 return NTK_NonUnion;
15338 case TTK_Enum:
15339 return NTK_NonEnum;
15340 }
15341 llvm_unreachable("invalid TTK")::llvm::llvm_unreachable_internal("invalid TTK", "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 15341)
;
15342}
15343
15344/// Determine whether a tag with a given kind is acceptable
15345/// as a redeclaration of the given tag declaration.
15346///
15347/// \returns true if the new tag kind is acceptable, false otherwise.
15348bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
15349 TagTypeKind NewTag, bool isDefinition,
15350 SourceLocation NewTagLoc,
15351 const IdentifierInfo *Name) {
15352 // C++ [dcl.type.elab]p3:
15353 // The class-key or enum keyword present in the
15354 // elaborated-type-specifier shall agree in kind with the
15355 // declaration to which the name in the elaborated-type-specifier
15356 // refers. This rule also applies to the form of
15357 // elaborated-type-specifier that declares a class-name or
15358 // friend class since it can be construed as referring to the
15359 // definition of the class. Thus, in any
15360 // elaborated-type-specifier, the enum keyword shall be used to
15361 // refer to an enumeration (7.2), the union class-key shall be
15362 // used to refer to a union (clause 9), and either the class or
15363 // struct class-key shall be used to refer to a class (clause 9)
15364 // declared using the class or struct class-key.
15365 TagTypeKind OldTag = Previous->getTagKind();
15366 if (OldTag != NewTag &&
15367 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
15368 return false;
15369
15370 // Tags are compatible, but we might still want to warn on mismatched tags.
15371 // Non-class tags can't be mismatched at this point.
15372 if (!isClassCompatTagKind(NewTag))
15373 return true;
15374
15375 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
15376 // by our warning analysis. We don't want to warn about mismatches with (eg)
15377 // declarations in system headers that are designed to be specialized, but if
15378 // a user asks us to warn, we should warn if their code contains mismatched
15379 // declarations.
15380 auto IsIgnoredLoc = [&](SourceLocation Loc) {
15381 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
15382 Loc);
15383 };
15384 if (IsIgnoredLoc(NewTagLoc))
15385 return true;
15386
15387 auto IsIgnored = [&](const TagDecl *Tag) {
15388 return IsIgnoredLoc(Tag->getLocation());
15389 };
15390 while (IsIgnored(Previous)) {
15391 Previous = Previous->getPreviousDecl();
15392 if (!Previous)
15393 return true;
15394 OldTag = Previous->getTagKind();
15395 }
15396
15397 bool isTemplate = false;
15398 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
15399 isTemplate = Record->getDescribedClassTemplate();
15400
15401 if (inTemplateInstantiation()) {
15402 if (OldTag != NewTag) {
15403 // In a template instantiation, do not offer fix-its for tag mismatches
15404 // since they usually mess up the template instead of fixing the problem.
15405 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15406 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15407 << getRedeclDiagFromTagKind(OldTag);
15408 // FIXME: Note previous location?
15409 }
15410 return true;
15411 }
15412
15413 if (isDefinition) {
15414 // On definitions, check all previous tags and issue a fix-it for each
15415 // one that doesn't match the current tag.
15416 if (Previous->getDefinition()) {
15417 // Don't suggest fix-its for redefinitions.
15418 return true;
15419 }
15420
15421 bool previousMismatch = false;
15422 for (const TagDecl *I : Previous->redecls()) {
15423 if (I->getTagKind() != NewTag) {
15424 // Ignore previous declarations for which the warning was disabled.
15425 if (IsIgnored(I))
15426 continue;
15427
15428 if (!previousMismatch) {
15429 previousMismatch = true;
15430 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
15431 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15432 << getRedeclDiagFromTagKind(I->getTagKind());
15433 }
15434 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
15435 << getRedeclDiagFromTagKind(NewTag)
15436 << FixItHint::CreateReplacement(I->getInnerLocStart(),
15437 TypeWithKeyword::getTagTypeKindName(NewTag));
15438 }
15439 }
15440 return true;
15441 }
15442
15443 // Identify the prevailing tag kind: this is the kind of the definition (if
15444 // there is a non-ignored definition), or otherwise the kind of the prior
15445 // (non-ignored) declaration.
15446 const TagDecl *PrevDef = Previous->getDefinition();
15447 if (PrevDef && IsIgnored(PrevDef))
15448 PrevDef = nullptr;
15449 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
15450 if (Redecl->getTagKind() != NewTag) {
15451 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15452 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15453 << getRedeclDiagFromTagKind(OldTag);
15454 Diag(Redecl->getLocation(), diag::note_previous_use);
15455
15456 // If there is a previous definition, suggest a fix-it.
15457 if (PrevDef) {
15458 Diag(NewTagLoc, diag::note_struct_class_suggestion)
15459 << getRedeclDiagFromTagKind(Redecl->getTagKind())
15460 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
15461 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
15462 }
15463 }
15464
15465 return true;
15466}
15467
15468/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
15469/// from an outer enclosing namespace or file scope inside a friend declaration.
15470/// This should provide the commented out code in the following snippet:
15471/// namespace N {
15472/// struct X;
15473/// namespace M {
15474/// struct Y { friend struct /*N::*/ X; };
15475/// }
15476/// }
15477static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
15478 SourceLocation NameLoc) {
15479 // While the decl is in a namespace, do repeated lookup of that name and see
15480 // if we get the same namespace back. If we do not, continue until
15481 // translation unit scope, at which point we have a fully qualified NNS.
15482 SmallVector<IdentifierInfo *, 4> Namespaces;
15483 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15484 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
15485 // This tag should be declared in a namespace, which can only be enclosed by
15486 // other namespaces. Bail if there's an anonymous namespace in the chain.
15487 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
15488 if (!Namespace || Namespace->isAnonymousNamespace())
15489 return FixItHint();
15490 IdentifierInfo *II = Namespace->getIdentifier();
15491 Namespaces.push_back(II);
15492 NamedDecl *Lookup = SemaRef.LookupSingleName(
15493 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
15494 if (Lookup == Namespace)
15495 break;
15496 }
15497
15498 // Once we have all the namespaces, reverse them to go outermost first, and
15499 // build an NNS.
15500 SmallString<64> Insertion;
15501 llvm::raw_svector_ostream OS(Insertion);
15502 if (DC->isTranslationUnit())
15503 OS << "::";
15504 std::reverse(Namespaces.begin(), Namespaces.end());
15505 for (auto *II : Namespaces)
15506 OS << II->getName() << "::";
15507 return FixItHint::CreateInsertion(NameLoc, Insertion);
15508}
15509
15510/// Determine whether a tag originally declared in context \p OldDC can
15511/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
15512/// found a declaration in \p OldDC as a previous decl, perhaps through a
15513/// using-declaration).
15514static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
15515 DeclContext *NewDC) {
15516 OldDC = OldDC->getRedeclContext();
15517 NewDC = NewDC->getRedeclContext();
15518
15519 if (OldDC->Equals(NewDC))
15520 return true;
15521
15522 // In MSVC mode, we allow a redeclaration if the contexts are related (either
15523 // encloses the other).
15524 if (S.getLangOpts().MSVCCompat &&
15525 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
15526 return true;
15527
15528 return false;
15529}
15530
15531/// This is invoked when we see 'struct foo' or 'struct {'. In the
15532/// former case, Name will be non-null. In the later case, Name will be null.
15533/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
15534/// reference/declaration/definition of a tag.
15535///
15536/// \param IsTypeSpecifier \c true if this is a type-specifier (or
15537/// trailing-type-specifier) other than one in an alias-declaration.
15538///
15539/// \param SkipBody If non-null, will be set to indicate if the caller should
15540/// skip the definition of this tag and treat it as if it were a declaration.
15541Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
15542 SourceLocation KWLoc, CXXScopeSpec &SS,
15543 IdentifierInfo *Name, SourceLocation NameLoc,
15544 const ParsedAttributesView &Attrs, AccessSpecifier AS,
15545 SourceLocation ModulePrivateLoc,
15546 MultiTemplateParamsArg TemplateParameterLists,
15547 bool &OwnedDecl, bool &IsDependent,
15548 SourceLocation ScopedEnumKWLoc,
15549 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
15550 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
15551 SkipBodyInfo *SkipBody) {
15552 // If this is not a definition, it must have a name.
15553 IdentifierInfo *OrigName = Name;
15554 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!\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 15555, __extension__ __PRETTY_FUNCTION__))
15555 "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!\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 15555, __extension__ __PRETTY_FUNCTION__))
;
15556 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"
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 15556, __extension__ __PRETTY_FUNCTION__))
;
15557
15558 OwnedDecl = false;
15559 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
15560 bool ScopedEnum = ScopedEnumKWLoc.isValid();
15561
15562 // FIXME: Check member specializations more carefully.
15563 bool isMemberSpecialization = false;
15564 bool Invalid = false;
15565
15566 // We only need to do this matching if we have template parameters
15567 // or a scope specifier, which also conveniently avoids this work
15568 // for non-C++ cases.
15569 if (TemplateParameterLists.size() > 0 ||
15570 (SS.isNotEmpty() && TUK != TUK_Reference)) {
15571 if (TemplateParameterList *TemplateParams =
15572 MatchTemplateParametersToScopeSpecifier(
15573 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
15574 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
15575 if (Kind == TTK_Enum) {
15576 Diag(KWLoc, diag::err_enum_template);
15577 return nullptr;
15578 }
15579
15580 if (TemplateParams->size() > 0) {
15581 // This is a declaration or definition of a class template (which may
15582 // be a member of another template).
15583
15584 if (Invalid)
15585 return nullptr;
15586
15587 OwnedDecl = false;
15588 DeclResult Result = CheckClassTemplate(
15589 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
15590 AS, ModulePrivateLoc,
15591 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
15592 TemplateParameterLists.data(), SkipBody);
15593 return Result.get();
15594 } else {
15595 // The "template<>" header is extraneous.
15596 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
15597 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
15598 isMemberSpecialization = true;
15599 }
15600 }
15601
15602 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
15603 CheckTemplateDeclScope(S, TemplateParameterLists.back()))
15604 return nullptr;
15605 }
15606
15607 // Figure out the underlying type if this a enum declaration. We need to do
15608 // this early, because it's needed to detect if this is an incompatible
15609 // redeclaration.
15610 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
15611 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
15612
15613 if (Kind == TTK_Enum) {
15614 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
15615 // No underlying type explicitly specified, or we failed to parse the
15616 // type, default to int.
15617 EnumUnderlying = Context.IntTy.getTypePtr();
15618 } else if (UnderlyingType.get()) {
15619 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
15620 // integral type; any cv-qualification is ignored.
15621 TypeSourceInfo *TI = nullptr;
15622 GetTypeFromParser(UnderlyingType.get(), &TI);
15623 EnumUnderlying = TI;
15624
15625 if (CheckEnumUnderlyingType(TI))
15626 // Recover by falling back to int.
15627 EnumUnderlying = Context.IntTy.getTypePtr();
15628
15629 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
15630 UPPC_FixedUnderlyingType))
15631 EnumUnderlying = Context.IntTy.getTypePtr();
15632
15633 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
15634 // For MSVC ABI compatibility, unfixed enums must use an underlying type
15635 // of 'int'. However, if this is an unfixed forward declaration, don't set
15636 // the underlying type unless the user enables -fms-compatibility. This
15637 // makes unfixed forward declared enums incomplete and is more conforming.
15638 if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
15639 EnumUnderlying = Context.IntTy.getTypePtr();
15640 }
15641 }
15642
15643 DeclContext *SearchDC = CurContext;
15644 DeclContext *DC = CurContext;
15645 bool isStdBadAlloc = false;
15646 bool isStdAlignValT = false;
15647
15648 RedeclarationKind Redecl = forRedeclarationInCurContext();
15649 if (TUK == TUK_Friend || TUK == TUK_Reference)
15650 Redecl = NotForRedeclaration;
15651
15652 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
15653 /// implemented asks for structural equivalence checking, the returned decl
15654 /// here is passed back to the parser, allowing the tag body to be parsed.
15655 auto createTagFromNewDecl = [&]() -> TagDecl * {
15656 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 15656, __extension__ __PRETTY_FUNCTION__))
;
15657 // If there is an identifier, use the location of the identifier as the
15658 // location of the decl, otherwise use the location of the struct/union
15659 // keyword.
15660 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15661 TagDecl *New = nullptr;
15662
15663 if (Kind == TTK_Enum) {
15664 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
15665 ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
15666 // If this is an undefined enum, bail.
15667 if (TUK != TUK_Definition && !Invalid)
15668 return nullptr;
15669 if (EnumUnderlying) {
15670 EnumDecl *ED = cast<EnumDecl>(New);
15671 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
15672 ED->setIntegerTypeSourceInfo(TI);
15673 else
15674 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
15675 ED->setPromotionType(ED->getIntegerType());
15676 }
15677 } else { // struct/union
15678 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15679 nullptr);
15680 }
15681
15682 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15683 // Add alignment attributes if necessary; these attributes are checked
15684 // when the ASTContext lays out the structure.
15685 //
15686 // It is important for implementing the correct semantics that this
15687 // happen here (in ActOnTag). The #pragma pack stack is
15688 // maintained as a result of parser callbacks which can occur at
15689 // many points during the parsing of a struct declaration (because
15690 // the #pragma tokens are effectively skipped over during the
15691 // parsing of the struct).
15692 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15693 AddAlignmentAttributesForRecord(RD);
15694 AddMsStructLayoutForRecord(RD);
15695 }
15696 }
15697 New->setLexicalDeclContext(CurContext);
15698 return New;
15699 };
15700
15701 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
15702 if (Name && SS.isNotEmpty()) {
15703 // We have a nested-name tag ('struct foo::bar').
15704
15705 // Check for invalid 'foo::'.
15706 if (SS.isInvalid()) {
15707 Name = nullptr;
15708 goto CreateNewDecl;
15709 }
15710
15711 // If this is a friend or a reference to a class in a dependent
15712 // context, don't try to make a decl for it.
15713 if (TUK == TUK_Friend || TUK == TUK_Reference) {
15714 DC = computeDeclContext(SS, false);
15715 if (!DC) {
15716 IsDependent = true;
15717 return nullptr;
15718 }
15719 } else {
15720 DC = computeDeclContext(SS, true);
15721 if (!DC) {
15722 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
15723 << SS.getRange();
15724 return nullptr;
15725 }
15726 }
15727
15728 if (RequireCompleteDeclContext(SS, DC))
15729 return nullptr;
15730
15731 SearchDC = DC;
15732 // Look-up name inside 'foo::'.
15733 LookupQualifiedName(Previous, DC);
15734
15735 if (Previous.isAmbiguous())
15736 return nullptr;
15737
15738 if (Previous.empty()) {
15739 // Name lookup did not find anything. However, if the
15740 // nested-name-specifier refers to the current instantiation,
15741 // and that current instantiation has any dependent base
15742 // classes, we might find something at instantiation time: treat
15743 // this as a dependent elaborated-type-specifier.
15744 // But this only makes any sense for reference-like lookups.
15745 if (Previous.wasNotFoundInCurrentInstantiation() &&
15746 (TUK == TUK_Reference || TUK == TUK_Friend)) {
15747 IsDependent = true;
15748 return nullptr;
15749 }
15750
15751 // A tag 'foo::bar' must already exist.
15752 Diag(NameLoc, diag::err_not_tag_in_scope)
15753 << Kind << Name << DC << SS.getRange();
15754 Name = nullptr;
15755 Invalid = true;
15756 goto CreateNewDecl;
15757 }
15758 } else if (Name) {
15759 // C++14 [class.mem]p14:
15760 // If T is the name of a class, then each of the following shall have a
15761 // name different from T:
15762 // -- every member of class T that is itself a type
15763 if (TUK != TUK_Reference && TUK != TUK_Friend &&
15764 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
15765 return nullptr;
15766
15767 // If this is a named struct, check to see if there was a previous forward
15768 // declaration or definition.
15769 // FIXME: We're looking into outer scopes here, even when we
15770 // shouldn't be. Doing so can result in ambiguities that we
15771 // shouldn't be diagnosing.
15772 LookupName(Previous, S);
15773
15774 // When declaring or defining a tag, ignore ambiguities introduced
15775 // by types using'ed into this scope.
15776 if (Previous.isAmbiguous() &&
15777 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
15778 LookupResult::Filter F = Previous.makeFilter();
15779 while (F.hasNext()) {
15780 NamedDecl *ND = F.next();
15781 if (!ND->getDeclContext()->getRedeclContext()->Equals(
15782 SearchDC->getRedeclContext()))
15783 F.erase();
15784 }
15785 F.done();
15786 }
15787
15788 // C++11 [namespace.memdef]p3:
15789 // If the name in a friend declaration is neither qualified nor
15790 // a template-id and the declaration is a function or an
15791 // elaborated-type-specifier, the lookup to determine whether
15792 // the entity has been previously declared shall not consider
15793 // any scopes outside the innermost enclosing namespace.
15794 //
15795 // MSVC doesn't implement the above rule for types, so a friend tag
15796 // declaration may be a redeclaration of a type declared in an enclosing
15797 // scope. They do implement this rule for friend functions.
15798 //
15799 // Does it matter that this should be by scope instead of by
15800 // semantic context?
15801 if (!Previous.empty() && TUK == TUK_Friend) {
15802 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
15803 LookupResult::Filter F = Previous.makeFilter();
15804 bool FriendSawTagOutsideEnclosingNamespace = false;
15805 while (F.hasNext()) {
15806 NamedDecl *ND = F.next();
15807 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15808 if (DC->isFileContext() &&
15809 !EnclosingNS->Encloses(ND->getDeclContext())) {
15810 if (getLangOpts().MSVCCompat)
15811 FriendSawTagOutsideEnclosingNamespace = true;
15812 else
15813 F.erase();
15814 }
15815 }
15816 F.done();
15817
15818 // Diagnose this MSVC extension in the easy case where lookup would have
15819 // unambiguously found something outside the enclosing namespace.
15820 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
15821 NamedDecl *ND = Previous.getFoundDecl();
15822 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
15823 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
15824 }
15825 }
15826
15827 // Note: there used to be some attempt at recovery here.
15828 if (Previous.isAmbiguous())
15829 return nullptr;
15830
15831 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
15832 // FIXME: This makes sure that we ignore the contexts associated
15833 // with C structs, unions, and enums when looking for a matching
15834 // tag declaration or definition. See the similar lookup tweak
15835 // in Sema::LookupName; is there a better way to deal with this?
15836 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
15837 SearchDC = SearchDC->getParent();
15838 }
15839 }
15840
15841 if (Previous.isSingleResult() &&
15842 Previous.getFoundDecl()->isTemplateParameter()) {
15843 // Maybe we will complain about the shadowed template parameter.
15844 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
15845 // Just pretend that we didn't see the previous declaration.
15846 Previous.clear();
15847 }
15848
15849 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
15850 DC->Equals(getStdNamespace())) {
15851 if (Name->isStr("bad_alloc")) {
15852 // This is a declaration of or a reference to "std::bad_alloc".
15853 isStdBadAlloc = true;
15854
15855 // If std::bad_alloc has been implicitly declared (but made invisible to
15856 // name lookup), fill in this implicit declaration as the previous
15857 // declaration, so that the declarations get chained appropriately.
15858 if (Previous.empty() && StdBadAlloc)
15859 Previous.addDecl(getStdBadAlloc());
15860 } else if (Name->isStr("align_val_t")) {
15861 isStdAlignValT = true;
15862 if (Previous.empty() && StdAlignValT)
15863 Previous.addDecl(getStdAlignValT());
15864 }
15865 }
15866
15867 // If we didn't find a previous declaration, and this is a reference
15868 // (or friend reference), move to the correct scope. In C++, we
15869 // also need to do a redeclaration lookup there, just in case
15870 // there's a shadow friend decl.
15871 if (Name && Previous.empty() &&
15872 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
15873 if (Invalid) goto CreateNewDecl;
15874 assert(SS.isEmpty())(static_cast <bool> (SS.isEmpty()) ? void (0) : __assert_fail
("SS.isEmpty()", "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 15874, __extension__ __PRETTY_FUNCTION__))
;
15875
15876 if (TUK == TUK_Reference || IsTemplateParamOrArg) {
15877 // C++ [basic.scope.pdecl]p5:
15878 // -- for an elaborated-type-specifier of the form
15879 //
15880 // class-key identifier
15881 //
15882 // if the elaborated-type-specifier is used in the
15883 // decl-specifier-seq or parameter-declaration-clause of a
15884 // function defined in namespace scope, the identifier is
15885 // declared as a class-name in the namespace that contains
15886 // the declaration; otherwise, except as a friend
15887 // declaration, the identifier is declared in the smallest
15888 // non-class, non-function-prototype scope that contains the
15889 // declaration.
15890 //
15891 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
15892 // C structs and unions.
15893 //
15894 // It is an error in C++ to declare (rather than define) an enum
15895 // type, including via an elaborated type specifier. We'll
15896 // diagnose that later; for now, declare the enum in the same
15897 // scope as we would have picked for any other tag type.
15898 //
15899 // GNU C also supports this behavior as part of its incomplete
15900 // enum types extension, while GNU C++ does not.
15901 //
15902 // Find the context where we'll be declaring the tag.
15903 // FIXME: We would like to maintain the current DeclContext as the
15904 // lexical context,
15905 SearchDC = getTagInjectionContext(SearchDC);
15906
15907 // Find the scope where we'll be declaring the tag.
15908 S = getTagInjectionScope(S, getLangOpts());
15909 } else {
15910 assert(TUK == TUK_Friend)(static_cast <bool> (TUK == TUK_Friend) ? void (0) : __assert_fail
("TUK == TUK_Friend", "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 15910, __extension__ __PRETTY_FUNCTION__))
;
15911 // C++ [namespace.memdef]p3:
15912 // If a friend declaration in a non-local class first declares a
15913 // class or function, the friend class or function is a member of
15914 // the innermost enclosing namespace.
15915 SearchDC = SearchDC->getEnclosingNamespaceContext();
15916 }
15917
15918 // In C++, we need to do a redeclaration lookup to properly
15919 // diagnose some problems.
15920 // FIXME: redeclaration lookup is also used (with and without C++) to find a
15921 // hidden declaration so that we don't get ambiguity errors when using a
15922 // type declared by an elaborated-type-specifier. In C that is not correct
15923 // and we should instead merge compatible types found by lookup.
15924 if (getLangOpts().CPlusPlus) {
15925 // FIXME: This can perform qualified lookups into function contexts,
15926 // which are meaningless.
15927 Previous.setRedeclarationKind(forRedeclarationInCurContext());
15928 LookupQualifiedName(Previous, SearchDC);
15929 } else {
15930 Previous.setRedeclarationKind(forRedeclarationInCurContext());
15931 LookupName(Previous, S);
15932 }
15933 }
15934
15935 // If we have a known previous declaration to use, then use it.
15936 if (Previous.empty() && SkipBody && SkipBody->Previous)
15937 Previous.addDecl(SkipBody->Previous);
15938
15939 if (!Previous.empty()) {
15940 NamedDecl *PrevDecl = Previous.getFoundDecl();
15941 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
15942
15943 // It's okay to have a tag decl in the same scope as a typedef
15944 // which hides a tag decl in the same scope. Finding this
15945 // insanity with a redeclaration lookup can only actually happen
15946 // in C++.
15947 //
15948 // This is also okay for elaborated-type-specifiers, which is
15949 // technically forbidden by the current standard but which is
15950 // okay according to the likely resolution of an open issue;
15951 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
15952 if (getLangOpts().CPlusPlus) {
15953 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15954 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
15955 TagDecl *Tag = TT->getDecl();
15956 if (Tag->getDeclName() == Name &&
15957 Tag->getDeclContext()->getRedeclContext()
15958 ->Equals(TD->getDeclContext()->getRedeclContext())) {
15959 PrevDecl = Tag;
15960 Previous.clear();
15961 Previous.addDecl(Tag);
15962 Previous.resolveKind();
15963 }
15964 }
15965 }
15966 }
15967
15968 // If this is a redeclaration of a using shadow declaration, it must
15969 // declare a tag in the same context. In MSVC mode, we allow a
15970 // redefinition if either context is within the other.
15971 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
15972 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
15973 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
15974 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
15975 !(OldTag && isAcceptableTagRedeclContext(
15976 *this, OldTag->getDeclContext(), SearchDC))) {
15977 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
15978 Diag(Shadow->getTargetDecl()->getLocation(),
15979 diag::note_using_decl_target);
15980 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
15981 << 0;
15982 // Recover by ignoring the old declaration.
15983 Previous.clear();
15984 goto CreateNewDecl;
15985 }
15986 }
15987
15988 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
15989 // If this is a use of a previous tag, or if the tag is already declared
15990 // in the same scope (so that the definition/declaration completes or
15991 // rementions the tag), reuse the decl.
15992 if (TUK == TUK_Reference || TUK == TUK_Friend ||
15993 isDeclInScope(DirectPrevDecl, SearchDC, S,
15994 SS.isNotEmpty() || isMemberSpecialization)) {
15995 // Make sure that this wasn't declared as an enum and now used as a
15996 // struct or something similar.
15997 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
15998 TUK == TUK_Definition, KWLoc,
15999 Name)) {
16000 bool SafeToContinue
16001 = (PrevTagDecl->getTagKind() != TTK_Enum &&
16002 Kind != TTK_Enum);
16003 if (SafeToContinue)
16004 Diag(KWLoc, diag::err_use_with_wrong_tag)
16005 << Name
16006 << FixItHint::CreateReplacement(SourceRange(KWLoc),
16007 PrevTagDecl->getKindName());
16008 else
16009 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
16010 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
16011
16012 if (SafeToContinue)
16013 Kind = PrevTagDecl->getTagKind();
16014 else {
16015 // Recover by making this an anonymous redefinition.
16016 Name = nullptr;
16017 Previous.clear();
16018 Invalid = true;
16019 }
16020 }
16021
16022 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
16023 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
16024 if (TUK == TUK_Reference || TUK == TUK_Friend)
16025 return PrevTagDecl;
16026
16027 QualType EnumUnderlyingTy;
16028 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16029 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
16030 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
16031 EnumUnderlyingTy = QualType(T, 0);
16032
16033 // All conflicts with previous declarations are recovered by
16034 // returning the previous declaration, unless this is a definition,
16035 // in which case we want the caller to bail out.
16036 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
16037 ScopedEnum, EnumUnderlyingTy,
16038 IsFixed, PrevEnum))
16039 return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
16040 }
16041
16042 // C++11 [class.mem]p1:
16043 // A member shall not be declared twice in the member-specification,
16044 // except that a nested class or member class template can be declared
16045 // and then later defined.
16046 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
16047 S->isDeclScope(PrevDecl)) {
16048 Diag(NameLoc, diag::ext_member_redeclared);
16049 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
16050 }
16051
16052 if (!Invalid) {
16053 // If this is a use, just return the declaration we found, unless
16054 // we have attributes.
16055 if (TUK == TUK_Reference || TUK == TUK_Friend) {
16056 if (!Attrs.empty()) {
16057 // FIXME: Diagnose these attributes. For now, we create a new
16058 // declaration to hold them.
16059 } else if (TUK == TUK_Reference &&
16060 (PrevTagDecl->getFriendObjectKind() ==
16061 Decl::FOK_Undeclared ||
16062 PrevDecl->getOwningModule() != getCurrentModule()) &&
16063 SS.isEmpty()) {
16064 // This declaration is a reference to an existing entity, but
16065 // has different visibility from that entity: it either makes
16066 // a friend visible or it makes a type visible in a new module.
16067 // In either case, create a new declaration. We only do this if
16068 // the declaration would have meant the same thing if no prior
16069 // declaration were found, that is, if it was found in the same
16070 // scope where we would have injected a declaration.
16071 if (!getTagInjectionContext(CurContext)->getRedeclContext()
16072 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
16073 return PrevTagDecl;
16074 // This is in the injected scope, create a new declaration in
16075 // that scope.
16076 S = getTagInjectionScope(S, getLangOpts());
16077 } else {
16078 return PrevTagDecl;
16079 }
16080 }
16081
16082 // Diagnose attempts to redefine a tag.
16083 if (TUK == TUK_Definition) {
16084 if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
16085 // If we're defining a specialization and the previous definition
16086 // is from an implicit instantiation, don't emit an error
16087 // here; we'll catch this in the general case below.
16088 bool IsExplicitSpecializationAfterInstantiation = false;
16089 if (isMemberSpecialization) {
16090 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
16091 IsExplicitSpecializationAfterInstantiation =
16092 RD->getTemplateSpecializationKind() !=
16093 TSK_ExplicitSpecialization;
16094 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
16095 IsExplicitSpecializationAfterInstantiation =
16096 ED->getTemplateSpecializationKind() !=
16097 TSK_ExplicitSpecialization;
16098 }
16099
16100 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
16101 // not keep more that one definition around (merge them). However,
16102 // ensure the decl passes the structural compatibility check in
16103 // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
16104 NamedDecl *Hidden = nullptr;
16105 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
16106 // There is a definition of this tag, but it is not visible. We
16107 // explicitly make use of C++'s one definition rule here, and
16108 // assume that this definition is identical to the hidden one
16109 // we already have. Make the existing definition visible and
16110 // use it in place of this one.
16111 if (!getLangOpts().CPlusPlus) {
16112 // Postpone making the old definition visible until after we
16113 // complete parsing the new one and do the structural
16114 // comparison.
16115 SkipBody->CheckSameAsPrevious = true;
16116 SkipBody->New = createTagFromNewDecl();
16117 SkipBody->Previous = Def;
16118 return Def;
16119 } else {
16120 SkipBody->ShouldSkip = true;
16121 SkipBody->Previous = Def;
16122 makeMergedDefinitionVisible(Hidden);
16123 // Carry on and handle it like a normal definition. We'll
16124 // skip starting the definitiion later.
16125 }
16126 } else if (!IsExplicitSpecializationAfterInstantiation) {
16127 // A redeclaration in function prototype scope in C isn't
16128 // visible elsewhere, so merely issue a warning.
16129 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
16130 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
16131 else
16132 Diag(NameLoc, diag::err_redefinition) << Name;
16133 notePreviousDefinition(Def,
16134 NameLoc.isValid() ? NameLoc : KWLoc);
16135 // If this is a redefinition, recover by making this
16136 // struct be anonymous, which will make any later
16137 // references get the previous definition.
16138 Name = nullptr;
16139 Previous.clear();
16140 Invalid = true;
16141 }
16142 } else {
16143 // If the type is currently being defined, complain
16144 // about a nested redefinition.
16145 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
16146 if (TD->isBeingDefined()) {
16147 Diag(NameLoc, diag::err_nested_redefinition) << Name;
16148 Diag(PrevTagDecl->getLocation(),
16149 diag::note_previous_definition);
16150 Name = nullptr;
16151 Previous.clear();
16152 Invalid = true;
16153 }
16154 }
16155
16156 // Okay, this is definition of a previously declared or referenced
16157 // tag. We're going to create a new Decl for it.
16158 }
16159
16160 // Okay, we're going to make a redeclaration. If this is some kind
16161 // of reference, make sure we build the redeclaration in the same DC
16162 // as the original, and ignore the current access specifier.
16163 if (TUK == TUK_Friend || TUK == TUK_Reference) {
16164 SearchDC = PrevTagDecl->getDeclContext();
16165 AS = AS_none;
16166 }
16167 }
16168 // If we get here we have (another) forward declaration or we
16169 // have a definition. Just create a new decl.
16170
16171 } else {
16172 // If we get here, this is a definition of a new tag type in a nested
16173 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
16174 // new decl/type. We set PrevDecl to NULL so that the entities
16175 // have distinct types.
16176 Previous.clear();
16177 }
16178 // If we get here, we're going to create a new Decl. If PrevDecl
16179 // is non-NULL, it's a definition of the tag declared by
16180 // PrevDecl. If it's NULL, we have a new definition.
16181
16182 // Otherwise, PrevDecl is not a tag, but was found with tag
16183 // lookup. This is only actually possible in C++, where a few
16184 // things like templates still live in the tag namespace.
16185 } else {
16186 // Use a better diagnostic if an elaborated-type-specifier
16187 // found the wrong kind of type on the first
16188 // (non-redeclaration) lookup.
16189 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
16190 !Previous.isForRedeclaration()) {
16191 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16192 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
16193 << Kind;
16194 Diag(PrevDecl->getLocation(), diag::note_declared_at);
16195 Invalid = true;
16196
16197 // Otherwise, only diagnose if the declaration is in scope.
16198 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
16199 SS.isNotEmpty() || isMemberSpecialization)) {
16200 // do nothing
16201
16202 // Diagnose implicit declarations introduced by elaborated types.
16203 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
16204 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16205 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
16206 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16207 Invalid = true;
16208
16209 // Otherwise it's a declaration. Call out a particularly common
16210 // case here.
16211 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16212 unsigned Kind = 0;
16213 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
16214 Diag(NameLoc, diag::err_tag_definition_of_typedef)
16215 << Name << Kind << TND->getUnderlyingType();
16216 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16217 Invalid = true;
16218
16219 // Otherwise, diagnose.
16220 } else {
16221 // The tag name clashes with something else in the target scope,
16222 // issue an error and recover by making this tag be anonymous.
16223 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
16224 notePreviousDefinition(PrevDecl, NameLoc);
16225 Name = nullptr;
16226 Invalid = true;
16227 }
16228
16229 // The existing declaration isn't relevant to us; we're in a
16230 // new scope, so clear out the previous declaration.
16231 Previous.clear();
16232 }
16233 }
16234
16235CreateNewDecl:
16236
16237 TagDecl *PrevDecl = nullptr;
16238 if (Previous.isSingleResult())
16239 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
16240
16241 // If there is an identifier, use the location of the identifier as the
16242 // location of the decl, otherwise use the location of the struct/union
16243 // keyword.
16244 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16245
16246 // Otherwise, create a new declaration. If there is a previous
16247 // declaration of the same entity, the two will be linked via
16248 // PrevDecl.
16249 TagDecl *New;
16250
16251 if (Kind == TTK_Enum) {
16252 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16253 // enum X { A, B, C } D; D should chain to X.
16254 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
16255 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
16256 ScopedEnumUsesClassTag, IsFixed);
16257
16258 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
16259 StdAlignValT = cast<EnumDecl>(New);
16260
16261 // If this is an undefined enum, warn.
16262 if (TUK != TUK_Definition && !Invalid) {
16263 TagDecl *Def;
16264 if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
16265 // C++0x: 7.2p2: opaque-enum-declaration.
16266 // Conflicts are diagnosed above. Do nothing.
16267 }
16268 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
16269 Diag(Loc, diag::ext_forward_ref_enum_def)
16270 << New;
16271 Diag(Def->getLocation(), diag::note_previous_definition);
16272 } else {
16273 unsigned DiagID = diag::ext_forward_ref_enum;
16274 if (getLangOpts().MSVCCompat)
16275 DiagID = diag::ext_ms_forward_ref_enum;
16276 else if (getLangOpts().CPlusPlus)
16277 DiagID = diag::err_forward_ref_enum;
16278 Diag(Loc, DiagID);
16279 }
16280 }
16281
16282 if (EnumUnderlying) {
16283 EnumDecl *ED = cast<EnumDecl>(New);
16284 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16285 ED->setIntegerTypeSourceInfo(TI);
16286 else
16287 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
16288 ED->setPromotionType(ED->getIntegerType());
16289 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 16289, __extension__ __PRETTY_FUNCTION__))
;
16290 }
16291 } else {
16292 // struct/union/class
16293
16294 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16295 // struct X { int A; } D; D should chain to X.
16296 if (getLangOpts().CPlusPlus) {
16297 // FIXME: Look for a way to use RecordDecl for simple structs.
16298 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16299 cast_or_null<CXXRecordDecl>(PrevDecl));
16300
16301 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
16302 StdBadAlloc = cast<CXXRecordDecl>(New);
16303 } else
16304 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16305 cast_or_null<RecordDecl>(PrevDecl));
16306 }
16307
16308 // C++11 [dcl.type]p3:
16309 // A type-specifier-seq shall not define a class or enumeration [...].
16310 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
16311 TUK == TUK_Definition) {
16312 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
16313 << Context.getTagDeclType(New);
16314 Invalid = true;
16315 }
16316
16317 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
16318 DC->getDeclKind() == Decl::Enum) {
16319 Diag(New->getLocation(), diag::err_type_defined_in_enum)
16320 << Context.getTagDeclType(New);
16321 Invalid = true;
16322 }
16323
16324 // Maybe add qualifier info.
16325 if (SS.isNotEmpty()) {
16326 if (SS.isSet()) {
16327 // If this is either a declaration or a definition, check the
16328 // nested-name-specifier against the current context.
16329 if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
16330 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
16331 isMemberSpecialization))
16332 Invalid = true;
16333
16334 New->setQualifierInfo(SS.getWithLocInContext(Context));
16335 if (TemplateParameterLists.size() > 0) {
16336 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
16337 }
16338 }
16339 else
16340 Invalid = true;
16341 }
16342
16343 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16344 // Add alignment attributes if necessary; these attributes are checked when
16345 // the ASTContext lays out the structure.
16346 //
16347 // It is important for implementing the correct semantics that this
16348 // happen here (in ActOnTag). The #pragma pack stack is
16349 // maintained as a result of parser callbacks which can occur at
16350 // many points during the parsing of a struct declaration (because
16351 // the #pragma tokens are effectively skipped over during the
16352 // parsing of the struct).
16353 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16354 AddAlignmentAttributesForRecord(RD);
16355 AddMsStructLayoutForRecord(RD);
16356 }
16357 }
16358
16359 if (ModulePrivateLoc.isValid()) {
16360 if (isMemberSpecialization)
16361 Diag(New->getLocation(), diag::err_module_private_specialization)
16362 << 2
16363 << FixItHint::CreateRemoval(ModulePrivateLoc);
16364 // __module_private__ does not apply to local classes. However, we only
16365 // diagnose this as an error when the declaration specifiers are
16366 // freestanding. Here, we just ignore the __module_private__.
16367 else if (!SearchDC->isFunctionOrMethod())
16368 New->setModulePrivate();
16369 }
16370
16371 // If this is a specialization of a member class (of a class template),
16372 // check the specialization.
16373 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
16374 Invalid = true;
16375
16376 // If we're declaring or defining a tag in function prototype scope in C,
16377 // note that this type can only be used within the function and add it to
16378 // the list of decls to inject into the function definition scope.
16379 if ((Name || Kind == TTK_Enum) &&
16380 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
16381 if (getLangOpts().CPlusPlus) {
16382 // C++ [dcl.fct]p6:
16383 // Types shall not be defined in return or parameter types.
16384 if (TUK == TUK_Definition && !IsTypeSpecifier) {
16385 Diag(Loc, diag::err_type_defined_in_param_type)
16386 << Name;
16387 Invalid = true;
16388 }
16389 } else if (!PrevDecl) {
16390 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
16391 }
16392 }
16393
16394 if (Invalid)
16395 New->setInvalidDecl();
16396
16397 // Set the lexical context. If the tag has a C++ scope specifier, the
16398 // lexical context will be different from the semantic context.
16399 New->setLexicalDeclContext(CurContext);
16400
16401 // Mark this as a friend decl if applicable.
16402 // In Microsoft mode, a friend declaration also acts as a forward
16403 // declaration so we always pass true to setObjectOfFriendDecl to make
16404 // the tag name visible.
16405 if (TUK == TUK_Friend)
16406 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
16407
16408 // Set the access specifier.
16409 if (!Invalid && SearchDC->isRecord())
16410 SetMemberAccessSpecifier(New, PrevDecl, AS);
16411
16412 if (PrevDecl)
16413 CheckRedeclarationModuleOwnership(New, PrevDecl);
16414
16415 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
16416 New->startDefinition();
16417
16418 ProcessDeclAttributeList(S, New, Attrs);
16419 AddPragmaAttributes(S, New);
16420
16421 // If this has an identifier, add it to the scope stack.
16422 if (TUK == TUK_Friend) {
16423 // We might be replacing an existing declaration in the lookup tables;
16424 // if so, borrow its access specifier.
16425 if (PrevDecl)
16426 New->setAccess(PrevDecl->getAccess());
16427
16428 DeclContext *DC = New->getDeclContext()->getRedeclContext();
16429 DC->makeDeclVisibleInContext(New);
16430 if (Name) // can be null along some error paths
16431 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16432 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
16433 } else if (Name) {
16434 S = getNonFieldDeclScope(S);
16435 PushOnScopeChains(New, S, true);
16436 } else {
16437 CurContext->addDecl(New);
16438 }
16439
16440 // If this is the C FILE type, notify the AST context.
16441 if (IdentifierInfo *II = New->getIdentifier())
16442 if (!New->isInvalidDecl() &&
16443 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
16444 II->isStr("FILE"))
16445 Context.setFILEDecl(New);
16446
16447 if (PrevDecl)
16448 mergeDeclAttributes(New, PrevDecl);
16449
16450 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
16451 inferGslOwnerPointerAttribute(CXXRD);
16452
16453 // If there's a #pragma GCC visibility in scope, set the visibility of this
16454 // record.
16455 AddPushedVisibilityAttribute(New);
16456
16457 if (isMemberSpecialization && !New->isInvalidDecl())
16458 CompleteMemberSpecialization(New, Previous);
16459
16460 OwnedDecl = true;
16461 // In C++, don't return an invalid declaration. We can't recover well from
16462 // the cases where we make the type anonymous.
16463 if (Invalid && getLangOpts().CPlusPlus) {
16464 if (New->isBeingDefined())
16465 if (auto RD = dyn_cast<RecordDecl>(New))
16466 RD->completeDefinition();
16467 return nullptr;
16468 } else if (SkipBody && SkipBody->ShouldSkip) {
16469 return SkipBody->Previous;
16470 } else {
16471 return New;
16472 }
16473}
16474
16475void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
16476 AdjustDeclIfTemplate(TagD);
16477 TagDecl *Tag = cast<TagDecl>(TagD);
16478
16479 // Enter the tag context.
16480 PushDeclContext(S, Tag);
16481
16482 ActOnDocumentableDecl(TagD);
16483
16484 // If there's a #pragma GCC visibility in scope, set the visibility of this
16485 // record.
16486 AddPushedVisibilityAttribute(Tag);
16487}
16488
16489bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
16490 SkipBodyInfo &SkipBody) {
16491 if (!hasStructuralCompatLayout(Prev, SkipBody.New))
16492 return false;
16493
16494 // Make the previous decl visible.
16495 makeMergedDefinitionVisible(SkipBody.Previous);
16496 return true;
16497}
16498
16499Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
16500 assert(isa<ObjCContainerDecl>(IDecl) &&(static_cast <bool> (isa<ObjCContainerDecl>(IDecl
) && "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"
) ? void (0) : __assert_fail ("isa<ObjCContainerDecl>(IDecl) && \"ActOnObjCContainerStartDefinition - Not ObjCContainerDecl\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 16501, __extension__ __PRETTY_FUNCTION__))
16501 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl")(static_cast <bool> (isa<ObjCContainerDecl>(IDecl
) && "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"
) ? void (0) : __assert_fail ("isa<ObjCContainerDecl>(IDecl) && \"ActOnObjCContainerStartDefinition - Not ObjCContainerDecl\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 16501, __extension__ __PRETTY_FUNCTION__))
;
16502 DeclContext *OCD = cast<DeclContext>(IDecl);
16503 assert(OCD->getLexicalParent() == CurContext &&(static_cast <bool> (OCD->getLexicalParent() == CurContext
&& "The next DeclContext should be lexically contained in the current one."
) ? void (0) : __assert_fail ("OCD->getLexicalParent() == CurContext && \"The next DeclContext should be lexically contained in the current one.\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 16504, __extension__ __PRETTY_FUNCTION__))
16504 "The next DeclContext should be lexically contained in the current one.")(static_cast <bool> (OCD->getLexicalParent() == CurContext
&& "The next DeclContext should be lexically contained in the current one."
) ? void (0) : __assert_fail ("OCD->getLexicalParent() == CurContext && \"The next DeclContext should be lexically contained in the current one.\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 16504, __extension__ __PRETTY_FUNCTION__))
;
16505 CurContext = OCD;
16506 return IDecl;
16507}
16508
16509void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
16510 SourceLocation FinalLoc,
16511 bool IsFinalSpelledSealed,
16512 bool IsAbstract,
16513 SourceLocation LBraceLoc) {
16514 AdjustDeclIfTemplate(TagD);
16515 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
16516
16517 FieldCollector->StartClass();
16518
16519 if (!Record->getIdentifier())
16520 return;
16521
16522 if (IsAbstract)
16523 Record->markAbstract();
16524
16525 if (FinalLoc.isValid()) {
16526 Record->addAttr(FinalAttr::Create(
16527 Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
16528 static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
16529 }
16530 // C++ [class]p2:
16531 // [...] The class-name is also inserted into the scope of the
16532 // class itself; this is known as the injected-class-name. For
16533 // purposes of access checking, the injected-class-name is treated
16534 // as if it were a public member name.
16535 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
16536 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
16537 Record->getLocation(), Record->getIdentifier(),
16538 /*PrevDecl=*/nullptr,
16539 /*DelayTypeCreation=*/true);
16540 Context.getTypeDeclType(InjectedClassName, Record);
16541 InjectedClassName->setImplicit();
16542 InjectedClassName->setAccess(AS_public);
16543 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
16544 InjectedClassName->setDescribedClassTemplate(Template);
16545 PushOnScopeChains(InjectedClassName, S);
16546 assert(InjectedClassName->isInjectedClassName() &&(static_cast <bool> (InjectedClassName->isInjectedClassName
() && "Broken injected-class-name") ? void (0) : __assert_fail
("InjectedClassName->isInjectedClassName() && \"Broken injected-class-name\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 16547, __extension__ __PRETTY_FUNCTION__))
16547 "Broken injected-class-name")(static_cast <bool> (InjectedClassName->isInjectedClassName
() && "Broken injected-class-name") ? void (0) : __assert_fail
("InjectedClassName->isInjectedClassName() && \"Broken injected-class-name\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 16547, __extension__ __PRETTY_FUNCTION__))
;
16548}
16549
16550void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
16551 SourceRange BraceRange) {
16552 AdjustDeclIfTemplate(TagD);
16553 TagDecl *Tag = cast<TagDecl>(TagD);
16554 Tag->setBraceRange(BraceRange);
16555
16556 // Make sure we "complete" the definition even it is invalid.
16557 if (Tag->isBeingDefined()) {
16558 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 16558, __extension__ __PRETTY_FUNCTION__))
;
16559 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16560 RD->completeDefinition();
16561 }
16562
16563 if (isa<CXXRecordDecl>(Tag)) {
16564 FieldCollector->FinishClass();
16565 }
16566
16567 // Exit this scope of this tag's definition.
16568 PopDeclContext();
16569
16570 if (getCurLexicalContext()->isObjCContainer() &&
16571 Tag->getDeclContext()->isFileContext())
16572 Tag->setTopLevelDeclInObjCContainer();
16573
16574 // Notify the consumer that we've defined a tag.
16575 if (!Tag->isInvalidDecl())
16576 Consumer.HandleTagDeclDefinition(Tag);
16577}
16578
16579void Sema::ActOnObjCContainerFinishDefinition() {
16580 // Exit this scope of this interface definition.
16581 PopDeclContext();
16582}
16583
16584void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
16585 assert(DC == CurContext && "Mismatch of container contexts")(static_cast <bool> (DC == CurContext && "Mismatch of container contexts"
) ? void (0) : __assert_fail ("DC == CurContext && \"Mismatch of container contexts\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 16585, __extension__ __PRETTY_FUNCTION__))
;
16586 OriginalLexicalContext = DC;
16587 ActOnObjCContainerFinishDefinition();
16588}
16589
16590void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
16591 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
16592 OriginalLexicalContext = nullptr;
16593}
16594
16595void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
16596 AdjustDeclIfTemplate(TagD);
16597 TagDecl *Tag = cast<TagDecl>(TagD);
16598 Tag->setInvalidDecl();
16599
16600 // Make sure we "complete" the definition even it is invalid.
16601 if (Tag->isBeingDefined()) {
16602 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16603 RD->completeDefinition();
16604 }
16605
16606 // We're undoing ActOnTagStartDefinition here, not
16607 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
16608 // the FieldCollector.
16609
16610 PopDeclContext();
16611}
16612
16613// Note that FieldName may be null for anonymous bitfields.
16614ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
16615 IdentifierInfo *FieldName,
16616 QualType FieldTy, bool IsMsStruct,
16617 Expr *BitWidth, bool *ZeroWidth) {
16618 assert(BitWidth)(static_cast <bool> (BitWidth) ? void (0) : __assert_fail
("BitWidth", "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 16618, __extension__ __PRETTY_FUNCTION__))
;
16619 if (BitWidth->containsErrors())
16620 return ExprError();
16621
16622 // Default to true; that shouldn't confuse checks for emptiness
16623 if (ZeroWidth)
16624 *ZeroWidth = true;
16625
16626 // C99 6.7.2.1p4 - verify the field type.
16627 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
16628 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
16629 // Handle incomplete and sizeless types with a specific error.
16630 if (RequireCompleteSizedType(FieldLoc, FieldTy,
16631 diag::err_field_incomplete_or_sizeless))
16632 return ExprError();
16633 if (FieldName)
16634 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
16635 << FieldName << FieldTy << BitWidth->getSourceRange();
16636 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
16637 << FieldTy << BitWidth->getSourceRange();
16638 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
16639 UPPC_BitFieldWidth))
16640 return ExprError();
16641
16642 // If the bit-width is type- or value-dependent, don't try to check
16643 // it now.
16644 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
16645 return BitWidth;
16646
16647 llvm::APSInt Value;
16648 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
16649 if (ICE.isInvalid())
16650 return ICE;
16651 BitWidth = ICE.get();
16652
16653 if (Value != 0 && ZeroWidth)
16654 *ZeroWidth = false;
16655
16656 // Zero-width bitfield is ok for anonymous field.
16657 if (Value == 0 && FieldName)
16658 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
16659
16660 if (Value.isSigned() && Value.isNegative()) {
16661 if (FieldName)
16662 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
16663 << FieldName << toString(Value, 10);
16664 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
16665 << toString(Value, 10);
16666 }
16667
16668 // The size of the bit-field must not exceed our maximum permitted object
16669 // size.
16670 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
16671 return Diag(FieldLoc, diag::err_bitfield_too_wide)
16672 << !FieldName << FieldName << toString(Value, 10);
16673 }
16674
16675 if (!FieldTy->isDependentType()) {
16676 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
16677 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
16678 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
16679
16680 // Over-wide bitfields are an error in C or when using the MSVC bitfield
16681 // ABI.
16682 bool CStdConstraintViolation =
16683 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
16684 bool MSBitfieldViolation =
16685 Value.ugt(TypeStorageSize) &&
16686 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
16687 if (CStdConstraintViolation || MSBitfieldViolation) {
16688 unsigned DiagWidth =
16689 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
16690 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
16691 << (bool)FieldName << FieldName << toString(Value, 10)
16692 << !CStdConstraintViolation << DiagWidth;
16693 }
16694
16695 // Warn on types where the user might conceivably expect to get all
16696 // specified bits as value bits: that's all integral types other than
16697 // 'bool'.
16698 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
16699 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
16700 << FieldName << toString(Value, 10)
16701 << (unsigned)TypeWidth;
16702 }
16703 }
16704
16705 return BitWidth;
16706}
16707
16708/// ActOnField - Each field of a C struct/union is passed into this in order
16709/// to create a FieldDecl object for it.
16710Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
16711 Declarator &D, Expr *BitfieldWidth) {
16712 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
16713 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
16714 /*InitStyle=*/ICIS_NoInit, AS_public);
16715 return Res;
16716}
16717
16718/// HandleField - Analyze a field of a C struct or a C++ data member.
16719///
16720FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
16721 SourceLocation DeclStart,
16722 Declarator &D, Expr *BitWidth,
16723 InClassInitStyle InitStyle,
16724 AccessSpecifier AS) {
16725 if (D.isDecompositionDeclarator()) {
16726 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
16727 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
16728 << Decomp.getSourceRange();
16729 return nullptr;
16730 }
16731
16732 IdentifierInfo *II = D.getIdentifier();
16733 SourceLocation Loc = DeclStart;
16734 if (II) Loc = D.getIdentifierLoc();
16735
16736 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16737 QualType T = TInfo->getType();
16738 if (getLangOpts().CPlusPlus) {
16739 CheckExtraCXXDefaultArguments(D);
16740
16741 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16742 UPPC_DataMemberType)) {
16743 D.setInvalidType();
16744 T = Context.IntTy;
16745 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
16746 }
16747 }
16748
16749 DiagnoseFunctionSpecifiers(D.getDeclSpec());
16750
16751 if (D.getDeclSpec().isInlineSpecified())
16752 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
16753 << getLangOpts().CPlusPlus17;
16754 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
16755 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
16756 diag::err_invalid_thread)
16757 << DeclSpec::getSpecifierName(TSCS);
16758
16759 // Check to see if this name was declared as a member previously
16760 NamedDecl *PrevDecl = nullptr;
16761 LookupResult Previous(*this, II, Loc, LookupMemberName,
16762 ForVisibleRedeclaration);
16763 LookupName(Previous, S);
16764 switch (Previous.getResultKind()) {
16765 case LookupResult::Found:
16766 case LookupResult::FoundUnresolvedValue:
16767 PrevDecl = Previous.getAsSingle<NamedDecl>();
16768 break;
16769
16770 case LookupResult::FoundOverloaded:
16771 PrevDecl = Previous.getRepresentativeDecl();
16772 break;
16773
16774 case LookupResult::NotFound:
16775 case LookupResult::NotFoundInCurrentInstantiation:
16776 case LookupResult::Ambiguous:
16777 break;
16778 }
16779 Previous.suppressDiagnostics();
16780
16781 if (PrevDecl && PrevDecl->isTemplateParameter()) {
16782 // Maybe we will complain about the shadowed template parameter.
16783 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16784 // Just pretend that we didn't see the previous declaration.
16785 PrevDecl = nullptr;
16786 }
16787
16788 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
16789 PrevDecl = nullptr;
16790
16791 bool Mutable
16792 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
16793 SourceLocation TSSL = D.getBeginLoc();
16794 FieldDecl *NewFD
16795 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
16796 TSSL, AS, PrevDecl, &D);
16797
16798 if (NewFD->isInvalidDecl())
16799 Record->setInvalidDecl();
16800
16801 if (D.getDeclSpec().isModulePrivateSpecified())
16802 NewFD->setModulePrivate();
16803
16804 if (NewFD->isInvalidDecl() && PrevDecl) {
16805 // Don't introduce NewFD into scope; there's already something
16806 // with the same name in the same scope.
16807 } else if (II) {
16808 PushOnScopeChains(NewFD, S);
16809 } else
16810 Record->addDecl(NewFD);
16811
16812 return NewFD;
16813}
16814
16815/// Build a new FieldDecl and check its well-formedness.
16816///
16817/// This routine builds a new FieldDecl given the fields name, type,
16818/// record, etc. \p PrevDecl should refer to any previous declaration
16819/// with the same name and in the same scope as the field to be
16820/// created.
16821///
16822/// \returns a new FieldDecl.
16823///
16824/// \todo The Declarator argument is a hack. It will be removed once
16825FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
16826 TypeSourceInfo *TInfo,
16827 RecordDecl *Record, SourceLocation Loc,
16828 bool Mutable, Expr *BitWidth,
16829 InClassInitStyle InitStyle,
16830 SourceLocation TSSL,
16831 AccessSpecifier AS, NamedDecl *PrevDecl,
16832 Declarator *D) {
16833 IdentifierInfo *II = Name.getAsIdentifierInfo();
16834 bool InvalidDecl = false;
16835 if (D) InvalidDecl = D->isInvalidType();
16836
16837 // If we receive a broken type, recover by assuming 'int' and
16838 // marking this declaration as invalid.
16839 if (T.isNull() || T->containsErrors()) {
16840 InvalidDecl = true;
16841 T = Context.IntTy;
16842 }
16843
16844 QualType EltTy = Context.getBaseElementType(T);
16845 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
16846 if (RequireCompleteSizedType(Loc, EltTy,
16847 diag::err_field_incomplete_or_sizeless)) {
16848 // Fields of incomplete type force their record to be invalid.
16849 Record->setInvalidDecl();
16850 InvalidDecl = true;
16851 } else {
16852 NamedDecl *Def;
16853 EltTy->isIncompleteType(&Def);
16854 if (Def && Def->isInvalidDecl()) {
16855 Record->setInvalidDecl();
16856 InvalidDecl = true;
16857 }
16858 }
16859 }
16860
16861 // TR 18037 does not allow fields to be declared with address space
16862 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
16863 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
16864 Diag(Loc, diag::err_field_with_address_space);
16865 Record->setInvalidDecl();
16866 InvalidDecl = true;
16867 }
16868
16869 if (LangOpts.OpenCL) {
16870 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
16871 // used as structure or union field: image, sampler, event or block types.
16872 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
16873 T->isBlockPointerType()) {
16874 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
16875 Record->setInvalidDecl();
16876 InvalidDecl = true;
16877 }
16878 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
16879 // is enabled.
16880 if (BitWidth && !getOpenCLOptions().isAvailableOption(
16881 "__cl_clang_bitfields", LangOpts)) {
16882 Diag(Loc, diag::err_opencl_bitfields);
16883 InvalidDecl = true;
16884 }
16885 }
16886
16887 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
16888 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
16889 T.hasQualifiers()) {
16890 InvalidDecl = true;
16891 Diag(Loc, diag::err_anon_bitfield_qualifiers);
16892 }
16893
16894 // C99 6.7.2.1p8: A member of a structure or union may have any type other
16895 // than a variably modified type.
16896 if (!InvalidDecl && T->isVariablyModifiedType()) {
16897 if (!tryToFixVariablyModifiedVarType(
16898 TInfo, T, Loc, diag::err_typecheck_field_variable_size))
16899 InvalidDecl = true;
16900 }
16901
16902 // Fields can not have abstract class types
16903 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
16904 diag::err_abstract_type_in_decl,
16905 AbstractFieldType))
16906 InvalidDecl = true;
16907
16908 bool ZeroWidth = false;
16909 if (InvalidDecl)
16910 BitWidth = nullptr;
16911 // If this is declared as a bit-field, check the bit-field.
16912 if (BitWidth) {
16913 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
16914 &ZeroWidth).get();
16915 if (!BitWidth) {
16916 InvalidDecl = true;
16917 BitWidth = nullptr;
16918 ZeroWidth = false;
16919 }
16920 }
16921
16922 // Check that 'mutable' is consistent with the type of the declaration.
16923 if (!InvalidDecl && Mutable) {
16924 unsigned DiagID = 0;
16925 if (T->isReferenceType())
16926 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
16927 : diag::err_mutable_reference;
16928 else if (T.isConstQualified())
16929 DiagID = diag::err_mutable_const;
16930
16931 if (DiagID) {
16932 SourceLocation ErrLoc = Loc;
16933 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
16934 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
16935 Diag(ErrLoc, DiagID);
16936 if (DiagID != diag::ext_mutable_reference) {
16937 Mutable = false;
16938 InvalidDecl = true;
16939 }
16940 }
16941 }
16942
16943 // C++11 [class.union]p8 (DR1460):
16944 // At most one variant member of a union may have a
16945 // brace-or-equal-initializer.
16946 if (InitStyle != ICIS_NoInit)
16947 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
16948
16949 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
16950 BitWidth, Mutable, InitStyle);
16951 if (InvalidDecl)
16952 NewFD->setInvalidDecl();
16953
16954 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
16955 Diag(Loc, diag::err_duplicate_member) << II;
16956 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16957 NewFD->setInvalidDecl();
16958 }
16959
16960 if (!InvalidDecl && getLangOpts().CPlusPlus) {
16961 if (Record->isUnion()) {
16962 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16963 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
16964 if (RDecl->getDefinition()) {
16965 // C++ [class.union]p1: An object of a class with a non-trivial
16966 // constructor, a non-trivial copy constructor, a non-trivial
16967 // destructor, or a non-trivial copy assignment operator
16968 // cannot be a member of a union, nor can an array of such
16969 // objects.
16970 if (CheckNontrivialField(NewFD))
16971 NewFD->setInvalidDecl();
16972 }
16973 }
16974
16975 // C++ [class.union]p1: If a union contains a member of reference type,
16976 // the program is ill-formed, except when compiling with MSVC extensions
16977 // enabled.
16978 if (EltTy->isReferenceType()) {
16979 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
16980 diag::ext_union_member_of_reference_type :
16981 diag::err_union_member_of_reference_type)
16982 << NewFD->getDeclName() << EltTy;
16983 if (!getLangOpts().MicrosoftExt)
16984 NewFD->setInvalidDecl();
16985 }
16986 }
16987 }
16988
16989 // FIXME: We need to pass in the attributes given an AST
16990 // representation, not a parser representation.
16991 if (D) {
16992 // FIXME: The current scope is almost... but not entirely... correct here.
16993 ProcessDeclAttributes(getCurScope(), NewFD, *D);
16994
16995 if (NewFD->hasAttrs())
16996 CheckAlignasUnderalignment(NewFD);
16997 }
16998
16999 // In auto-retain/release, infer strong retension for fields of
17000 // retainable type.
17001 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
17002 NewFD->setInvalidDecl();
17003
17004 if (T.isObjCGCWeak())
17005 Diag(Loc, diag::warn_attribute_weak_on_field);
17006
17007 // PPC MMA non-pointer types are not allowed as field types.
17008 if (Context.getTargetInfo().getTriple().isPPC64() &&
17009 CheckPPCMMAType(T, NewFD->getLocation()))
17010 NewFD->setInvalidDecl();
17011
17012 NewFD->setAccess(AS);
17013 return NewFD;
17014}
17015
17016bool Sema::CheckNontrivialField(FieldDecl *FD) {
17017 assert(FD)(static_cast <bool> (FD) ? void (0) : __assert_fail ("FD"
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 17017, __extension__ __PRETTY_FUNCTION__))
;
17018 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++\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 17018, __extension__ __PRETTY_FUNCTION__))
;
17019
17020 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
17021 return false;
17022
17023 QualType EltTy = Context.getBaseElementType(FD->getType());
17024 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17025 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
17026 if (RDecl->getDefinition()) {
17027 // We check for copy constructors before constructors
17028 // because otherwise we'll never get complaints about
17029 // copy constructors.
17030
17031 CXXSpecialMember member = CXXInvalid;
17032 // We're required to check for any non-trivial constructors. Since the
17033 // implicit default constructor is suppressed if there are any
17034 // user-declared constructors, we just need to check that there is a
17035 // trivial default constructor and a trivial copy constructor. (We don't
17036 // worry about move constructors here, since this is a C++98 check.)
17037 if (RDecl->hasNonTrivialCopyConstructor())
17038 member = CXXCopyConstructor;
17039 else if (!RDecl->hasTrivialDefaultConstructor())
17040 member = CXXDefaultConstructor;
17041 else if (RDecl->hasNonTrivialCopyAssignment())
17042 member = CXXCopyAssignment;
17043 else if (RDecl->hasNonTrivialDestructor())
17044 member = CXXDestructor;
17045
17046 if (member != CXXInvalid) {
17047 if (!getLangOpts().CPlusPlus11 &&
17048 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
17049 // Objective-C++ ARC: it is an error to have a non-trivial field of
17050 // a union. However, system headers in Objective-C programs
17051 // occasionally have Objective-C lifetime objects within unions,
17052 // and rather than cause the program to fail, we make those
17053 // members unavailable.
17054 SourceLocation Loc = FD->getLocation();
17055 if (getSourceManager().isInSystemHeader(Loc)) {
17056 if (!FD->hasAttr<UnavailableAttr>())
17057 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
17058 UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
17059 return false;
17060 }
17061 }
17062
17063 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
17064 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
17065 diag::err_illegal_union_or_anon_struct_member)
17066 << FD->getParent()->isUnion() << FD->getDeclName() << member;
17067 DiagnoseNontrivial(RDecl, member);
17068 return !getLangOpts().CPlusPlus11;
17069 }
17070 }
17071 }
17072
17073 return false;
17074}
17075
17076/// TranslateIvarVisibility - Translate visibility from a token ID to an
17077/// AST enum value.
17078static ObjCIvarDecl::AccessControl
17079TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
17080 switch (ivarVisibility) {
17081 default: llvm_unreachable("Unknown visitibility kind")::llvm::llvm_unreachable_internal("Unknown visitibility kind"
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 17081)
;
17082 case tok::objc_private: return ObjCIvarDecl::Private;
17083 case tok::objc_public: return ObjCIvarDecl::Public;
17084 case tok::objc_protected: return ObjCIvarDecl::Protected;
17085 case tok::objc_package: return ObjCIvarDecl::Package;
17086 }
17087}
17088
17089/// ActOnIvar - Each ivar field of an objective-c class is passed into this
17090/// in order to create an IvarDecl object for it.
17091Decl *Sema::ActOnIvar(Scope *S,
17092 SourceLocation DeclStart,
17093 Declarator &D, Expr *BitfieldWidth,
17094 tok::ObjCKeywordKind Visibility) {
17095
17096 IdentifierInfo *II = D.getIdentifier();
17097 Expr *BitWidth = (Expr*)BitfieldWidth;
17098 SourceLocation Loc = DeclStart;
17099 if (II) Loc = D.getIdentifierLoc();
17100
17101 // FIXME: Unnamed fields can be handled in various different ways, for
17102 // example, unnamed unions inject all members into the struct namespace!
17103
17104 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17105 QualType T = TInfo->getType();
17106
17107 if (BitWidth) {
17108 // 6.7.2.1p3, 6.7.2.1p4
17109 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
17110 if (!BitWidth)
17111 D.setInvalidType();
17112 } else {
17113 // Not a bitfield.
17114
17115 // validate II.
17116
17117 }
17118 if (T->isReferenceType()) {
17119 Diag(Loc, diag::err_ivar_reference_type);
17120 D.setInvalidType();
17121 }
17122 // C99 6.7.2.1p8: A member of a structure or union may have any type other
17123 // than a variably modified type.
17124 else if (T->isVariablyModifiedType()) {
17125 if (!tryToFixVariablyModifiedVarType(
17126 TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
17127 D.setInvalidType();
17128 }
17129
17130 // Get the visibility (access control) for this ivar.
17131 ObjCIvarDecl::AccessControl ac =
17132 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
17133 : ObjCIvarDecl::None;
17134 // Must set ivar's DeclContext to its enclosing interface.
17135 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
17136 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
17137 return nullptr;
17138 ObjCContainerDecl *EnclosingContext;
17139 if (ObjCImplementationDecl *IMPDecl =
17140 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17141 if (LangOpts.ObjCRuntime.isFragile()) {
17142 // Case of ivar declared in an implementation. Context is that of its class.
17143 EnclosingContext = IMPDecl->getClassInterface();
17144 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!\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 17144, __extension__ __PRETTY_FUNCTION__))
;
17145 }
17146 else
17147 EnclosingContext = EnclosingDecl;
17148 } else {
17149 if (ObjCCategoryDecl *CDecl =
17150 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17151 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
17152 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
17153 return nullptr;
17154 }
17155 }
17156 EnclosingContext = EnclosingDecl;
17157 }
17158
17159 // Construct the decl.
17160 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
17161 DeclStart, Loc, II, T,
17162 TInfo, ac, (Expr *)BitfieldWidth);
17163
17164 if (II) {
17165 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
17166 ForVisibleRedeclaration);
17167 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
17168 && !isa<TagDecl>(PrevDecl)) {
17169 Diag(Loc, diag::err_duplicate_member) << II;
17170 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17171 NewID->setInvalidDecl();
17172 }
17173 }
17174
17175 // Process attributes attached to the ivar.
17176 ProcessDeclAttributes(S, NewID, D);
17177
17178 if (D.isInvalidType())
17179 NewID->setInvalidDecl();
17180
17181 // In ARC, infer 'retaining' for ivars of retainable type.
17182 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
17183 NewID->setInvalidDecl();
17184
17185 if (D.getDeclSpec().isModulePrivateSpecified())
17186 NewID->setModulePrivate();
17187
17188 if (II) {
17189 // FIXME: When interfaces are DeclContexts, we'll need to add
17190 // these to the interface.
17191 S->AddDecl(NewID);
17192 IdResolver.AddDecl(NewID);
17193 }
17194
17195 if (LangOpts.ObjCRuntime.isNonFragile() &&
17196 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
17197 Diag(Loc, diag::warn_ivars_in_interface);
17198
17199 return NewID;
17200}
17201
17202/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
17203/// class and class extensions. For every class \@interface and class
17204/// extension \@interface, if the last ivar is a bitfield of any type,
17205/// then add an implicit `char :0` ivar to the end of that interface.
17206void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
17207 SmallVectorImpl<Decl *> &AllIvarDecls) {
17208 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
17209 return;
17210
17211 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
17212 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
17213
17214 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
17215 return;
17216 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
17217 if (!ID) {
17218 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
17219 if (!CD->IsClassExtension())
17220 return;
17221 }
17222 // No need to add this to end of @implementation.
17223 else
17224 return;
17225 }
17226 // All conditions are met. Add a new bitfield to the tail end of ivars.
17227 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
17228 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
17229
17230 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
17231 DeclLoc, DeclLoc, nullptr,
17232 Context.CharTy,
17233 Context.getTrivialTypeSourceInfo(Context.CharTy,
17234 DeclLoc),
17235 ObjCIvarDecl::Private, BW,
17236 true);
17237 AllIvarDecls.push_back(Ivar);
17238}
17239
17240void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
17241 ArrayRef<Decl *> Fields, SourceLocation LBrac,
17242 SourceLocation RBrac,
17243 const ParsedAttributesView &Attrs) {
17244 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 17244, __extension__ __PRETTY_FUNCTION__))
;
17245
17246 // If this is an Objective-C @implementation or category and we have
17247 // new fields here we should reset the layout of the interface since
17248 // it will now change.
17249 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
17250 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
17251 switch (DC->getKind()) {
17252 default: break;
17253 case Decl::ObjCCategory:
17254 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
17255 break;
17256 case Decl::ObjCImplementation:
17257 Context.
17258 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
17259 break;
17260 }
17261 }
17262
17263 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
17264 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
17265
17266 // Start counting up the number of named members; make sure to include
17267 // members of anonymous structs and unions in the total.
17268 unsigned NumNamedMembers = 0;
17269 if (Record) {
17270 for (const auto *I : Record->decls()) {
17271 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
17272 if (IFD->getDeclName())
17273 ++NumNamedMembers;
17274 }
17275 }
17276
17277 // Verify that all the fields are okay.
17278 SmallVector<FieldDecl*, 32> RecFields;
17279
17280 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
17281 i != end; ++i) {
17282 FieldDecl *FD = cast<FieldDecl>(*i);
17283
17284 // Get the type for the field.
17285 const Type *FDTy = FD->getType().getTypePtr();
17286
17287 if (!FD->isAnonymousStructOrUnion()) {
17288 // Remember all fields written by the user.
17289 RecFields.push_back(FD);
17290 }
17291
17292 // If the field is already invalid for some reason, don't emit more
17293 // diagnostics about it.
17294 if (FD->isInvalidDecl()) {
17295 EnclosingDecl->setInvalidDecl();
17296 continue;
17297 }
17298
17299 // C99 6.7.2.1p2:
17300 // A structure or union shall not contain a member with
17301 // incomplete or function type (hence, a structure shall not
17302 // contain an instance of itself, but may contain a pointer to
17303 // an instance of itself), except that the last member of a
17304 // structure with more than one named member may have incomplete
17305 // array type; such a structure (and any union containing,
17306 // possibly recursively, a member that is such a structure)
17307 // shall not be a member of a structure or an element of an
17308 // array.
17309 bool IsLastField = (i + 1 == Fields.end());
17310 if (FDTy->isFunctionType()) {
17311 // Field declared as a function.
17312 Diag(FD->getLocation(), diag::err_field_declared_as_function)
17313 << FD->getDeclName();
17314 FD->setInvalidDecl();
17315 EnclosingDecl->setInvalidDecl();
17316 continue;
17317 } else if (FDTy->isIncompleteArrayType() &&
17318 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
17319 if (Record) {
17320 // Flexible array member.
17321 // Microsoft and g++ is more permissive regarding flexible array.
17322 // It will accept flexible array in union and also
17323 // as the sole element of a struct/class.
17324 unsigned DiagID = 0;
17325 if (!Record->isUnion() && !IsLastField) {
17326 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
17327 << FD->getDeclName() << FD->getType() << Record->getTagKind();
17328 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
17329 FD->setInvalidDecl();
17330 EnclosingDecl->setInvalidDecl();
17331 continue;
17332 } else if (Record->isUnion())
17333 DiagID = getLangOpts().MicrosoftExt
17334 ? diag::ext_flexible_array_union_ms
17335 : getLangOpts().CPlusPlus
17336 ? diag::ext_flexible_array_union_gnu
17337 : diag::err_flexible_array_union;
17338 else if (NumNamedMembers < 1)
17339 DiagID = getLangOpts().MicrosoftExt
17340 ? diag::ext_flexible_array_empty_aggregate_ms
17341 : getLangOpts().CPlusPlus
17342 ? diag::ext_flexible_array_empty_aggregate_gnu
17343 : diag::err_flexible_array_empty_aggregate;
17344
17345 if (DiagID)
17346 Diag(FD->getLocation(), DiagID) << FD->getDeclName()
17347 << Record->getTagKind();
17348 // While the layout of types that contain virtual bases is not specified
17349 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
17350 // virtual bases after the derived members. This would make a flexible
17351 // array member declared at the end of an object not adjacent to the end
17352 // of the type.
17353 if (CXXRecord && CXXRecord->getNumVBases() != 0)
17354 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
17355 << FD->getDeclName() << Record->getTagKind();
17356 if (!getLangOpts().C99)
17357 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
17358 << FD->getDeclName() << Record->getTagKind();
17359
17360 // If the element type has a non-trivial destructor, we would not
17361 // implicitly destroy the elements, so disallow it for now.
17362 //
17363 // FIXME: GCC allows this. We should probably either implicitly delete
17364 // the destructor of the containing class, or just allow this.
17365 QualType BaseElem = Context.getBaseElementType(FD->getType());
17366 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
17367 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
17368 << FD->getDeclName() << FD->getType();
17369 FD->setInvalidDecl();
17370 EnclosingDecl->setInvalidDecl();
17371 continue;
17372 }
17373 // Okay, we have a legal flexible array member at the end of the struct.
17374 Record->setHasFlexibleArrayMember(true);
17375 } else {
17376 // In ObjCContainerDecl ivars with incomplete array type are accepted,
17377 // unless they are followed by another ivar. That check is done
17378 // elsewhere, after synthesized ivars are known.
17379 }
17380 } else if (!FDTy->isDependentType() &&
17381 RequireCompleteSizedType(
17382 FD->getLocation(), FD->getType(),
17383 diag::err_field_incomplete_or_sizeless)) {
17384 // Incomplete type
17385 FD->setInvalidDecl();
17386 EnclosingDecl->setInvalidDecl();
17387 continue;
17388 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
17389 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
17390 // A type which contains a flexible array member is considered to be a
17391 // flexible array member.
17392 Record->setHasFlexibleArrayMember(true);
17393 if (!Record->isUnion()) {
17394 // If this is a struct/class and this is not the last element, reject
17395 // it. Note that GCC supports variable sized arrays in the middle of
17396 // structures.
17397 if (!IsLastField)
17398 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
17399 << FD->getDeclName() << FD->getType();
17400 else {
17401 // We support flexible arrays at the end of structs in
17402 // other structs as an extension.
17403 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
17404 << FD->getDeclName();
17405 }
17406 }
17407 }
17408 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
17409 RequireNonAbstractType(FD->getLocation(), FD->getType(),
17410 diag::err_abstract_type_in_decl,
17411 AbstractIvarType)) {
17412 // Ivars can not have abstract class types
17413 FD->setInvalidDecl();
17414 }
17415 if (Record && FDTTy->getDecl()->hasObjectMember())
17416 Record->setHasObjectMember(true);
17417 if (Record && FDTTy->getDecl()->hasVolatileMember())
17418 Record->setHasVolatileMember(true);
17419 } else if (FDTy->isObjCObjectType()) {
17420 /// A field cannot be an Objective-c object
17421 Diag(FD->getLocation(), diag::err_statically_allocated_object)
17422 << FixItHint::CreateInsertion(FD->getLocation(), "*");
17423 QualType T = Context.getObjCObjectPointerType(FD->getType());
17424 FD->setType(T);
17425 } else if (Record && Record->isUnion() &&
17426 FD->getType().hasNonTrivialObjCLifetime() &&
17427 getSourceManager().isInSystemHeader(FD->getLocation()) &&
17428 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
17429 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
17430 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
17431 // For backward compatibility, fields of C unions declared in system
17432 // headers that have non-trivial ObjC ownership qualifications are marked
17433 // as unavailable unless the qualifier is explicit and __strong. This can
17434 // break ABI compatibility between programs compiled with ARC and MRR, but
17435 // is a better option than rejecting programs using those unions under
17436 // ARC.
17437 FD->addAttr(UnavailableAttr::CreateImplicit(
17438 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
17439 FD->getLocation()));
17440 } else if (getLangOpts().ObjC &&
17441 getLangOpts().getGC() != LangOptions::NonGC && Record &&
17442 !Record->hasObjectMember()) {
17443 if (FD->getType()->isObjCObjectPointerType() ||
17444 FD->getType().isObjCGCStrong())
17445 Record->setHasObjectMember(true);
17446 else if (Context.getAsArrayType(FD->getType())) {
17447 QualType BaseType = Context.getBaseElementType(FD->getType());
17448 if (BaseType->isRecordType() &&
17449 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
17450 Record->setHasObjectMember(true);
17451 else if (BaseType->isObjCObjectPointerType() ||
17452 BaseType.isObjCGCStrong())
17453 Record->setHasObjectMember(true);
17454 }
17455 }
17456
17457 if (Record && !getLangOpts().CPlusPlus &&
17458 !shouldIgnoreForRecordTriviality(FD)) {
17459 QualType FT = FD->getType();
17460 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
17461 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
17462 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
17463 Record->isUnion())
17464 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
17465 }
17466 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
17467 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
17468 Record->setNonTrivialToPrimitiveCopy(true);
17469 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
17470 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
17471 }
17472 if (FT.isDestructedType()) {
17473 Record->setNonTrivialToPrimitiveDestroy(true);
17474 Record->setParamDestroyedInCallee(true);
17475 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
17476 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
17477 }
17478
17479 if (const auto *RT = FT->getAs<RecordType>()) {
17480 if (RT->getDecl()->getArgPassingRestrictions() ==
17481 RecordDecl::APK_CanNeverPassInRegs)
17482 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17483 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
17484 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17485 }
17486
17487 if (Record && FD->getType().isVolatileQualified())
17488 Record->setHasVolatileMember(true);
17489 // Keep track of the number of named members.
17490 if (FD->getIdentifier())
17491 ++NumNamedMembers;
17492 }
17493
17494 // Okay, we successfully defined 'Record'.
17495 if (Record) {
17496 bool Completed = false;
17497 if (CXXRecord) {
17498 if (!CXXRecord->isInvalidDecl()) {
17499 // Set access bits correctly on the directly-declared conversions.
17500 for (CXXRecordDecl::conversion_iterator
17501 I = CXXRecord->conversion_begin(),
17502 E = CXXRecord->conversion_end(); I != E; ++I)
17503 I.setAccess((*I)->getAccess());
17504 }
17505
17506 // Add any implicitly-declared members to this class.
17507 AddImplicitlyDeclaredMembersToClass(CXXRecord);
17508
17509 if (!CXXRecord->isDependentType()) {
17510 if (!CXXRecord->isInvalidDecl()) {
17511 // If we have virtual base classes, we may end up finding multiple
17512 // final overriders for a given virtual function. Check for this
17513 // problem now.
17514 if (CXXRecord->getNumVBases()) {
17515 CXXFinalOverriderMap FinalOverriders;
17516 CXXRecord->getFinalOverriders(FinalOverriders);
17517
17518 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
17519 MEnd = FinalOverriders.end();
17520 M != MEnd; ++M) {
17521 for (OverridingMethods::iterator SO = M->second.begin(),
17522 SOEnd = M->second.end();
17523 SO != SOEnd; ++SO) {
17524 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?\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 17525, __extension__ __PRETTY_FUNCTION__))
17525 "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?\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 17525, __extension__ __PRETTY_FUNCTION__))
;
17526 if (SO->second.size() == 1)
17527 continue;
17528
17529 // C++ [class.virtual]p2:
17530 // In a derived class, if a virtual member function of a base
17531 // class subobject has more than one final overrider the
17532 // program is ill-formed.
17533 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
17534 << (const NamedDecl *)M->first << Record;
17535 Diag(M->first->getLocation(),
17536 diag::note_overridden_virtual_function);
17537 for (OverridingMethods::overriding_iterator
17538 OM = SO->second.begin(),
17539 OMEnd = SO->second.end();
17540 OM != OMEnd; ++OM)
17541 Diag(OM->Method->getLocation(), diag::note_final_overrider)
17542 << (const NamedDecl *)M->first << OM->Method->getParent();
17543
17544 Record->setInvalidDecl();
17545 }
17546 }
17547 CXXRecord->completeDefinition(&FinalOverriders);
17548 Completed = true;
17549 }
17550 }
17551 }
17552 }
17553
17554 if (!Completed)
17555 Record->completeDefinition();
17556
17557 // Handle attributes before checking the layout.
17558 ProcessDeclAttributeList(S, Record, Attrs);
17559
17560 // We may have deferred checking for a deleted destructor. Check now.
17561 if (CXXRecord) {
17562 auto *Dtor = CXXRecord->getDestructor();
17563 if (Dtor && Dtor->isImplicit() &&
17564 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
17565 CXXRecord->setImplicitDestructorIsDeleted();
17566 SetDeclDeleted(Dtor, CXXRecord->getLocation());
17567 }
17568 }
17569
17570 if (Record->hasAttrs()) {
17571 CheckAlignasUnderalignment(Record);
17572
17573 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
17574 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
17575 IA->getRange(), IA->getBestCase(),
17576 IA->getInheritanceModel());
17577 }
17578
17579 // Check if the structure/union declaration is a type that can have zero
17580 // size in C. For C this is a language extension, for C++ it may cause
17581 // compatibility problems.
17582 bool CheckForZeroSize;
17583 if (!getLangOpts().CPlusPlus) {
17584 CheckForZeroSize = true;
17585 } else {
17586 // For C++ filter out types that cannot be referenced in C code.
17587 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
17588 CheckForZeroSize =
17589 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
17590 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
17591 CXXRecord->isCLike();
17592 }
17593 if (CheckForZeroSize) {
17594 bool ZeroSize = true;
17595 bool IsEmpty = true;
17596 unsigned NonBitFields = 0;
17597 for (RecordDecl::field_iterator I = Record->field_begin(),
17598 E = Record->field_end();
17599 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
17600 IsEmpty = false;
17601 if (I->isUnnamedBitfield()) {
17602 if (!I->isZeroLengthBitField(Context))
17603 ZeroSize = false;
17604 } else {
17605 ++NonBitFields;
17606 QualType FieldType = I->getType();
17607 if (FieldType->isIncompleteType() ||
17608 !Context.getTypeSizeInChars(FieldType).isZero())
17609 ZeroSize = false;
17610 }
17611 }
17612
17613 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
17614 // allowed in C++, but warn if its declaration is inside
17615 // extern "C" block.
17616 if (ZeroSize) {
17617 Diag(RecLoc, getLangOpts().CPlusPlus ?
17618 diag::warn_zero_size_struct_union_in_extern_c :
17619 diag::warn_zero_size_struct_union_compat)
17620 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
17621 }
17622
17623 // Structs without named members are extension in C (C99 6.7.2.1p7),
17624 // but are accepted by GCC.
17625 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
17626 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
17627 diag::ext_no_named_members_in_struct_union)
17628 << Record->isUnion();
17629 }
17630 }
17631 } else {
17632 ObjCIvarDecl **ClsFields =
17633 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
17634 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
17635 ID->setEndOfDefinitionLoc(RBrac);
17636 // Add ivar's to class's DeclContext.
17637 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17638 ClsFields[i]->setLexicalDeclContext(ID);
17639 ID->addDecl(ClsFields[i]);
17640 }
17641 // Must enforce the rule that ivars in the base classes may not be
17642 // duplicates.
17643 if (ID->getSuperClass())
17644 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
17645 } else if (ObjCImplementationDecl *IMPDecl =
17646 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17647 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl")(static_cast <bool> (IMPDecl && "ActOnFields - missing ObjCImplementationDecl"
) ? void (0) : __assert_fail ("IMPDecl && \"ActOnFields - missing ObjCImplementationDecl\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 17647, __extension__ __PRETTY_FUNCTION__))
;
17648 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
17649 // Ivar declared in @implementation never belongs to the implementation.
17650 // Only it is in implementation's lexical context.
17651 ClsFields[I]->setLexicalDeclContext(IMPDecl);
17652 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
17653 IMPDecl->setIvarLBraceLoc(LBrac);
17654 IMPDecl->setIvarRBraceLoc(RBrac);
17655 } else if (ObjCCategoryDecl *CDecl =
17656 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17657 // case of ivars in class extension; all other cases have been
17658 // reported as errors elsewhere.
17659 // FIXME. Class extension does not have a LocEnd field.
17660 // CDecl->setLocEnd(RBrac);
17661 // Add ivar's to class extension's DeclContext.
17662 // Diagnose redeclaration of private ivars.
17663 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
17664 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17665 if (IDecl) {
17666 if (const ObjCIvarDecl *ClsIvar =
17667 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
17668 Diag(ClsFields[i]->getLocation(),
17669 diag::err_duplicate_ivar_declaration);
17670 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
17671 continue;
17672 }
17673 for (const auto *Ext : IDecl->known_extensions()) {
17674 if (const ObjCIvarDecl *ClsExtIvar
17675 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
17676 Diag(ClsFields[i]->getLocation(),
17677 diag::err_duplicate_ivar_declaration);
17678 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
17679 continue;
17680 }
17681 }
17682 }
17683 ClsFields[i]->setLexicalDeclContext(CDecl);
17684 CDecl->addDecl(ClsFields[i]);
17685 }
17686 CDecl->setIvarLBraceLoc(LBrac);
17687 CDecl->setIvarRBraceLoc(RBrac);
17688 }
17689 }
17690}
17691
17692/// Determine whether the given integral value is representable within
17693/// the given type T.
17694static bool isRepresentableIntegerValue(ASTContext &Context,
17695 llvm::APSInt &Value,
17696 QualType T) {
17697 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!\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 17698, __extension__ __PRETTY_FUNCTION__))
17698 "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!\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 17698, __extension__ __PRETTY_FUNCTION__))
;
17699 unsigned BitWidth = Context.getIntWidth(T);
17700
17701 if (Value.isUnsigned() || Value.isNonNegative()) {
17702 if (T->isSignedIntegerOrEnumerationType())
17703 --BitWidth;
17704 return Value.getActiveBits() <= BitWidth;
17705 }
17706 return Value.getMinSignedBits() <= BitWidth;
17707}
17708
17709// Given an integral type, return the next larger integral type
17710// (or a NULL type of no such type exists).
17711static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
17712 // FIXME: Int128/UInt128 support, which also needs to be introduced into
17713 // enum checking below.
17714 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!\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 17715, __extension__ __PRETTY_FUNCTION__))
17715 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!\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 17715, __extension__ __PRETTY_FUNCTION__))
;
17716 const unsigned NumTypes = 4;
17717 QualType SignedIntegralTypes[NumTypes] = {
17718 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
17719 };
17720 QualType UnsignedIntegralTypes[NumTypes] = {
17721 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
17722 Context.UnsignedLongLongTy
17723 };
17724
17725 unsigned BitWidth = Context.getTypeSize(T);
17726 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
17727 : UnsignedIntegralTypes;
17728 for (unsigned I = 0; I != NumTypes; ++I)
17729 if (Context.getTypeSize(Types[I]) > BitWidth)
17730 return Types[I];
17731
17732 return QualType();
17733}
17734
17735EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
17736 EnumConstantDecl *LastEnumConst,
17737 SourceLocation IdLoc,
17738 IdentifierInfo *Id,
17739 Expr *Val) {
17740 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17741 llvm::APSInt EnumVal(IntWidth);
17742 QualType EltTy;
17743
17744 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
17745 Val = nullptr;
17746
17747 if (Val)
17748 Val = DefaultLvalueConversion(Val).get();
17749
17750 if (Val) {
17751 if (Enum->isDependentType() || Val->isTypeDependent())
17752 EltTy = Context.DependentTy;
17753 else {
17754 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
17755 // underlying type, but do allow it in all other contexts.
17756 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
17757 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
17758 // constant-expression in the enumerator-definition shall be a converted
17759 // constant expression of the underlying type.
17760 EltTy = Enum->getIntegerType();
17761 ExprResult Converted =
17762 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
17763 CCEK_Enumerator);
17764 if (Converted.isInvalid())
17765 Val = nullptr;
17766 else
17767 Val = Converted.get();
17768 } else if (!Val->isValueDependent() &&
17769 !(Val =
17770 VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
17771 .get())) {
17772 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
17773 } else {
17774 if (Enum->isComplete()) {
17775 EltTy = Enum->getIntegerType();
17776
17777 // In Obj-C and Microsoft mode, require the enumeration value to be
17778 // representable in the underlying type of the enumeration. In C++11,
17779 // we perform a non-narrowing conversion as part of converted constant
17780 // expression checking.
17781 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17782 if (Context.getTargetInfo()
17783 .getTriple()
17784 .isWindowsMSVCEnvironment()) {
17785 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
17786 } else {
17787 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
17788 }
17789 }
17790
17791 // Cast to the underlying type.
17792 Val = ImpCastExprToType(Val, EltTy,
17793 EltTy->isBooleanType() ? CK_IntegralToBoolean
17794 : CK_IntegralCast)
17795 .get();
17796 } else if (getLangOpts().CPlusPlus) {
17797 // C++11 [dcl.enum]p5:
17798 // If the underlying type is not fixed, the type of each enumerator
17799 // is the type of its initializing value:
17800 // - If an initializer is specified for an enumerator, the
17801 // initializing value has the same type as the expression.
17802 EltTy = Val->getType();
17803 } else {
17804 // C99 6.7.2.2p2:
17805 // The expression that defines the value of an enumeration constant
17806 // shall be an integer constant expression that has a value
17807 // representable as an int.
17808
17809 // Complain if the value is not representable in an int.
17810 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
17811 Diag(IdLoc, diag::ext_enum_value_not_int)
17812 << toString(EnumVal, 10) << Val->getSourceRange()
17813 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
17814 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
17815 // Force the type of the expression to 'int'.
17816 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
17817 }
17818 EltTy = Val->getType();
17819 }
17820 }
17821 }
17822 }
17823
17824 if (!Val) {
17825 if (Enum->isDependentType())
17826 EltTy = Context.DependentTy;
17827 else if (!LastEnumConst) {
17828 // C++0x [dcl.enum]p5:
17829 // If the underlying type is not fixed, the type of each enumerator
17830 // is the type of its initializing value:
17831 // - If no initializer is specified for the first enumerator, the
17832 // initializing value has an unspecified integral type.
17833 //
17834 // GCC uses 'int' for its unspecified integral type, as does
17835 // C99 6.7.2.2p3.
17836 if (Enum->isFixed()) {
17837 EltTy = Enum->getIntegerType();
17838 }
17839 else {
17840 EltTy = Context.IntTy;
17841 }
17842 } else {
17843 // Assign the last value + 1.
17844 EnumVal = LastEnumConst->getInitVal();
17845 ++EnumVal;
17846 EltTy = LastEnumConst->getType();
17847
17848 // Check for overflow on increment.
17849 if (EnumVal < LastEnumConst->getInitVal()) {
17850 // C++0x [dcl.enum]p5:
17851 // If the underlying type is not fixed, the type of each enumerator
17852 // is the type of its initializing value:
17853 //
17854 // - Otherwise the type of the initializing value is the same as
17855 // the type of the initializing value of the preceding enumerator
17856 // unless the incremented value is not representable in that type,
17857 // in which case the type is an unspecified integral type
17858 // sufficient to contain the incremented value. If no such type
17859 // exists, the program is ill-formed.
17860 QualType T = getNextLargerIntegralType(Context, EltTy);
17861 if (T.isNull() || Enum->isFixed()) {
17862 // There is no integral type larger enough to represent this
17863 // value. Complain, then allow the value to wrap around.
17864 EnumVal = LastEnumConst->getInitVal();
17865 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
17866 ++EnumVal;
17867 if (Enum->isFixed())
17868 // When the underlying type is fixed, this is ill-formed.
17869 Diag(IdLoc, diag::err_enumerator_wrapped)
17870 << toString(EnumVal, 10)
17871 << EltTy;
17872 else
17873 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
17874 << toString(EnumVal, 10);
17875 } else {
17876 EltTy = T;
17877 }
17878
17879 // Retrieve the last enumerator's value, extent that type to the
17880 // type that is supposed to be large enough to represent the incremented
17881 // value, then increment.
17882 EnumVal = LastEnumConst->getInitVal();
17883 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17884 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
17885 ++EnumVal;
17886
17887 // If we're not in C++, diagnose the overflow of enumerator values,
17888 // which in C99 means that the enumerator value is not representable in
17889 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
17890 // permits enumerator values that are representable in some larger
17891 // integral type.
17892 if (!getLangOpts().CPlusPlus && !T.isNull())
17893 Diag(IdLoc, diag::warn_enum_value_overflow);
17894 } else if (!getLangOpts().CPlusPlus &&
17895 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17896 // Enforce C99 6.7.2.2p2 even when we compute the next value.
17897 Diag(IdLoc, diag::ext_enum_value_not_int)
17898 << toString(EnumVal, 10) << 1;
17899 }
17900 }
17901 }
17902
17903 if (!EltTy->isDependentType()) {
17904 // Make the enumerator value match the signedness and size of the
17905 // enumerator's type.
17906 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
17907 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17908 }
17909
17910 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
17911 Val, EnumVal);
17912}
17913
17914Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
17915 SourceLocation IILoc) {
17916 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
17917 !getLangOpts().CPlusPlus)
17918 return SkipBodyInfo();
17919
17920 // We have an anonymous enum definition. Look up the first enumerator to
17921 // determine if we should merge the definition with an existing one and
17922 // skip the body.
17923 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
17924 forRedeclarationInCurContext());
17925 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
17926 if (!PrevECD)
17927 return SkipBodyInfo();
17928
17929 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
17930 NamedDecl *Hidden;
17931 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
17932 SkipBodyInfo Skip;
17933 Skip.Previous = Hidden;
17934 return Skip;
17935 }
17936
17937 return SkipBodyInfo();
17938}
17939
17940Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
17941 SourceLocation IdLoc, IdentifierInfo *Id,
17942 const ParsedAttributesView &Attrs,
17943 SourceLocation EqualLoc, Expr *Val) {
17944 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
17945 EnumConstantDecl *LastEnumConst =
17946 cast_or_null<EnumConstantDecl>(lastEnumConst);
17947
17948 // The scope passed in may not be a decl scope. Zip up the scope tree until
17949 // we find one that is.
17950 S = getNonFieldDeclScope(S);
17951
17952 // Verify that there isn't already something declared with this name in this
17953 // scope.
17954 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
17955 LookupName(R, S);
17956 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
17957
17958 if (PrevDecl && PrevDecl->isTemplateParameter()) {
17959 // Maybe we will complain about the shadowed template parameter.
17960 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
17961 // Just pretend that we didn't see the previous declaration.
17962 PrevDecl = nullptr;
17963 }
17964
17965 // C++ [class.mem]p15:
17966 // If T is the name of a class, then each of the following shall have a name
17967 // different from T:
17968 // - every enumerator of every member of class T that is an unscoped
17969 // enumerated type
17970 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
17971 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
17972 DeclarationNameInfo(Id, IdLoc));
17973
17974 EnumConstantDecl *New =
17975 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
17976 if (!New)
17977 return nullptr;
17978
17979 if (PrevDecl) {
17980 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
17981 // Check for other kinds of shadowing not already handled.
17982 CheckShadow(New, PrevDecl, R);
17983 }
17984
17985 // When in C++, we may get a TagDecl with the same name; in this case the
17986 // enum constant will 'hide' the tag.
17987 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++!\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 17988, __extension__ __PRETTY_FUNCTION__))
17988 "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++!\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 17988, __extension__ __PRETTY_FUNCTION__))
;
17989 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
17990 if (isa<EnumConstantDecl>(PrevDecl))
17991 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
17992 else
17993 Diag(IdLoc, diag::err_redefinition) << Id;
17994 notePreviousDefinition(PrevDecl, IdLoc);
17995 return nullptr;
17996 }
17997 }
17998
17999 // Process attributes.
18000 ProcessDeclAttributeList(S, New, Attrs);
18001 AddPragmaAttributes(S, New);
18002
18003 // Register this decl in the current scope stack.
18004 New->setAccess(TheEnumDecl->getAccess());
18005 PushOnScopeChains(New, S);
18006
18007 ActOnDocumentableDecl(New);
18008
18009 return New;
18010}
18011
18012// Returns true when the enum initial expression does not trigger the
18013// duplicate enum warning. A few common cases are exempted as follows:
18014// Element2 = Element1
18015// Element2 = Element1 + 1
18016// Element2 = Element1 - 1
18017// Where Element2 and Element1 are from the same enum.
18018static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
18019 Expr *InitExpr = ECD->getInitExpr();
18020 if (!InitExpr)
18021 return true;
18022 InitExpr = InitExpr->IgnoreImpCasts();
18023
18024 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
18025 if (!BO->isAdditiveOp())
18026 return true;
18027 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
18028 if (!IL)
18029 return true;
18030 if (IL->getValue() != 1)
18031 return true;
18032
18033 InitExpr = BO->getLHS();
18034 }
18035
18036 // This checks if the elements are from the same enum.
18037 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
18038 if (!DRE)
18039 return true;
18040
18041 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
18042 if (!EnumConstant)
18043 return true;
18044
18045 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
18046 Enum)
18047 return true;
18048
18049 return false;
18050}
18051
18052// Emits a warning when an element is implicitly set a value that
18053// a previous element has already been set to.
18054static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
18055 EnumDecl *Enum, QualType EnumType) {
18056 // Avoid anonymous enums
18057 if (!Enum->getIdentifier())
18058 return;
18059
18060 // Only check for small enums.
18061 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
18062 return;
18063
18064 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
18065 return;
18066
18067 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
18068 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
18069
18070 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
18071
18072 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
18073 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
18074
18075 // Use int64_t as a key to avoid needing special handling for map keys.
18076 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
18077 llvm::APSInt Val = D->getInitVal();
18078 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
18079 };
18080
18081 DuplicatesVector DupVector;
18082 ValueToVectorMap EnumMap;
18083
18084 // Populate the EnumMap with all values represented by enum constants without
18085 // an initializer.
18086 for (auto *Element : Elements) {
18087 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
18088
18089 // Null EnumConstantDecl means a previous diagnostic has been emitted for
18090 // this constant. Skip this enum since it may be ill-formed.
18091 if (!ECD) {
18092 return;
18093 }
18094
18095 // Constants with initalizers are handled in the next loop.
18096 if (ECD->getInitExpr())
18097 continue;
18098
18099 // Duplicate values are handled in the next loop.
18100 EnumMap.insert({EnumConstantToKey(ECD), ECD});
18101 }
18102
18103 if (EnumMap.size() == 0)
18104 return;
18105
18106 // Create vectors for any values that has duplicates.
18107 for (auto *Element : Elements) {
18108 // The last loop returned if any constant was null.
18109 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
18110 if (!ValidDuplicateEnum(ECD, Enum))
18111 continue;
18112
18113 auto Iter = EnumMap.find(EnumConstantToKey(ECD));
18114 if (Iter == EnumMap.end())
18115 continue;
18116
18117 DeclOrVector& Entry = Iter->second;
18118 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
18119 // Ensure constants are different.
18120 if (D == ECD)
18121 continue;
18122
18123 // Create new vector and push values onto it.
18124 auto Vec = std::make_unique<ECDVector>();
18125 Vec->push_back(D);
18126 Vec->push_back(ECD);
18127
18128 // Update entry to point to the duplicates vector.
18129 Entry = Vec.get();
18130
18131 // Store the vector somewhere we can consult later for quick emission of
18132 // diagnostics.
18133 DupVector.emplace_back(std::move(Vec));
18134 continue;
18135 }
18136
18137 ECDVector *Vec = Entry.get<ECDVector*>();
18138 // Make sure constants are not added more than once.
18139 if (*Vec->begin() == ECD)
18140 continue;
18141
18142 Vec->push_back(ECD);
18143 }
18144
18145 // Emit diagnostics.
18146 for (const auto &Vec : DupVector) {
18147 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.\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 18147, __extension__ __PRETTY_FUNCTION__))
;
18148
18149 // Emit warning for one enum constant.
18150 auto *FirstECD = Vec->front();
18151 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
18152 << FirstECD << toString(FirstECD->getInitVal(), 10)
18153 << FirstECD->getSourceRange();
18154
18155 // Emit one note for each of the remaining enum constants with
18156 // the same value.
18157 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
18158 S.Diag(ECD->getLocation(), diag::note_duplicate_element)
18159 << ECD << toString(ECD->getInitVal(), 10)
18160 << ECD->getSourceRange();
18161 }
18162}
18163
18164bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
18165 bool AllowMask) const {
18166 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\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 18166, __extension__ __PRETTY_FUNCTION__))
;
18167 assert(ED->isCompleteDefinition() && "expected enum definition")(static_cast <bool> (ED->isCompleteDefinition() &&
"expected enum definition") ? void (0) : __assert_fail ("ED->isCompleteDefinition() && \"expected enum definition\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 18167, __extension__ __PRETTY_FUNCTION__))
;
18168
18169 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
18170 llvm::APInt &FlagBits = R.first->second;
18171
18172 if (R.second) {
18173 for (auto *E : ED->enumerators()) {
18174 const auto &EVal = E->getInitVal();
18175 // Only single-bit enumerators introduce new flag values.
18176 if (EVal.isPowerOf2())
18177 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
18178 }
18179 }
18180
18181 // A value is in a flag enum if either its bits are a subset of the enum's
18182 // flag bits (the first condition) or we are allowing masks and the same is
18183 // true of its complement (the second condition). When masks are allowed, we
18184 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
18185 //
18186 // While it's true that any value could be used as a mask, the assumption is
18187 // that a mask will have all of the insignificant bits set. Anything else is
18188 // likely a logic error.
18189 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
18190 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
18191}
18192
18193void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
18194 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
18195 const ParsedAttributesView &Attrs) {
18196 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
18197 QualType EnumType = Context.getTypeDeclType(Enum);
18198
18199 ProcessDeclAttributeList(S, Enum, Attrs);
18200
18201 if (Enum->isDependentType()) {
18202 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18203 EnumConstantDecl *ECD =
18204 cast_or_null<EnumConstantDecl>(Elements[i]);
18205 if (!ECD) continue;
18206
18207 ECD->setType(EnumType);
18208 }
18209
18210 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
18211 return;
18212 }
18213
18214 // TODO: If the result value doesn't fit in an int, it must be a long or long
18215 // long value. ISO C does not support this, but GCC does as an extension,
18216 // emit a warning.
18217 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18218 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
18219 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
18220
18221 // Verify that all the values are okay, compute the size of the values, and
18222 // reverse the list.
18223 unsigned NumNegativeBits = 0;
18224 unsigned NumPositiveBits = 0;
18225
18226 // Keep track of whether all elements have type int.
18227 bool AllElementsInt = true;
18228
18229 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18230 EnumConstantDecl *ECD =
18231 cast_or_null<EnumConstantDecl>(Elements[i]);
18232 if (!ECD) continue; // Already issued a diagnostic.
18233
18234 const llvm::APSInt &InitVal = ECD->getInitVal();
18235
18236 // Keep track of the size of positive and negative values.
18237 if (InitVal.isUnsigned() || InitVal.isNonNegative())
18238 NumPositiveBits = std::max(NumPositiveBits,
18239 (unsigned)InitVal.getActiveBits());
18240 else
18241 NumNegativeBits = std::max(NumNegativeBits,
18242 (unsigned)InitVal.getMinSignedBits());
18243
18244 // Keep track of whether every enum element has type int (very common).
18245 if (AllElementsInt)
18246 AllElementsInt = ECD->getType() == Context.IntTy;
18247 }
18248
18249 // Figure out the type that should be used for this enum.
18250 QualType BestType;
18251 unsigned BestWidth;
18252
18253 // C++0x N3000 [conv.prom]p3:
18254 // An rvalue of an unscoped enumeration type whose underlying
18255 // type is not fixed can be converted to an rvalue of the first
18256 // of the following types that can represent all the values of
18257 // the enumeration: int, unsigned int, long int, unsigned long
18258 // int, long long int, or unsigned long long int.
18259 // C99 6.4.4.3p2:
18260 // An identifier declared as an enumeration constant has type int.
18261 // The C99 rule is modified by a gcc extension
18262 QualType BestPromotionType;
18263
18264 bool Packed = Enum->hasAttr<PackedAttr>();
18265 // -fshort-enums is the equivalent to specifying the packed attribute on all
18266 // enum definitions.
18267 if (LangOpts.ShortEnums)
18268 Packed = true;
18269
18270 // If the enum already has a type because it is fixed or dictated by the
18271 // target, promote that type instead of analyzing the enumerators.
18272 if (Enum->isComplete()) {
18273 BestType = Enum->getIntegerType();
18274 if (BestType->isPromotableIntegerType())
18275 BestPromotionType = Context.getPromotedIntegerType(BestType);
18276 else
18277 BestPromotionType = BestType;
18278
18279 BestWidth = Context.getIntWidth(BestType);
18280 }
18281 else if (NumNegativeBits) {
18282 // If there is a negative value, figure out the smallest integer type (of
18283 // int/long/longlong) that fits.
18284 // If it's packed, check also if it fits a char or a short.
18285 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
18286 BestType = Context.SignedCharTy;
18287 BestWidth = CharWidth;
18288 } else if (Packed && NumNegativeBits <= ShortWidth &&
18289 NumPositiveBits < ShortWidth) {
18290 BestType = Context.ShortTy;
18291 BestWidth = ShortWidth;
18292 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
18293 BestType = Context.IntTy;
18294 BestWidth = IntWidth;
18295 } else {
18296 BestWidth = Context.getTargetInfo().getLongWidth();
18297
18298 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
18299 BestType = Context.LongTy;
18300 } else {
18301 BestWidth = Context.getTargetInfo().getLongLongWidth();
18302
18303 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
18304 Diag(Enum->getLocation(), diag::ext_enum_too_large);
18305 BestType = Context.LongLongTy;
18306 }
18307 }
18308 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
18309 } else {
18310 // If there is no negative value, figure out the smallest type that fits
18311 // all of the enumerator values.
18312 // If it's packed, check also if it fits a char or a short.
18313 if (Packed && NumPositiveBits <= CharWidth) {
18314 BestType = Context.UnsignedCharTy;
18315 BestPromotionType = Context.IntTy;
18316 BestWidth = CharWidth;
18317 } else if (Packed && NumPositiveBits <= ShortWidth) {
18318 BestType = Context.UnsignedShortTy;
18319 BestPromotionType = Context.IntTy;
18320 BestWidth = ShortWidth;
18321 } else if (NumPositiveBits <= IntWidth) {
18322 BestType = Context.UnsignedIntTy;
18323 BestWidth = IntWidth;
18324 BestPromotionType
18325 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18326 ? Context.UnsignedIntTy : Context.IntTy;
18327 } else if (NumPositiveBits <=
18328 (BestWidth = Context.getTargetInfo().getLongWidth())) {
18329 BestType = Context.UnsignedLongTy;
18330 BestPromotionType
18331 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18332 ? Context.UnsignedLongTy : Context.LongTy;
18333 } else {
18334 BestWidth = Context.getTargetInfo().getLongLongWidth();
18335 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?\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 18336, __extension__ __PRETTY_FUNCTION__))
18336 "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?\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 18336, __extension__ __PRETTY_FUNCTION__))
;
18337 BestType = Context.UnsignedLongLongTy;
18338 BestPromotionType
18339 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18340 ? Context.UnsignedLongLongTy : Context.LongLongTy;
18341 }
18342 }
18343
18344 // Loop over all of the enumerator constants, changing their types to match
18345 // the type of the enum if needed.
18346 for (auto *D : Elements) {
18347 auto *ECD = cast_or_null<EnumConstantDecl>(D);
18348 if (!ECD) continue; // Already issued a diagnostic.
18349
18350 // Standard C says the enumerators have int type, but we allow, as an
18351 // extension, the enumerators to be larger than int size. If each
18352 // enumerator value fits in an int, type it as an int, otherwise type it the
18353 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
18354 // that X has type 'int', not 'unsigned'.
18355
18356 // Determine whether the value fits into an int.
18357 llvm::APSInt InitVal = ECD->getInitVal();
18358
18359 // If it fits into an integer type, force it. Otherwise force it to match
18360 // the enum decl type.
18361 QualType NewTy;
18362 unsigned NewWidth;
18363 bool NewSign;
18364 if (!getLangOpts().CPlusPlus &&
18365 !Enum->isFixed() &&
18366 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
18367 NewTy = Context.IntTy;
18368 NewWidth = IntWidth;
18369 NewSign = true;
18370 } else if (ECD->getType() == BestType) {
18371 // Already the right type!
18372 if (getLangOpts().CPlusPlus)
18373 // C++ [dcl.enum]p4: Following the closing brace of an
18374 // enum-specifier, each enumerator has the type of its
18375 // enumeration.
18376 ECD->setType(EnumType);
18377 continue;
18378 } else {
18379 NewTy = BestType;
18380 NewWidth = BestWidth;
18381 NewSign = BestType->isSignedIntegerOrEnumerationType();
18382 }
18383
18384 // Adjust the APSInt value.
18385 InitVal = InitVal.extOrTrunc(NewWidth);
18386 InitVal.setIsSigned(NewSign);
18387 ECD->setInitVal(InitVal);
18388
18389 // Adjust the Expr initializer and type.
18390 if (ECD->getInitExpr() &&
18391 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
18392 ECD->setInitExpr(ImplicitCastExpr::Create(
18393 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
18394 /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
18395 if (getLangOpts().CPlusPlus)
18396 // C++ [dcl.enum]p4: Following the closing brace of an
18397 // enum-specifier, each enumerator has the type of its
18398 // enumeration.
18399 ECD->setType(EnumType);
18400 else
18401 ECD->setType(NewTy);
18402 }
18403
18404 Enum->completeDefinition(BestType, BestPromotionType,
18405 NumPositiveBits, NumNegativeBits);
18406
18407 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
18408
18409 if (Enum->isClosedFlag()) {
18410 for (Decl *D : Elements) {
18411 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
18412 if (!ECD) continue; // Already issued a diagnostic.
18413
18414 llvm::APSInt InitVal = ECD->getInitVal();
18415 if (InitVal != 0 && !InitVal.isPowerOf2() &&
18416 !IsValueInFlagEnum(Enum, InitVal, true))
18417 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
18418 << ECD << Enum;
18419 }
18420 }
18421
18422 // Now that the enum type is defined, ensure it's not been underaligned.
18423 if (Enum->hasAttrs())
18424 CheckAlignasUnderalignment(Enum);
18425}
18426
18427Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
18428 SourceLocation StartLoc,
18429 SourceLocation EndLoc) {
18430 StringLiteral *AsmString = cast<StringLiteral>(expr);
18431
18432 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
18433 AsmString, StartLoc,
18434 EndLoc);
18435 CurContext->addDecl(New);
18436 return New;
18437}
18438
18439void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
18440 IdentifierInfo* AliasName,
18441 SourceLocation PragmaLoc,
18442 SourceLocation NameLoc,
18443 SourceLocation AliasNameLoc) {
18444 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
18445 LookupOrdinaryName);
18446 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
18447 AttributeCommonInfo::AS_Pragma);
18448 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
18449 Context, AliasName->getName(), /*LiteralLabel=*/true, Info);
18450
18451 // If a declaration that:
18452 // 1) declares a function or a variable
18453 // 2) has external linkage
18454 // already exists, add a label attribute to it.
18455 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18456 if (isDeclExternC(PrevDecl))
18457 PrevDecl->addAttr(Attr);
18458 else
18459 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
18460 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
18461 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
18462 } else
18463 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
18464}
18465
18466void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
18467 SourceLocation PragmaLoc,
18468 SourceLocation NameLoc) {
18469 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
18470
18471 if (PrevDecl) {
18472 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
18473 } else {
18474 (void)WeakUndeclaredIdentifiers.insert(
18475 std::pair<IdentifierInfo*,WeakInfo>
18476 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
18477 }
18478}
18479
18480void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
18481 IdentifierInfo* AliasName,
18482 SourceLocation PragmaLoc,
18483 SourceLocation NameLoc,
18484 SourceLocation AliasNameLoc) {
18485 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
18486 LookupOrdinaryName);
18487 WeakInfo W = WeakInfo(Name, NameLoc);
18488
18489 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18490 if (!PrevDecl->hasAttr<AliasAttr>())
18491 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
18492 DeclApplyPragmaWeak(TUScope, ND, W);
18493 } else {
18494 (void)WeakUndeclaredIdentifiers.insert(
18495 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
18496 }
18497}
18498
18499Decl *Sema::getObjCDeclContext() const {
18500 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
18501}
18502
18503Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
18504 bool Final) {
18505 assert(FD && "Expected non-null FunctionDecl")(static_cast <bool> (FD && "Expected non-null FunctionDecl"
) ? void (0) : __assert_fail ("FD && \"Expected non-null FunctionDecl\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/lib/Sema/SemaDecl.cpp"
, 18505, __extension__ __PRETTY_FUNCTION__))
;
18506
18507 // SYCL functions can be template, so we check if they have appropriate
18508 // attribute prior to checking if it is a template.
18509 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
18510 return FunctionEmissionStatus::Emitted;
18511
18512 // Templates are emitted when they're instantiated.
18513 if (FD->isDependentContext())
18514 return FunctionEmissionStatus::TemplateDiscarded;
18515
18516 // Check whether this function is an externally visible definition.
18517 auto IsEmittedForExternalSymbol = [this, FD]() {
18518 // We have to check the GVA linkage of the function's *definition* -- if we
18519 // only have a declaration, we don't know whether or not the function will
18520 // be emitted, because (say) the definition could include "inline".
18521 FunctionDecl *Def = FD->getDefinition();
18522
18523 return Def && !isDiscardableGVALinkage(
18524 getASTContext().GetGVALinkageForFunction(Def));
18525 };
18526
18527 if (LangOpts.OpenMPIsDevice) {
18528 // In OpenMP device mode we will not emit host only functions, or functions
18529 // we don't need due to their linkage.
18530 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18531 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18532 // DevTy may be changed later by
18533 // #pragma omp declare target to(*) device_type(*).
18534 // Therefore DevTy having no value does not imply host. The emission status
18535 // will be checked again at the end of compilation unit with Final = true.
18536 if (DevTy.hasValue())
18537 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
18538 return FunctionEmissionStatus::OMPDiscarded;
18539 // If we have an explicit value for the device type, or we are in a target
18540 // declare context, we need to emit all extern and used symbols.
18541 if (isInOpenMPDeclareTargetContext() || DevTy.hasValue())
18542 if (IsEmittedForExternalSymbol())
18543 return FunctionEmissionStatus::Emitted;
18544 // Device mode only emits what it must, if it wasn't tagged yet and needed,
18545 // we'll omit it.
18546 if (Final)
18547 return FunctionEmissionStatus::OMPDiscarded;
18548 } else if (LangOpts.OpenMP > 45) {
18549 // In OpenMP host compilation prior to 5.0 everything was an emitted host
18550 // function. In 5.0, no_host was introduced which might cause a function to
18551 // be ommitted.
18552 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18553 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18554 if (DevTy.hasValue())
18555 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
18556 return FunctionEmissionStatus::OMPDiscarded;
18557 }
18558
18559 if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
18560 return FunctionEmissionStatus::Emitted;
18561
18562 if (LangOpts.CUDA) {
18563 // When compiling for device, host functions are never emitted. Similarly,
18564 // when compiling for host, device and global functions are never emitted.
18565 // (Technically, we do emit a host-side stub for global functions, but this
18566 // doesn't count for our purposes here.)
18567 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
18568 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
18569 return FunctionEmissionStatus::CUDADiscarded;
18570 if (!LangOpts.CUDAIsDevice &&
18571 (T == Sema::CFT_Device || T == Sema::CFT_Global))
18572 return FunctionEmissionStatus::CUDADiscarded;
18573
18574 if (IsEmittedForExternalSymbol())
18575 return FunctionEmissionStatus::Emitted;
18576 }
18577
18578 // Otherwise, the function is known-emitted if it's in our set of
18579 // known-emitted functions.
18580 return FunctionEmissionStatus::Unknown;
18581}
18582
18583bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
18584 // Host-side references to a __global__ function refer to the stub, so the
18585 // function itself is never emitted and therefore should not be marked.
18586 // If we have host fn calls kernel fn calls host+device, the HD function
18587 // does not get instantiated on the host. We model this by omitting at the
18588 // call to the kernel from the callgraph. This ensures that, when compiling
18589 // for host, only HD functions actually called from the host get marked as
18590 // known-emitted.
18591 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
18592 IdentifyCUDATarget(Callee) == CFT_Global;
18593}

/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/include/clang/AST/DeclBase.h

1//===- DeclBase.h - Base Classes for representing declarations --*- C++ -*-===//
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 defines the Decl and DeclContext interfaces.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_AST_DECLBASE_H
14#define LLVM_CLANG_AST_DECLBASE_H
15
16#include "clang/AST/ASTDumperUtils.h"
17#include "clang/AST/AttrIterator.h"
18#include "clang/AST/DeclarationName.h"
19#include "clang/Basic/IdentifierTable.h"
20#include "clang/Basic/LLVM.h"
21#include "clang/Basic/SourceLocation.h"
22#include "clang/Basic/Specifiers.h"
23#include "llvm/ADT/ArrayRef.h"
24#include "llvm/ADT/PointerIntPair.h"
25#include "llvm/ADT/PointerUnion.h"
26#include "llvm/ADT/iterator.h"
27#include "llvm/ADT/iterator_range.h"
28#include "llvm/Support/Casting.h"
29#include "llvm/Support/Compiler.h"
30#include "llvm/Support/PrettyStackTrace.h"
31#include "llvm/Support/VersionTuple.h"
32#include <algorithm>
33#include <cassert>
34#include <cstddef>
35#include <iterator>
36#include <string>
37#include <type_traits>
38#include <utility>
39
40namespace clang {
41
42class ASTContext;
43class ASTMutationListener;
44class Attr;
45class BlockDecl;
46class DeclContext;
47class ExternalSourceSymbolAttr;
48class FunctionDecl;
49class FunctionType;
50class IdentifierInfo;
51enum Linkage : unsigned char;
52class LinkageSpecDecl;
53class Module;
54class NamedDecl;
55class ObjCCategoryDecl;
56class ObjCCategoryImplDecl;
57class ObjCContainerDecl;
58class ObjCImplDecl;
59class ObjCImplementationDecl;
60class ObjCInterfaceDecl;
61class ObjCMethodDecl;
62class ObjCProtocolDecl;
63struct PrintingPolicy;
64class RecordDecl;
65class SourceManager;
66class Stmt;
67class StoredDeclsMap;
68class TemplateDecl;
69class TemplateParameterList;
70class TranslationUnitDecl;
71class UsingDirectiveDecl;
72
73/// Captures the result of checking the availability of a
74/// declaration.
75enum AvailabilityResult {
76 AR_Available = 0,
77 AR_NotYetIntroduced,
78 AR_Deprecated,
79 AR_Unavailable
80};
81
82/// Decl - This represents one declaration (or definition), e.g. a variable,
83/// typedef, function, struct, etc.
84///
85/// Note: There are objects tacked on before the *beginning* of Decl
86/// (and its subclasses) in its Decl::operator new(). Proper alignment
87/// of all subclasses (not requiring more than the alignment of Decl) is
88/// asserted in DeclBase.cpp.
89class alignas(8) Decl {
90public:
91 /// Lists the kind of concrete classes of Decl.
92 enum Kind {
93#define DECL(DERIVED, BASE) DERIVED,
94#define ABSTRACT_DECL(DECL)
95#define DECL_RANGE(BASE, START, END) \
96 first##BASE = START, last##BASE = END,
97#define LAST_DECL_RANGE(BASE, START, END) \
98 first##BASE = START, last##BASE = END
99#include "clang/AST/DeclNodes.inc"
100 };
101
102 /// A placeholder type used to construct an empty shell of a
103 /// decl-derived type that will be filled in later (e.g., by some
104 /// deserialization method).
105 struct EmptyShell {};
106
107 /// IdentifierNamespace - The different namespaces in which
108 /// declarations may appear. According to C99 6.2.3, there are
109 /// four namespaces, labels, tags, members and ordinary
110 /// identifiers. C++ describes lookup completely differently:
111 /// certain lookups merely "ignore" certain kinds of declarations,
112 /// usually based on whether the declaration is of a type, etc.
113 ///
114 /// These are meant as bitmasks, so that searches in
115 /// C++ can look into the "tag" namespace during ordinary lookup.
116 ///
117 /// Decl currently provides 15 bits of IDNS bits.
118 enum IdentifierNamespace {
119 /// Labels, declared with 'x:' and referenced with 'goto x'.
120 IDNS_Label = 0x0001,
121
122 /// Tags, declared with 'struct foo;' and referenced with
123 /// 'struct foo'. All tags are also types. This is what
124 /// elaborated-type-specifiers look for in C.
125 /// This also contains names that conflict with tags in the
126 /// same scope but that are otherwise ordinary names (non-type
127 /// template parameters and indirect field declarations).
128 IDNS_Tag = 0x0002,
129
130 /// Types, declared with 'struct foo', typedefs, etc.
131 /// This is what elaborated-type-specifiers look for in C++,
132 /// but note that it's ill-formed to find a non-tag.
133 IDNS_Type = 0x0004,
134
135 /// Members, declared with object declarations within tag
136 /// definitions. In C, these can only be found by "qualified"
137 /// lookup in member expressions. In C++, they're found by
138 /// normal lookup.
139 IDNS_Member = 0x0008,
140
141 /// Namespaces, declared with 'namespace foo {}'.
142 /// Lookup for nested-name-specifiers find these.
143 IDNS_Namespace = 0x0010,
144
145 /// Ordinary names. In C, everything that's not a label, tag,
146 /// member, or function-local extern ends up here.
147 IDNS_Ordinary = 0x0020,
148
149 /// Objective C \@protocol.
150 IDNS_ObjCProtocol = 0x0040,
151
152 /// This declaration is a friend function. A friend function
153 /// declaration is always in this namespace but may also be in
154 /// IDNS_Ordinary if it was previously declared.
155 IDNS_OrdinaryFriend = 0x0080,
156
157 /// This declaration is a friend class. A friend class
158 /// declaration is always in this namespace but may also be in
159 /// IDNS_Tag|IDNS_Type if it was previously declared.
160 IDNS_TagFriend = 0x0100,
161
162 /// This declaration is a using declaration. A using declaration
163 /// *introduces* a number of other declarations into the current
164 /// scope, and those declarations use the IDNS of their targets,
165 /// but the actual using declarations go in this namespace.
166 IDNS_Using = 0x0200,
167
168 /// This declaration is a C++ operator declared in a non-class
169 /// context. All such operators are also in IDNS_Ordinary.
170 /// C++ lexical operator lookup looks for these.
171 IDNS_NonMemberOperator = 0x0400,
172
173 /// This declaration is a function-local extern declaration of a
174 /// variable or function. This may also be IDNS_Ordinary if it
175 /// has been declared outside any function. These act mostly like
176 /// invisible friend declarations, but are also visible to unqualified
177 /// lookup within the scope of the declaring function.
178 IDNS_LocalExtern = 0x0800,
179
180 /// This declaration is an OpenMP user defined reduction construction.
181 IDNS_OMPReduction = 0x1000,
182
183 /// This declaration is an OpenMP user defined mapper.
184 IDNS_OMPMapper = 0x2000,
185 };
186
187 /// ObjCDeclQualifier - 'Qualifiers' written next to the return and
188 /// parameter types in method declarations. Other than remembering
189 /// them and mangling them into the method's signature string, these
190 /// are ignored by the compiler; they are consumed by certain
191 /// remote-messaging frameworks.
192 ///
193 /// in, inout, and out are mutually exclusive and apply only to
194 /// method parameters. bycopy and byref are mutually exclusive and
195 /// apply only to method parameters (?). oneway applies only to
196 /// results. All of these expect their corresponding parameter to
197 /// have a particular type. None of this is currently enforced by
198 /// clang.
199 ///
200 /// This should be kept in sync with ObjCDeclSpec::ObjCDeclQualifier.
201 enum ObjCDeclQualifier {
202 OBJC_TQ_None = 0x0,
203 OBJC_TQ_In = 0x1,
204 OBJC_TQ_Inout = 0x2,
205 OBJC_TQ_Out = 0x4,
206 OBJC_TQ_Bycopy = 0x8,
207 OBJC_TQ_Byref = 0x10,
208 OBJC_TQ_Oneway = 0x20,
209
210 /// The nullability qualifier is set when the nullability of the
211 /// result or parameter was expressed via a context-sensitive
212 /// keyword.
213 OBJC_TQ_CSNullability = 0x40
214 };
215
216 /// The kind of ownership a declaration has, for visibility purposes.
217 /// This enumeration is designed such that higher values represent higher
218 /// levels of name hiding.
219 enum class ModuleOwnershipKind : unsigned {
220 /// This declaration is not owned by a module.
221 Unowned,
222
223 /// This declaration has an owning module, but is globally visible
224 /// (typically because its owning module is visible and we know that
225 /// modules cannot later become hidden in this compilation).
226 /// After serialization and deserialization, this will be converted
227 /// to VisibleWhenImported.
228 Visible,
229
230 /// This declaration has an owning module, and is visible when that
231 /// module is imported.
232 VisibleWhenImported,
233
234 /// This declaration has an owning module, but is only visible to
235 /// lookups that occur within that module.
236 ModulePrivate
237 };
238
239protected:
240 /// The next declaration within the same lexical
241 /// DeclContext. These pointers form the linked list that is
242 /// traversed via DeclContext's decls_begin()/decls_end().
243 ///
244 /// The extra two bits are used for the ModuleOwnershipKind.
245 llvm::PointerIntPair<Decl *, 2, ModuleOwnershipKind> NextInContextAndBits;
246
247private:
248 friend class DeclContext;
249
250 struct MultipleDC {
251 DeclContext *SemanticDC;
252 DeclContext *LexicalDC;
253 };
254
255 /// DeclCtx - Holds either a DeclContext* or a MultipleDC*.
256 /// For declarations that don't contain C++ scope specifiers, it contains
257 /// the DeclContext where the Decl was declared.
258 /// For declarations with C++ scope specifiers, it contains a MultipleDC*
259 /// with the context where it semantically belongs (SemanticDC) and the
260 /// context where it was lexically declared (LexicalDC).
261 /// e.g.:
262 ///
263 /// namespace A {
264 /// void f(); // SemanticDC == LexicalDC == 'namespace A'
265 /// }
266 /// void A::f(); // SemanticDC == namespace 'A'
267 /// // LexicalDC == global namespace
268 llvm::PointerUnion<DeclContext*, MultipleDC*> DeclCtx;
269
270 bool isInSemaDC() const { return DeclCtx.is<DeclContext*>(); }
271 bool isOutOfSemaDC() const { return DeclCtx.is<MultipleDC*>(); }
272
273 MultipleDC *getMultipleDC() const {
274 return DeclCtx.get<MultipleDC*>();
275 }
276
277 DeclContext *getSemanticDC() const {
278 return DeclCtx.get<DeclContext*>();
279 }
280
281 /// Loc - The location of this decl.
282 SourceLocation Loc;
283
284 /// DeclKind - This indicates which class this is.
285 unsigned DeclKind : 7;
286
287 /// InvalidDecl - This indicates a semantic error occurred.
288 unsigned InvalidDecl : 1;
289
290 /// HasAttrs - This indicates whether the decl has attributes or not.
291 unsigned HasAttrs : 1;
292
293 /// Implicit - Whether this declaration was implicitly generated by
294 /// the implementation rather than explicitly written by the user.
295 unsigned Implicit : 1;
296
297 /// Whether this declaration was "used", meaning that a definition is
298 /// required.
299 unsigned Used : 1;
300
301 /// Whether this declaration was "referenced".
302 /// The difference with 'Used' is whether the reference appears in a
303 /// evaluated context or not, e.g. functions used in uninstantiated templates
304 /// are regarded as "referenced" but not "used".
305 unsigned Referenced : 1;
306
307 /// Whether this declaration is a top-level declaration (function,
308 /// global variable, etc.) that is lexically inside an objc container
309 /// definition.
310 unsigned TopLevelDeclInObjCContainer : 1;
311
312 /// Whether statistic collection is enabled.
313 static bool StatisticsEnabled;
314
315protected:
316 friend class ASTDeclReader;
317 friend class ASTDeclWriter;
318 friend class ASTNodeImporter;
319 friend class ASTReader;
320 friend class CXXClassMemberWrapper;
321 friend class LinkageComputer;
322 template<typename decl_type> friend class Redeclarable;
323
324 /// Access - Used by C++ decls for the access specifier.
325 // NOTE: VC++ treats enums as signed, avoid using the AccessSpecifier enum
326 unsigned Access : 2;
327
328 /// Whether this declaration was loaded from an AST file.
329 unsigned FromASTFile : 1;
330
331 /// IdentifierNamespace - This specifies what IDNS_* namespace this lives in.
332 unsigned IdentifierNamespace : 14;
333
334 /// If 0, we have not computed the linkage of this declaration.
335 /// Otherwise, it is the linkage + 1.
336 mutable unsigned CacheValidAndLinkage : 3;
337
338 /// Allocate memory for a deserialized declaration.
339 ///
340 /// This routine must be used to allocate memory for any declaration that is
341 /// deserialized from a module file.
342 ///
343 /// \param Size The size of the allocated object.
344 /// \param Ctx The context in which we will allocate memory.
345 /// \param ID The global ID of the deserialized declaration.
346 /// \param Extra The amount of extra space to allocate after the object.
347 void *operator new(std::size_t Size, const ASTContext &Ctx, unsigned ID,
348 std::size_t Extra = 0);
349
350 /// Allocate memory for a non-deserialized declaration.
351 void *operator new(std::size_t Size, const ASTContext &Ctx,
352 DeclContext *Parent, std::size_t Extra = 0);
353
354private:
355 bool AccessDeclContextSanity() const;
356
357 /// Get the module ownership kind to use for a local lexical child of \p DC,
358 /// which may be either a local or (rarely) an imported declaration.
359 static ModuleOwnershipKind getModuleOwnershipKindForChildOf(DeclContext *DC) {
360 if (DC) {
361 auto *D = cast<Decl>(DC);
362 auto MOK = D->getModuleOwnershipKind();
363 if (MOK != ModuleOwnershipKind::Unowned &&
364 (!D->isFromASTFile() || D->hasLocalOwningModuleStorage()))
365 return MOK;
366 // If D is not local and we have no local module storage, then we don't
367 // need to track module ownership at all.
368 }
369 return ModuleOwnershipKind::Unowned;
370 }
371
372public:
373 Decl() = delete;
374 Decl(const Decl&) = delete;
375 Decl(Decl &&) = delete;
376 Decl &operator=(const Decl&) = delete;
377 Decl &operator=(Decl&&) = delete;
378
379protected:
380 Decl(Kind DK, DeclContext *DC, SourceLocation L)
381 : NextInContextAndBits(nullptr, getModuleOwnershipKindForChildOf(DC)),
382 DeclCtx(DC), Loc(L), DeclKind(DK), InvalidDecl(false), HasAttrs(false),
383 Implicit(false), Used(false), Referenced(false),
384 TopLevelDeclInObjCContainer(false), Access(AS_none), FromASTFile(0),
385 IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
386 CacheValidAndLinkage(0) {
387 if (StatisticsEnabled) add(DK);
388 }
389
390 Decl(Kind DK, EmptyShell Empty)
391 : DeclKind(DK), InvalidDecl(false), HasAttrs(false), Implicit(false),
392 Used(false), Referenced(false), TopLevelDeclInObjCContainer(false),
393 Access(AS_none), FromASTFile(0),
394 IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
395 CacheValidAndLinkage(0) {
396 if (StatisticsEnabled) add(DK);
397 }
398
399 virtual ~Decl();
400
401 /// Update a potentially out-of-date declaration.
402 void updateOutOfDate(IdentifierInfo &II) const;
403
404 Linkage getCachedLinkage() const {
405 return Linkage(CacheValidAndLinkage - 1);
406 }
407
408 void setCachedLinkage(Linkage L) const {
409 CacheValidAndLinkage = L + 1;
410 }
411
412 bool hasCachedLinkage() const {
413 return CacheValidAndLinkage;
414 }
415
416public:
417 /// Source range that this declaration covers.
418 virtual SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) {
419 return SourceRange(getLocation(), getLocation());
420 }
421
422 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
423 return getSourceRange().getBegin();
424 }
425
426 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
427 return getSourceRange().getEnd();
428 }
429
430 SourceLocation getLocation() const { return Loc; }
431 void setLocation(SourceLocation L) { Loc = L; }
432
433 Kind getKind() const { return static_cast<Kind>(DeclKind); }
434 const char *getDeclKindName() const;
435
436 Decl *getNextDeclInContext() { return NextInContextAndBits.getPointer(); }
437 const Decl *getNextDeclInContext() const {return NextInContextAndBits.getPointer();}
438
439 DeclContext *getDeclContext() {
440 if (isInSemaDC())
441 return getSemanticDC();
442 return getMultipleDC()->SemanticDC;
443 }
444 const DeclContext *getDeclContext() const {
445 return const_cast<Decl*>(this)->getDeclContext();
446 }
447
448 /// Find the innermost non-closure ancestor of this declaration,
449 /// walking up through blocks, lambdas, etc. If that ancestor is
450 /// not a code context (!isFunctionOrMethod()), returns null.
451 ///
452 /// A declaration may be its own non-closure context.
453 Decl *getNonClosureContext();
454 const Decl *getNonClosureContext() const {
455 return const_cast<Decl*>(this)->getNonClosureContext();
456 }
457
458 TranslationUnitDecl *getTranslationUnitDecl();
459 const TranslationUnitDecl *getTranslationUnitDecl() const {
460 return const_cast<Decl*>(this)->getTranslationUnitDecl();
461 }
462
463 bool isInAnonymousNamespace() const;
464
465 bool isInStdNamespace() const;
466
467 ASTContext &getASTContext() const LLVM_READONLY__attribute__((__pure__));
468
469 /// Helper to get the language options from the ASTContext.
470 /// Defined out of line to avoid depending on ASTContext.h.
471 const LangOptions &getLangOpts() const LLVM_READONLY__attribute__((__pure__));
472
473 void setAccess(AccessSpecifier AS) {
474 Access = AS;
475 assert(AccessDeclContextSanity())(static_cast <bool> (AccessDeclContextSanity()) ? void (
0) : __assert_fail ("AccessDeclContextSanity()", "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/include/clang/AST/DeclBase.h"
, 475, __extension__ __PRETTY_FUNCTION__))
;
476 }
477
478 AccessSpecifier getAccess() const {
479 assert(AccessDeclContextSanity())(static_cast <bool> (AccessDeclContextSanity()) ? void (
0) : __assert_fail ("AccessDeclContextSanity()", "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/include/clang/AST/DeclBase.h"
, 479, __extension__ __PRETTY_FUNCTION__))
;
480 return AccessSpecifier(Access);
481 }
482
483 /// Retrieve the access specifier for this declaration, even though
484 /// it may not yet have been properly set.
485 AccessSpecifier getAccessUnsafe() const {
486 return AccessSpecifier(Access);
487 }
488
489 bool hasAttrs() const { return HasAttrs; }
490
491 void setAttrs(const AttrVec& Attrs) {
492 return setAttrsImpl(Attrs, getASTContext());
493 }
494
495 AttrVec &getAttrs() {
496 return const_cast<AttrVec&>(const_cast<const Decl*>(this)->getAttrs());
497 }
498
499 const AttrVec &getAttrs() const;
500 void dropAttrs();
501 void addAttr(Attr *A);
502
503 using attr_iterator = AttrVec::const_iterator;
504 using attr_range = llvm::iterator_range<attr_iterator>;
505
506 attr_range attrs() const {
507 return attr_range(attr_begin(), attr_end());
508 }
509
510 attr_iterator attr_begin() const {
511 return hasAttrs() ? getAttrs().begin() : nullptr;
512 }
513 attr_iterator attr_end() const {
514 return hasAttrs() ? getAttrs().end() : nullptr;
515 }
516
517 template <typename T>
518 void dropAttr() {
519 if (!HasAttrs) return;
520
521 AttrVec &Vec = getAttrs();
522 llvm::erase_if(Vec, [](Attr *A) { return isa<T>(A); });
523
524 if (Vec.empty())
525 HasAttrs = false;
526 }
527
528 template <typename T>
529 llvm::iterator_range<specific_attr_iterator<T>> specific_attrs() const {
530 return llvm::make_range(specific_attr_begin<T>(), specific_attr_end<T>());
531 }
532
533 template <typename T>
534 specific_attr_iterator<T> specific_attr_begin() const {
535 return specific_attr_iterator<T>(attr_begin());
536 }
537
538 template <typename T>
539 specific_attr_iterator<T> specific_attr_end() const {
540 return specific_attr_iterator<T>(attr_end());
541 }
542
543 template<typename T> T *getAttr() const {
544 return hasAttrs() ? getSpecificAttr<T>(getAttrs()) : nullptr;
545 }
546
547 template<typename T> bool hasAttr() const {
548 return hasAttrs() && hasSpecificAttr<T>(getAttrs());
549 }
550
551 /// getMaxAlignment - return the maximum alignment specified by attributes
552 /// on this decl, 0 if there are none.
553 unsigned getMaxAlignment() const;
554
555 /// setInvalidDecl - Indicates the Decl had a semantic error. This
556 /// allows for graceful error recovery.
557 void setInvalidDecl(bool Invalid = true);
558 bool isInvalidDecl() const { return (bool) InvalidDecl; }
559
560 /// isImplicit - Indicates whether the declaration was implicitly
561 /// generated by the implementation. If false, this declaration
562 /// was written explicitly in the source code.
563 bool isImplicit() const { return Implicit; }
564 void setImplicit(bool I = true) { Implicit = I; }
565
566 /// Whether *any* (re-)declaration of the entity was used, meaning that
567 /// a definition is required.
568 ///
569 /// \param CheckUsedAttr When true, also consider the "used" attribute
570 /// (in addition to the "used" bit set by \c setUsed()) when determining
571 /// whether the function is used.
572 bool isUsed(bool CheckUsedAttr = true) const;
573
574 /// Set whether the declaration is used, in the sense of odr-use.
575 ///
576 /// This should only be used immediately after creating a declaration.
577 /// It intentionally doesn't notify any listeners.
578 void setIsUsed() { getCanonicalDecl()->Used = true; }
579
580 /// Mark the declaration used, in the sense of odr-use.
581 ///
582 /// This notifies any mutation listeners in addition to setting a bit
583 /// indicating the declaration is used.
584 void markUsed(ASTContext &C);
585
586 /// Whether any declaration of this entity was referenced.
587 bool isReferenced() const;
588
589 /// Whether this declaration was referenced. This should not be relied
590 /// upon for anything other than debugging.
591 bool isThisDeclarationReferenced() const { return Referenced; }
592
593 void setReferenced(bool R = true) { Referenced = R; }
594
595 /// Whether this declaration is a top-level declaration (function,
596 /// global variable, etc.) that is lexically inside an objc container
597 /// definition.
598 bool isTopLevelDeclInObjCContainer() const {
599 return TopLevelDeclInObjCContainer;
600 }
601
602 void setTopLevelDeclInObjCContainer(bool V = true) {
603 TopLevelDeclInObjCContainer = V;
604 }
605
606 /// Looks on this and related declarations for an applicable
607 /// external source symbol attribute.
608 ExternalSourceSymbolAttr *getExternalSourceSymbolAttr() const;
609
610 /// Whether this declaration was marked as being private to the
611 /// module in which it was defined.
612 bool isModulePrivate() const {
613 return getModuleOwnershipKind() == ModuleOwnershipKind::ModulePrivate;
614 }
615
616 /// Return true if this declaration has an attribute which acts as
617 /// definition of the entity, such as 'alias' or 'ifunc'.
618 bool hasDefiningAttr() const;
619
620 /// Return this declaration's defining attribute if it has one.
621 const Attr *getDefiningAttr() const;
622
623protected:
624 /// Specify that this declaration was marked as being private
625 /// to the module in which it was defined.
626 void setModulePrivate() {
627 // The module-private specifier has no effect on unowned declarations.
628 // FIXME: We should track this in some way for source fidelity.
629 if (getModuleOwnershipKind() == ModuleOwnershipKind::Unowned)
630 return;
631 setModuleOwnershipKind(ModuleOwnershipKind::ModulePrivate);
632 }
633
634public:
635 /// Set the FromASTFile flag. This indicates that this declaration
636 /// was deserialized and not parsed from source code and enables
637 /// features such as module ownership information.
638 void setFromASTFile() {
639 FromASTFile = true;
640 }
641
642 /// Set the owning module ID. This may only be called for
643 /// deserialized Decls.
644 void setOwningModuleID(unsigned ID) {
645 assert(isFromASTFile() && "Only works on a deserialized declaration")(static_cast <bool> (isFromASTFile() && "Only works on a deserialized declaration"
) ? void (0) : __assert_fail ("isFromASTFile() && \"Only works on a deserialized declaration\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/include/clang/AST/DeclBase.h"
, 645, __extension__ __PRETTY_FUNCTION__))
;
646 *((unsigned*)this - 2) = ID;
647 }
648
649public:
650 /// Determine the availability of the given declaration.
651 ///
652 /// This routine will determine the most restrictive availability of
653 /// the given declaration (e.g., preferring 'unavailable' to
654 /// 'deprecated').
655 ///
656 /// \param Message If non-NULL and the result is not \c
657 /// AR_Available, will be set to a (possibly empty) message
658 /// describing why the declaration has not been introduced, is
659 /// deprecated, or is unavailable.
660 ///
661 /// \param EnclosingVersion The version to compare with. If empty, assume the
662 /// deployment target version.
663 ///
664 /// \param RealizedPlatform If non-NULL and the availability result is found
665 /// in an available attribute it will set to the platform which is written in
666 /// the available attribute.
667 AvailabilityResult
668 getAvailability(std::string *Message = nullptr,
669 VersionTuple EnclosingVersion = VersionTuple(),
670 StringRef *RealizedPlatform = nullptr) const;
671
672 /// Retrieve the version of the target platform in which this
673 /// declaration was introduced.
674 ///
675 /// \returns An empty version tuple if this declaration has no 'introduced'
676 /// availability attributes, or the version tuple that's specified in the
677 /// attribute otherwise.
678 VersionTuple getVersionIntroduced() const;
679
680 /// Determine whether this declaration is marked 'deprecated'.
681 ///
682 /// \param Message If non-NULL and the declaration is deprecated,
683 /// this will be set to the message describing why the declaration
684 /// was deprecated (which may be empty).
685 bool isDeprecated(std::string *Message = nullptr) const {
686 return getAvailability(Message) == AR_Deprecated;
687 }
688
689 /// Determine whether this declaration is marked 'unavailable'.
690 ///
691 /// \param Message If non-NULL and the declaration is unavailable,
692 /// this will be set to the message describing why the declaration
693 /// was made unavailable (which may be empty).
694 bool isUnavailable(std::string *Message = nullptr) const {
695 return getAvailability(Message) == AR_Unavailable;
696 }
697
698 /// Determine whether this is a weak-imported symbol.
699 ///
700 /// Weak-imported symbols are typically marked with the
701 /// 'weak_import' attribute, but may also be marked with an
702 /// 'availability' attribute where we're targing a platform prior to
703 /// the introduction of this feature.
704 bool isWeakImported() const;
705
706 /// Determines whether this symbol can be weak-imported,
707 /// e.g., whether it would be well-formed to add the weak_import
708 /// attribute.
709 ///
710 /// \param IsDefinition Set to \c true to indicate that this
711 /// declaration cannot be weak-imported because it has a definition.
712 bool canBeWeakImported(bool &IsDefinition) const;
713
714 /// Determine whether this declaration came from an AST file (such as
715 /// a precompiled header or module) rather than having been parsed.
716 bool isFromASTFile() const { return FromASTFile; }
717
718 /// Retrieve the global declaration ID associated with this
719 /// declaration, which specifies where this Decl was loaded from.
720 unsigned getGlobalID() const {
721 if (isFromASTFile())
722 return *((const unsigned*)this - 1);
723 return 0;
724 }
725
726 /// Retrieve the global ID of the module that owns this particular
727 /// declaration.
728 unsigned getOwningModuleID() const {
729 if (isFromASTFile())
730 return *((const unsigned*)this - 2);
731 return 0;
732 }
733
734private:
735 Module *getOwningModuleSlow() const;
736
737protected:
738 bool hasLocalOwningModuleStorage() const;
739
740public:
741 /// Get the imported owning module, if this decl is from an imported
742 /// (non-local) module.
743 Module *getImportedOwningModule() const {
744 if (!isFromASTFile() || !hasOwningModule())
745 return nullptr;
746
747 return getOwningModuleSlow();
748 }
749
750 /// Get the local owning module, if known. Returns nullptr if owner is
751 /// not yet known or declaration is not from a module.
752 Module *getLocalOwningModule() const {
753 if (isFromASTFile() || !hasOwningModule())
754 return nullptr;
755
756 assert(hasLocalOwningModuleStorage() &&(static_cast <bool> (hasLocalOwningModuleStorage() &&
"owned local decl but no local module storage") ? void (0) :
__assert_fail ("hasLocalOwningModuleStorage() && \"owned local decl but no local module storage\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/include/clang/AST/DeclBase.h"
, 757, __extension__ __PRETTY_FUNCTION__))
757 "owned local decl but no local module storage")(static_cast <bool> (hasLocalOwningModuleStorage() &&
"owned local decl but no local module storage") ? void (0) :
__assert_fail ("hasLocalOwningModuleStorage() && \"owned local decl but no local module storage\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/include/clang/AST/DeclBase.h"
, 757, __extension__ __PRETTY_FUNCTION__))
;
758 return reinterpret_cast<Module *const *>(this)[-1];
759 }
760 void setLocalOwningModule(Module *M) {
761 assert(!isFromASTFile() && hasOwningModule() &&(static_cast <bool> (!isFromASTFile() && hasOwningModule
() && hasLocalOwningModuleStorage() && "should not have a cached owning module"
) ? void (0) : __assert_fail ("!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage() && \"should not have a cached owning module\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/include/clang/AST/DeclBase.h"
, 763, __extension__ __PRETTY_FUNCTION__))
762 hasLocalOwningModuleStorage() &&(static_cast <bool> (!isFromASTFile() && hasOwningModule
() && hasLocalOwningModuleStorage() && "should not have a cached owning module"
) ? void (0) : __assert_fail ("!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage() && \"should not have a cached owning module\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/include/clang/AST/DeclBase.h"
, 763, __extension__ __PRETTY_FUNCTION__))
763 "should not have a cached owning module")(static_cast <bool> (!isFromASTFile() && hasOwningModule
() && hasLocalOwningModuleStorage() && "should not have a cached owning module"
) ? void (0) : __assert_fail ("!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage() && \"should not have a cached owning module\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/include/clang/AST/DeclBase.h"
, 763, __extension__ __PRETTY_FUNCTION__))
;
764 reinterpret_cast<Module **>(this)[-1] = M;
765 }
766
767 /// Is this declaration owned by some module?
768 bool hasOwningModule() const {
769 return getModuleOwnershipKind() != ModuleOwnershipKind::Unowned;
770 }
771
772 /// Get the module that owns this declaration (for visibility purposes).
773 Module *getOwningModule() const {
774 return isFromASTFile() ? getImportedOwningModule() : getLocalOwningModule();
775 }
776
777 /// Get the module that owns this declaration for linkage purposes.
778 /// There only ever is such a module under the C++ Modules TS.
779 ///
780 /// \param IgnoreLinkage Ignore the linkage of the entity; assume that
781 /// all declarations in a global module fragment are unowned.
782 Module *getOwningModuleForLinkage(bool IgnoreLinkage = false) const;
783
784 /// Determine whether this declaration is definitely visible to name lookup,
785 /// independent of whether the owning module is visible.
786 /// Note: The declaration may be visible even if this returns \c false if the
787 /// owning module is visible within the query context. This is a low-level
788 /// helper function; most code should be calling Sema::isVisible() instead.
789 bool isUnconditionallyVisible() const {
790 return (int)getModuleOwnershipKind() <= (int)ModuleOwnershipKind::Visible;
791 }
792
793 /// Set that this declaration is globally visible, even if it came from a
794 /// module that is not visible.
795 void setVisibleDespiteOwningModule() {
796 if (!isUnconditionallyVisible())
797 setModuleOwnershipKind(ModuleOwnershipKind::Visible);
798 }
799
800 /// Get the kind of module ownership for this declaration.
801 ModuleOwnershipKind getModuleOwnershipKind() const {
802 return NextInContextAndBits.getInt();
803 }
804
805 /// Set whether this declaration is hidden from name lookup.
806 void setModuleOwnershipKind(ModuleOwnershipKind MOK) {
807 assert(!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned &&(static_cast <bool> (!(getModuleOwnershipKind() == ModuleOwnershipKind
::Unowned && MOK != ModuleOwnershipKind::Unowned &&
!isFromASTFile() && !hasLocalOwningModuleStorage()) &&
"no storage available for owning module for this declaration"
) ? void (0) : __assert_fail ("!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && \"no storage available for owning module for this declaration\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/include/clang/AST/DeclBase.h"
, 810, __extension__ __PRETTY_FUNCTION__))
808 MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() &&(static_cast <bool> (!(getModuleOwnershipKind() == ModuleOwnershipKind
::Unowned && MOK != ModuleOwnershipKind::Unowned &&
!isFromASTFile() && !hasLocalOwningModuleStorage()) &&
"no storage available for owning module for this declaration"
) ? void (0) : __assert_fail ("!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && \"no storage available for owning module for this declaration\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/include/clang/AST/DeclBase.h"
, 810, __extension__ __PRETTY_FUNCTION__))
809 !hasLocalOwningModuleStorage()) &&(static_cast <bool> (!(getModuleOwnershipKind() == ModuleOwnershipKind
::Unowned && MOK != ModuleOwnershipKind::Unowned &&
!isFromASTFile() && !hasLocalOwningModuleStorage()) &&
"no storage available for owning module for this declaration"
) ? void (0) : __assert_fail ("!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && \"no storage available for owning module for this declaration\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/include/clang/AST/DeclBase.h"
, 810, __extension__ __PRETTY_FUNCTION__))
810 "no storage available for owning module for this declaration")(static_cast <bool> (!(getModuleOwnershipKind() == ModuleOwnershipKind
::Unowned && MOK != ModuleOwnershipKind::Unowned &&
!isFromASTFile() && !hasLocalOwningModuleStorage()) &&
"no storage available for owning module for this declaration"
) ? void (0) : __assert_fail ("!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && \"no storage available for owning module for this declaration\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/include/clang/AST/DeclBase.h"
, 810, __extension__ __PRETTY_FUNCTION__))
;
811 NextInContextAndBits.setInt(MOK);
812 }
813
814 unsigned getIdentifierNamespace() const {
815 return IdentifierNamespace;
816 }
817
818 bool isInIdentifierNamespace(unsigned NS) const {
819 return getIdentifierNamespace() & NS;
820 }
821
822 static unsigned getIdentifierNamespaceForKind(Kind DK);
823
824 bool hasTagIdentifierNamespace() const {
825 return isTagIdentifierNamespace(getIdentifierNamespace());
826 }
827
828 static bool isTagIdentifierNamespace(unsigned NS) {
829 // TagDecls have Tag and Type set and may also have TagFriend.
830 return (NS & ~IDNS_TagFriend) == (IDNS_Tag | IDNS_Type);
831 }
832
833 /// getLexicalDeclContext - The declaration context where this Decl was
834 /// lexically declared (LexicalDC). May be different from
835 /// getDeclContext() (SemanticDC).
836 /// e.g.:
837 ///
838 /// namespace A {
839 /// void f(); // SemanticDC == LexicalDC == 'namespace A'
840 /// }
841 /// void A::f(); // SemanticDC == namespace 'A'
842 /// // LexicalDC == global namespace
843 DeclContext *getLexicalDeclContext() {
844 if (isInSemaDC())
845 return getSemanticDC();
846 return getMultipleDC()->LexicalDC;
847 }
848 const DeclContext *getLexicalDeclContext() const {
849 return const_cast<Decl*>(this)->getLexicalDeclContext();
850 }
851
852 /// Determine whether this declaration is declared out of line (outside its
853 /// semantic context).
854 virtual bool isOutOfLine() const;
855
856 /// setDeclContext - Set both the semantic and lexical DeclContext
857 /// to DC.
858 void setDeclContext(DeclContext *DC);
859
860 void setLexicalDeclContext(DeclContext *DC);
861
862 /// Determine whether this declaration is a templated entity (whether it is
863 // within the scope of a template parameter).
864 bool isTemplated() const;
865
866 /// Determine the number of levels of template parameter surrounding this
867 /// declaration.
868 unsigned getTemplateDepth() const;
869
870 /// isDefinedOutsideFunctionOrMethod - This predicate returns true if this
871 /// scoped decl is defined outside the current function or method. This is
872 /// roughly global variables and functions, but also handles enums (which
873 /// could be defined inside or outside a function etc).
874 bool isDefinedOutsideFunctionOrMethod() const {
875 return getParentFunctionOrMethod() == nullptr;
876 }
877
878 /// Determine whether a substitution into this declaration would occur as
879 /// part of a substitution into a dependent local scope. Such a substitution
880 /// transitively substitutes into all constructs nested within this
881 /// declaration.
882 ///
883 /// This recognizes non-defining declarations as well as members of local
884 /// classes and lambdas:
885 /// \code
886 /// template<typename T> void foo() { void bar(); }
887 /// template<typename T> void foo2() { class ABC { void bar(); }; }
888 /// template<typename T> inline int x = [](){ return 0; }();
889 /// \endcode
890 bool isInLocalScopeForInstantiation() const;
891
892 /// If this decl is defined inside a function/method/block it returns
893 /// the corresponding DeclContext, otherwise it returns null.
894 const DeclContext *getParentFunctionOrMethod() const;
895 DeclContext *getParentFunctionOrMethod() {
896 return const_cast<DeclContext*>(
897 const_cast<const Decl*>(this)->getParentFunctionOrMethod());
898 }
899
900 /// Retrieves the "canonical" declaration of the given declaration.
901 virtual Decl *getCanonicalDecl() { return this; }
902 const Decl *getCanonicalDecl() const {
903 return const_cast<Decl*>(this)->getCanonicalDecl();
904 }
905
906 /// Whether this particular Decl is a canonical one.
907 bool isCanonicalDecl() const { return getCanonicalDecl() == this; }
908
909protected:
910 /// Returns the next redeclaration or itself if this is the only decl.
911 ///
912 /// Decl subclasses that can be redeclared should override this method so that
913 /// Decl::redecl_iterator can iterate over them.
914 virtual Decl *getNextRedeclarationImpl() { return this; }
915
916 /// Implementation of getPreviousDecl(), to be overridden by any
917 /// subclass that has a redeclaration chain.
918 virtual Decl *getPreviousDeclImpl() { return nullptr; }
919
920 /// Implementation of getMostRecentDecl(), to be overridden by any
921 /// subclass that has a redeclaration chain.
922 virtual Decl *getMostRecentDeclImpl() { return this; }
923
924public:
925 /// Iterates through all the redeclarations of the same decl.
926 class redecl_iterator {
927 /// Current - The current declaration.
928 Decl *Current = nullptr;
929 Decl *Starter;
930
931 public:
932 using value_type = Decl *;
933 using reference = const value_type &;
934 using pointer = const value_type *;
935 using iterator_category = std::forward_iterator_tag;
936 using difference_type = std::ptrdiff_t;
937
938 redecl_iterator() = default;
939 explicit redecl_iterator(Decl *C) : Current(C), Starter(C) {}
940
941 reference operator*() const { return Current; }
942 value_type operator->() const { return Current; }
943
944 redecl_iterator& operator++() {
945 assert(Current && "Advancing while iterator has reached end")(static_cast <bool> (Current && "Advancing while iterator has reached end"
) ? void (0) : __assert_fail ("Current && \"Advancing while iterator has reached end\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/include/clang/AST/DeclBase.h"
, 945, __extension__ __PRETTY_FUNCTION__))
;
946 // Get either previous decl or latest decl.
947 Decl *Next = Current->getNextRedeclarationImpl();
948 assert(Next && "Should return next redeclaration or itself, never null!")(static_cast <bool> (Next && "Should return next redeclaration or itself, never null!"
) ? void (0) : __assert_fail ("Next && \"Should return next redeclaration or itself, never null!\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/include/clang/AST/DeclBase.h"
, 948, __extension__ __PRETTY_FUNCTION__))
;
949 Current = (Next != Starter) ? Next : nullptr;
950 return *this;
951 }
952
953 redecl_iterator operator++(int) {
954 redecl_iterator tmp(*this);
955 ++(*this);
956 return tmp;
957 }
958
959 friend bool operator==(redecl_iterator x, redecl_iterator y) {
960 return x.Current == y.Current;
961 }
962
963 friend bool operator!=(redecl_iterator x, redecl_iterator y) {
964 return x.Current != y.Current;
965 }
966 };
967
968 using redecl_range = llvm::iterator_range<redecl_iterator>;
969
970 /// Returns an iterator range for all the redeclarations of the same
971 /// decl. It will iterate at least once (when this decl is the only one).
972 redecl_range redecls() const {
973 return redecl_range(redecls_begin(), redecls_end());
974 }
975
976 redecl_iterator redecls_begin() const {
977 return redecl_iterator(const_cast<Decl *>(this));
978 }
979
980 redecl_iterator redecls_end() const { return redecl_iterator(); }
981
982 /// Retrieve the previous declaration that declares the same entity
983 /// as this declaration, or NULL if there is no previous declaration.
984 Decl *getPreviousDecl() { return getPreviousDeclImpl(); }
985
986 /// Retrieve the previous declaration that declares the same entity
987 /// as this declaration, or NULL if there is no previous declaration.
988 const Decl *getPreviousDecl() const {
989 return const_cast<Decl *>(this)->getPreviousDeclImpl();
990 }
991
992 /// True if this is the first declaration in its redeclaration chain.
993 bool isFirstDecl() const {
994 return getPreviousDecl() == nullptr;
995 }
996
997 /// Retrieve the most recent declaration that declares the same entity
998 /// as this declaration (which may be this declaration).
999 Decl *getMostRecentDecl() { return getMostRecentDeclImpl(); }
1000
1001 /// Retrieve the most recent declaration that declares the same entity
1002 /// as this declaration (which may be this declaration).
1003 const Decl *getMostRecentDecl() const {
1004 return const_cast<Decl *>(this)->getMostRecentDeclImpl();
1005 }
1006
1007 /// getBody - If this Decl represents a declaration for a body of code,
1008 /// such as a function or method definition, this method returns the
1009 /// top-level Stmt* of that body. Otherwise this method returns null.
1010 virtual Stmt* getBody() const { return nullptr; }
1011
1012 /// Returns true if this \c Decl represents a declaration for a body of
1013 /// code, such as a function or method definition.
1014 /// Note that \c hasBody can also return true if any redeclaration of this
1015 /// \c Decl represents a declaration for a body of code.
1016 virtual bool hasBody() const { return getBody() != nullptr; }
1017
1018 /// getBodyRBrace - Gets the right brace of the body, if a body exists.
1019 /// This works whether the body is a CompoundStmt or a CXXTryStmt.
1020 SourceLocation getBodyRBrace() const;
1021
1022 // global temp stats (until we have a per-module visitor)
1023 static void add(Kind k);
1024 static void EnableStatistics();
1025 static void PrintStats();
1026
1027 /// isTemplateParameter - Determines whether this declaration is a
1028 /// template parameter.
1029 bool isTemplateParameter() const;
1030
1031 /// isTemplateParameter - Determines whether this declaration is a
1032 /// template parameter pack.
1033 bool isTemplateParameterPack() const;
1034
1035 /// Whether this declaration is a parameter pack.
1036 bool isParameterPack() const;
1037
1038 /// returns true if this declaration is a template
1039 bool isTemplateDecl() const;
1040
1041 /// Whether this declaration is a function or function template.
1042 bool isFunctionOrFunctionTemplate() const {
1043 return (DeclKind >= Decl::firstFunction &&
1044 DeclKind <= Decl::lastFunction) ||
1045 DeclKind == FunctionTemplate;
1046 }
1047
1048 /// If this is a declaration that describes some template, this
1049 /// method returns that template declaration.
1050 ///
1051 /// Note that this returns nullptr for partial specializations, because they
1052 /// are not modeled as TemplateDecls. Use getDescribedTemplateParams to handle
1053 /// those cases.
1054 TemplateDecl *getDescribedTemplate() const;
1055
1056 /// If this is a declaration that describes some template or partial
1057 /// specialization, this returns the corresponding template parameter list.
1058 const TemplateParameterList *getDescribedTemplateParams() const;
1059
1060 /// Returns the function itself, or the templated function if this is a
1061 /// function template.
1062 FunctionDecl *getAsFunction() LLVM_READONLY__attribute__((__pure__));
1063
1064 const FunctionDecl *getAsFunction() const {
1065 return const_cast<Decl *>(this)->getAsFunction();
1066 }
1067
1068 /// Changes the namespace of this declaration to reflect that it's
1069 /// a function-local extern declaration.
1070 ///
1071 /// These declarations appear in the lexical context of the extern
1072 /// declaration, but in the semantic context of the enclosing namespace
1073 /// scope.
1074 void setLocalExternDecl() {
1075 Decl *Prev = getPreviousDecl();
1076 IdentifierNamespace &= ~IDNS_Ordinary;
1077
1078 // It's OK for the declaration to still have the "invisible friend" flag or
1079 // the "conflicts with tag declarations in this scope" flag for the outer
1080 // scope.
1081 assert((IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag)) == 0 &&(static_cast <bool> ((IdentifierNamespace & ~(IDNS_OrdinaryFriend
| IDNS_Tag)) == 0 && "namespace is not ordinary") ? void
(0) : __assert_fail ("(IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag)) == 0 && \"namespace is not ordinary\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/include/clang/AST/DeclBase.h"
, 1082, __extension__ __PRETTY_FUNCTION__))
1082 "namespace is not ordinary")(static_cast <bool> ((IdentifierNamespace & ~(IDNS_OrdinaryFriend
| IDNS_Tag)) == 0 && "namespace is not ordinary") ? void
(0) : __assert_fail ("(IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag)) == 0 && \"namespace is not ordinary\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/include/clang/AST/DeclBase.h"
, 1082, __extension__ __PRETTY_FUNCTION__))
;
1083
1084 IdentifierNamespace |= IDNS_LocalExtern;
1085 if (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary)
1086 IdentifierNamespace |= IDNS_Ordinary;
1087 }
1088
1089 /// Determine whether this is a block-scope declaration with linkage.
1090 /// This will either be a local variable declaration declared 'extern', or a
1091 /// local function declaration.
1092 bool isLocalExternDecl() {
1093 return IdentifierNamespace & IDNS_LocalExtern;
1094 }
1095
1096 /// Changes the namespace of this declaration to reflect that it's
1097 /// the object of a friend declaration.
1098 ///
1099 /// These declarations appear in the lexical context of the friending
1100 /// class, but in the semantic context of the actual entity. This property
1101 /// applies only to a specific decl object; other redeclarations of the
1102 /// same entity may not (and probably don't) share this property.
1103 void setObjectOfFriendDecl(bool PerformFriendInjection = false) {
1104 unsigned OldNS = IdentifierNamespace;
1105 assert((OldNS & (IDNS_Tag | IDNS_Ordinary |(static_cast <bool> ((OldNS & (IDNS_Tag | IDNS_Ordinary
| IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator
)) && "namespace includes neither ordinary nor tag") ?
void (0) : __assert_fail ("(OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes neither ordinary nor tag\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/include/clang/AST/DeclBase.h"
, 1108, __extension__ __PRETTY_FUNCTION__))
1106 IDNS_TagFriend | IDNS_OrdinaryFriend |(static_cast <bool> ((OldNS & (IDNS_Tag | IDNS_Ordinary
| IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator
)) && "namespace includes neither ordinary nor tag") ?
void (0) : __assert_fail ("(OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes neither ordinary nor tag\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/include/clang/AST/DeclBase.h"
, 1108, __extension__ __PRETTY_FUNCTION__))
1107 IDNS_LocalExtern | IDNS_NonMemberOperator)) &&(static_cast <bool> ((OldNS & (IDNS_Tag | IDNS_Ordinary
| IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator
)) && "namespace includes neither ordinary nor tag") ?
void (0) : __assert_fail ("(OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes neither ordinary nor tag\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/include/clang/AST/DeclBase.h"
, 1108, __extension__ __PRETTY_FUNCTION__))
1108 "namespace includes neither ordinary nor tag")(static_cast <bool> ((OldNS & (IDNS_Tag | IDNS_Ordinary
| IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator
)) && "namespace includes neither ordinary nor tag") ?
void (0) : __assert_fail ("(OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes neither ordinary nor tag\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/include/clang/AST/DeclBase.h"
, 1108, __extension__ __PRETTY_FUNCTION__))
;
1109 assert(!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type |(static_cast <bool> (!(OldNS & ~(IDNS_Tag | IDNS_Ordinary
| IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern
| IDNS_NonMemberOperator)) && "namespace includes other than ordinary or tag"
) ? void (0) : __assert_fail ("!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes other than ordinary or tag\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/include/clang/AST/DeclBase.h"
, 1112, __extension__ __PRETTY_FUNCTION__))
1110 IDNS_TagFriend | IDNS_OrdinaryFriend |(static_cast <bool> (!(OldNS & ~(IDNS_Tag | IDNS_Ordinary
| IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern
| IDNS_NonMemberOperator)) && "namespace includes other than ordinary or tag"
) ? void (0) : __assert_fail ("!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes other than ordinary or tag\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/include/clang/AST/DeclBase.h"
, 1112, __extension__ __PRETTY_FUNCTION__))
1111 IDNS_LocalExtern | IDNS_NonMemberOperator)) &&(static_cast <bool> (!(OldNS & ~(IDNS_Tag | IDNS_Ordinary
| IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern
| IDNS_NonMemberOperator)) && "namespace includes other than ordinary or tag"
) ? void (0) : __assert_fail ("!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes other than ordinary or tag\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/include/clang/AST/DeclBase.h"
, 1112, __extension__ __PRETTY_FUNCTION__))
1112 "namespace includes other than ordinary or tag")(static_cast <bool> (!(OldNS & ~(IDNS_Tag | IDNS_Ordinary
| IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern
| IDNS_NonMemberOperator)) && "namespace includes other than ordinary or tag"
) ? void (0) : __assert_fail ("!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes other than ordinary or tag\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/include/clang/AST/DeclBase.h"
, 1112, __extension__ __PRETTY_FUNCTION__))
;
1113
1114 Decl *Prev = getPreviousDecl();
1115 IdentifierNamespace &= ~(IDNS_Ordinary | IDNS_Tag | IDNS_Type);
1116
1117 if (OldNS & (IDNS_Tag | IDNS_TagFriend)) {
1118 IdentifierNamespace |= IDNS_TagFriend;
1119 if (PerformFriendInjection ||
1120 (Prev && Prev->getIdentifierNamespace() & IDNS_Tag))
1121 IdentifierNamespace |= IDNS_Tag | IDNS_Type;
1122 }
1123
1124 if (OldNS & (IDNS_Ordinary | IDNS_OrdinaryFriend |
1125 IDNS_LocalExtern | IDNS_NonMemberOperator)) {
1126 IdentifierNamespace |= IDNS_OrdinaryFriend;
1127 if (PerformFriendInjection ||
1128 (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary))
1129 IdentifierNamespace |= IDNS_Ordinary;
1130 }
1131 }
1132
1133 enum FriendObjectKind {
1134 FOK_None, ///< Not a friend object.
1135 FOK_Declared, ///< A friend of a previously-declared entity.
1136 FOK_Undeclared ///< A friend of a previously-undeclared entity.
1137 };
1138
1139 /// Determines whether this declaration is the object of a
1140 /// friend declaration and, if so, what kind.
1141 ///
1142 /// There is currently no direct way to find the associated FriendDecl.
1143 FriendObjectKind getFriendObjectKind() const {
1144 unsigned mask =
1145 (IdentifierNamespace & (IDNS_TagFriend | IDNS_OrdinaryFriend));
1146 if (!mask) return FOK_None;
17
Assuming 'mask' is not equal to 0, which participates in a condition later
1147 return (IdentifierNamespace & (IDNS_Tag | IDNS_Ordinary) ? FOK_Declared
18
Taking false branch
19
Assuming the condition is false
20
'?' condition is false
21
Returning the value 2, which participates in a condition later
1148 : FOK_Undeclared);
1149 }
1150
1151 /// Specifies that this declaration is a C++ overloaded non-member.
1152 void setNonMemberOperator() {
1153 assert(getKind() == Function || getKind() == FunctionTemplate)(static_cast <bool> (getKind() == Function || getKind()
== FunctionTemplate) ? void (0) : __assert_fail ("getKind() == Function || getKind() == FunctionTemplate"
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/include/clang/AST/DeclBase.h"
, 1153, __extension__ __PRETTY_FUNCTION__))
;
1154 assert((IdentifierNamespace & IDNS_Ordinary) &&(static_cast <bool> ((IdentifierNamespace & IDNS_Ordinary
) && "visible non-member operators should be in ordinary namespace"
) ? void (0) : __assert_fail ("(IdentifierNamespace & IDNS_Ordinary) && \"visible non-member operators should be in ordinary namespace\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/include/clang/AST/DeclBase.h"
, 1155, __extension__ __PRETTY_FUNCTION__))
1155 "visible non-member operators should be in ordinary namespace")(static_cast <bool> ((IdentifierNamespace & IDNS_Ordinary
) && "visible non-member operators should be in ordinary namespace"
) ? void (0) : __assert_fail ("(IdentifierNamespace & IDNS_Ordinary) && \"visible non-member operators should be in ordinary namespace\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/include/clang/AST/DeclBase.h"
, 1155, __extension__ __PRETTY_FUNCTION__))
;
1156 IdentifierNamespace |= IDNS_NonMemberOperator;
1157 }
1158
1159 static bool classofKind(Kind K) { return true; }
1160 static DeclContext *castToDeclContext(const Decl *);
1161 static Decl *castFromDeclContext(const DeclContext *);
1162
1163 void print(raw_ostream &Out, unsigned Indentation = 0,
1164 bool PrintInstantiation = false) const;
1165 void print(raw_ostream &Out, const PrintingPolicy &Policy,
1166 unsigned Indentation = 0, bool PrintInstantiation = false) const;
1167 static void printGroup(Decl** Begin, unsigned NumDecls,
1168 raw_ostream &Out, const PrintingPolicy &Policy,
1169 unsigned Indentation = 0);
1170
1171 // Debuggers don't usually respect default arguments.
1172 void dump() const;
1173
1174 // Same as dump(), but forces color printing.
1175 void dumpColor() const;
1176
1177 void dump(raw_ostream &Out, bool Deserialize = false,
1178 ASTDumpOutputFormat OutputFormat = ADOF_Default) const;
1179
1180 /// \return Unique reproducible object identifier
1181 int64_t getID() const;
1182
1183 /// Looks through the Decl's underlying type to extract a FunctionType
1184 /// when possible. Will return null if the type underlying the Decl does not
1185 /// have a FunctionType.
1186 const FunctionType *getFunctionType(bool BlocksToo = true) const;
1187
1188private:
1189 void setAttrsImpl(const AttrVec& Attrs, ASTContext &Ctx);
1190 void setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
1191 ASTContext &Ctx);
1192
1193protected:
1194 ASTMutationListener *getASTMutationListener() const;
1195};
1196
1197/// Determine whether two declarations declare the same entity.
1198inline bool declaresSameEntity(const Decl *D1, const Decl *D2) {
1199 if (!D1 || !D2)
1200 return false;
1201
1202 if (D1 == D2)
1203 return true;
1204
1205 return D1->getCanonicalDecl() == D2->getCanonicalDecl();
1206}
1207
1208/// PrettyStackTraceDecl - If a crash occurs, indicate that it happened when
1209/// doing something to a specific decl.
1210class PrettyStackTraceDecl : public llvm::PrettyStackTraceEntry {
1211 const Decl *TheDecl;
1212 SourceLocation Loc;
1213 SourceManager &SM;
1214 const char *Message;
1215
1216public:
1217 PrettyStackTraceDecl(const Decl *theDecl, SourceLocation L,
1218 SourceManager &sm, const char *Msg)
1219 : TheDecl(theDecl), Loc(L), SM(sm), Message(Msg) {}
1220
1221 void print(raw_ostream &OS) const override;
1222};
1223} // namespace clang
1224
1225// Required to determine the layout of the PointerUnion<NamedDecl*> before
1226// seeing the NamedDecl definition being first used in DeclListNode::operator*.
1227namespace llvm {
1228 template <> struct PointerLikeTypeTraits<::clang::NamedDecl *> {
1229 static inline void *getAsVoidPointer(::clang::NamedDecl *P) { return P; }
1230 static inline ::clang::NamedDecl *getFromVoidPointer(void *P) {
1231 return static_cast<::clang::NamedDecl *>(P);
1232 }
1233 static constexpr int NumLowBitsAvailable = 3;
1234 };
1235}
1236
1237namespace clang {
1238/// A list storing NamedDecls in the lookup tables.
1239class DeclListNode {
1240 friend class ASTContext; // allocate, deallocate nodes.
1241 friend class StoredDeclsList;
1242public:
1243 using Decls = llvm::PointerUnion<NamedDecl*, DeclListNode*>;
1244 class iterator {
1245 friend class DeclContextLookupResult;
1246 friend class StoredDeclsList;
1247
1248 Decls Ptr;
1249 iterator(Decls Node) : Ptr(Node) { }
1250 public:
1251 using difference_type = ptrdiff_t;
1252 using value_type = NamedDecl*;
1253 using pointer = void;
1254 using reference = value_type;
1255 using iterator_category = std::forward_iterator_tag;
1256
1257 iterator() = default;
1258
1259 reference operator*() const {
1260 assert(Ptr && "dereferencing end() iterator")(static_cast <bool> (Ptr && "dereferencing end() iterator"
) ? void (0) : __assert_fail ("Ptr && \"dereferencing end() iterator\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/include/clang/AST/DeclBase.h"
, 1260, __extension__ __PRETTY_FUNCTION__))
;
1261 if (DeclListNode *CurNode = Ptr.dyn_cast<DeclListNode*>())
1262 return CurNode->D;
1263 return Ptr.get<NamedDecl*>();
1264 }
1265 void operator->() const { } // Unsupported.
1266 bool operator==(const iterator &X) const { return Ptr == X.Ptr; }
1267 bool operator!=(const iterator &X) const { return Ptr != X.Ptr; }
1268 inline iterator &operator++() { // ++It
1269 assert(!Ptr.isNull() && "Advancing empty iterator")(static_cast <bool> (!Ptr.isNull() && "Advancing empty iterator"
) ? void (0) : __assert_fail ("!Ptr.isNull() && \"Advancing empty iterator\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/include/clang/AST/DeclBase.h"
, 1269, __extension__ __PRETTY_FUNCTION__))
;
1270
1271 if (DeclListNode *CurNode = Ptr.dyn_cast<DeclListNode*>())
1272 Ptr = CurNode->Rest;
1273 else
1274 Ptr = nullptr;
1275 return *this;
1276 }
1277 iterator operator++(int) { // It++
1278 iterator temp = *this;
1279 ++(*this);
1280 return temp;
1281 }
1282 // Enables the pattern for (iterator I =..., E = I.end(); I != E; ++I)
1283 iterator end() { return iterator(); }
1284 };
1285private:
1286 NamedDecl *D = nullptr;
1287 Decls Rest = nullptr;
1288 DeclListNode(NamedDecl *ND) : D(ND) {}
1289};
1290
1291/// The results of name lookup within a DeclContext.
1292class DeclContextLookupResult {
1293 using Decls = DeclListNode::Decls;
1294
1295 /// When in collection form, this is what the Data pointer points to.
1296 Decls Result;
1297
1298public:
1299 DeclContextLookupResult() = default;
1300 DeclContextLookupResult(Decls Result) : Result(Result) {}
1301
1302 using iterator = DeclListNode::iterator;
1303 using const_iterator = iterator;
1304 using reference = iterator::reference;
1305
1306 iterator begin() { return iterator(Result); }
1307 iterator end() { return iterator(); }
1308 const_iterator begin() const {
1309 return const_cast<DeclContextLookupResult*>(this)->begin();
1310 }
1311 const_iterator end() const { return iterator(); }
1312
1313 bool empty() const { return Result.isNull(); }
1314 bool isSingleResult() const { return Result.dyn_cast<NamedDecl*>(); }
1315 reference front() const { return *begin(); }
1316
1317 // Find the first declaration of the given type in the list. Note that this
1318 // is not in general the earliest-declared declaration, and should only be
1319 // used when it's not possible for there to be more than one match or where
1320 // it doesn't matter which one is found.
1321 template<class T> T *find_first() const {
1322 for (auto *D : *this)
1323 if (T *Decl = dyn_cast<T>(D))
1324 return Decl;
1325
1326 return nullptr;
1327 }
1328};
1329
1330/// DeclContext - This is used only as base class of specific decl types that
1331/// can act as declaration contexts. These decls are (only the top classes
1332/// that directly derive from DeclContext are mentioned, not their subclasses):
1333///
1334/// TranslationUnitDecl
1335/// ExternCContext
1336/// NamespaceDecl
1337/// TagDecl
1338/// OMPDeclareReductionDecl
1339/// OMPDeclareMapperDecl
1340/// FunctionDecl
1341/// ObjCMethodDecl
1342/// ObjCContainerDecl
1343/// LinkageSpecDecl
1344/// ExportDecl
1345/// BlockDecl
1346/// CapturedDecl
1347class DeclContext {
1348 /// For makeDeclVisibleInContextImpl
1349 friend class ASTDeclReader;
1350 /// For reconcileExternalVisibleStorage, CreateStoredDeclsMap,
1351 /// hasNeedToReconcileExternalVisibleStorage
1352 friend class ExternalASTSource;
1353 /// For CreateStoredDeclsMap
1354 friend class DependentDiagnostic;
1355 /// For hasNeedToReconcileExternalVisibleStorage,
1356 /// hasLazyLocalLexicalLookups, hasLazyExternalLexicalLookups
1357 friend class ASTWriter;
1358
1359 // We use uint64_t in the bit-fields below since some bit-fields
1360 // cross the unsigned boundary and this breaks the packing.
1361
1362 /// Stores the bits used by DeclContext.
1363 /// If modified NumDeclContextBit, the ctor of DeclContext and the accessor
1364 /// methods in DeclContext should be updated appropriately.
1365 class DeclContextBitfields {
1366 friend class DeclContext;
1367 /// DeclKind - This indicates which class this is.
1368 uint64_t DeclKind : 7;
1369
1370 /// Whether this declaration context also has some external
1371 /// storage that contains additional declarations that are lexically
1372 /// part of this context.
1373 mutable uint64_t ExternalLexicalStorage : 1;
1374
1375 /// Whether this declaration context also has some external
1376 /// storage that contains additional declarations that are visible
1377 /// in this context.
1378 mutable uint64_t ExternalVisibleStorage : 1;
1379
1380 /// Whether this declaration context has had externally visible
1381 /// storage added since the last lookup. In this case, \c LookupPtr's
1382 /// invariant may not hold and needs to be fixed before we perform
1383 /// another lookup.
1384 mutable uint64_t NeedToReconcileExternalVisibleStorage : 1;
1385
1386 /// If \c true, this context may have local lexical declarations
1387 /// that are missing from the lookup table.
1388 mutable uint64_t HasLazyLocalLexicalLookups : 1;
1389
1390 /// If \c true, the external source may have lexical declarations
1391 /// that are missing from the lookup table.
1392 mutable uint64_t HasLazyExternalLexicalLookups : 1;
1393
1394 /// If \c true, lookups should only return identifier from
1395 /// DeclContext scope (for example TranslationUnit). Used in
1396 /// LookupQualifiedName()
1397 mutable uint64_t UseQualifiedLookup : 1;
1398 };
1399
1400 /// Number of bits in DeclContextBitfields.
1401 enum { NumDeclContextBits = 13 };
1402
1403 /// Stores the bits used by TagDecl.
1404 /// If modified NumTagDeclBits and the accessor
1405 /// methods in TagDecl should be updated appropriately.
1406 class TagDeclBitfields {
1407 friend class TagDecl;
1408 /// For the bits in DeclContextBitfields
1409 uint64_t : NumDeclContextBits;
1410
1411 /// The TagKind enum.
1412 uint64_t TagDeclKind : 3;
1413
1414 /// True if this is a definition ("struct foo {};"), false if it is a
1415 /// declaration ("struct foo;"). It is not considered a definition
1416 /// until the definition has been fully processed.
1417 uint64_t IsCompleteDefinition : 1;
1418
1419 /// True if this is currently being defined.
1420 uint64_t IsBeingDefined : 1;
1421
1422 /// True if this tag declaration is "embedded" (i.e., defined or declared
1423 /// for the very first time) in the syntax of a declarator.
1424 uint64_t IsEmbeddedInDeclarator : 1;
1425
1426 /// True if this tag is free standing, e.g. "struct foo;".
1427 uint64_t IsFreeStanding : 1;
1428
1429 /// Indicates whether it is possible for declarations of this kind
1430 /// to have an out-of-date definition.
1431 ///
1432 /// This option is only enabled when modules are enabled.
1433 uint64_t MayHaveOutOfDateDef : 1;
1434
1435 /// Has the full definition of this type been required by a use somewhere in
1436 /// the TU.
1437 uint64_t IsCompleteDefinitionRequired : 1;
1438 };
1439
1440 /// Number of non-inherited bits in TagDeclBitfields.
1441 enum { NumTagDeclBits = 9 };
1442
1443 /// Stores the bits used by EnumDecl.
1444 /// If modified NumEnumDeclBit and the accessor
1445 /// methods in EnumDecl should be updated appropriately.
1446 class EnumDeclBitfields {
1447 friend class EnumDecl;
1448 /// For the bits in DeclContextBitfields.
1449 uint64_t : NumDeclContextBits;
1450 /// For the bits in TagDeclBitfields.
1451 uint64_t : NumTagDeclBits;
1452
1453 /// Width in bits required to store all the non-negative
1454 /// enumerators of this enum.
1455 uint64_t NumPositiveBits : 8;
1456
1457 /// Width in bits required to store all the negative
1458 /// enumerators of this enum.
1459 uint64_t NumNegativeBits : 8;
1460
1461 /// True if this tag declaration is a scoped enumeration. Only
1462 /// possible in C++11 mode.
1463 uint64_t IsScoped : 1;
1464
1465 /// If this tag declaration is a scoped enum,
1466 /// then this is true if the scoped enum was declared using the class
1467 /// tag, false if it was declared with the struct tag. No meaning is
1468 /// associated if this tag declaration is not a scoped enum.
1469 uint64_t IsScopedUsingClassTag : 1;
1470
1471 /// True if this is an enumeration with fixed underlying type. Only
1472 /// possible in C++11, Microsoft extensions, or Objective C mode.
1473 uint64_t IsFixed : 1;
1474
1475 /// True if a valid hash is stored in ODRHash.
1476 uint64_t HasODRHash : 1;
1477 };
1478
1479 /// Number of non-inherited bits in EnumDeclBitfields.
1480 enum { NumEnumDeclBits = 20 };
1481
1482 /// Stores the bits used by RecordDecl.
1483 /// If modified NumRecordDeclBits and the accessor
1484 /// methods in RecordDecl should be updated appropriately.
1485 class RecordDeclBitfields {
1486 friend class RecordDecl;
1487 /// For the bits in DeclContextBitfields.
1488 uint64_t : NumDeclContextBits;
1489 /// For the bits in TagDeclBitfields.
1490 uint64_t : NumTagDeclBits;
1491
1492 /// This is true if this struct ends with a flexible
1493 /// array member (e.g. int X[]) or if this union contains a struct that does.
1494 /// If so, this cannot be contained in arrays or other structs as a member.
1495 uint64_t HasFlexibleArrayMember : 1;
1496
1497 /// Whether this is the type of an anonymous struct or union.
1498 uint64_t AnonymousStructOrUnion : 1;
1499
1500 /// This is true if this struct has at least one member
1501 /// containing an Objective-C object pointer type.
1502 uint64_t HasObjectMember : 1;
1503
1504 /// This is true if struct has at least one member of
1505 /// 'volatile' type.
1506 uint64_t HasVolatileMember : 1;
1507
1508 /// Whether the field declarations of this record have been loaded
1509 /// from external storage. To avoid unnecessary deserialization of
1510 /// methods/nested types we allow deserialization of just the fields
1511 /// when needed.
1512 mutable uint64_t LoadedFieldsFromExternalStorage : 1;
1513
1514 /// Basic properties of non-trivial C structs.
1515 uint64_t NonTrivialToPrimitiveDefaultInitialize : 1;
1516 uint64_t NonTrivialToPrimitiveCopy : 1;
1517 uint64_t NonTrivialToPrimitiveDestroy : 1;
1518
1519 /// The following bits indicate whether this is or contains a C union that
1520 /// is non-trivial to default-initialize, destruct, or copy. These bits
1521 /// imply the associated basic non-triviality predicates declared above.
1522 uint64_t HasNonTrivialToPrimitiveDefaultInitializeCUnion : 1;
1523 uint64_t HasNonTrivialToPrimitiveDestructCUnion : 1;
1524 uint64_t HasNonTrivialToPrimitiveCopyCUnion : 1;
1525
1526 /// Indicates whether this struct is destroyed in the callee.
1527 uint64_t ParamDestroyedInCallee : 1;
1528
1529 /// Represents the way this type is passed to a function.
1530 uint64_t ArgPassingRestrictions : 2;
1531 };
1532
1533 /// Number of non-inherited bits in RecordDeclBitfields.
1534 enum { NumRecordDeclBits = 14 };
1535
1536 /// Stores the bits used by OMPDeclareReductionDecl.
1537 /// If modified NumOMPDeclareReductionDeclBits and the accessor
1538 /// methods in OMPDeclareReductionDecl should be updated appropriately.
1539 class OMPDeclareReductionDeclBitfields {
1540 friend class OMPDeclareReductionDecl;
1541 /// For the bits in DeclContextBitfields
1542 uint64_t : NumDeclContextBits;
1543
1544 /// Kind of initializer,
1545 /// function call or omp_priv<init_expr> initializtion.
1546 uint64_t InitializerKind : 2;
1547 };
1548
1549 /// Number of non-inherited bits in OMPDeclareReductionDeclBitfields.
1550 enum { NumOMPDeclareReductionDeclBits = 2 };
1551
1552 /// Stores the bits used by FunctionDecl.
1553 /// If modified NumFunctionDeclBits and the accessor
1554 /// methods in FunctionDecl and CXXDeductionGuideDecl
1555 /// (for IsCopyDeductionCandidate) should be updated appropriately.
1556 class FunctionDeclBitfields {
1557 friend class FunctionDecl;
1558 /// For IsCopyDeductionCandidate
1559 friend class CXXDeductionGuideDecl;
1560 /// For the bits in DeclContextBitfields.
1561 uint64_t : NumDeclContextBits;
1562
1563 uint64_t SClass : 3;
1564 uint64_t IsInline : 1;
1565 uint64_t IsInlineSpecified : 1;
1566
1567 uint64_t IsVirtualAsWritten : 1;
1568 uint64_t IsPure : 1;
1569 uint64_t HasInheritedPrototype : 1;
1570 uint64_t HasWrittenPrototype : 1;
1571 uint64_t IsDeleted : 1;
1572 /// Used by CXXMethodDecl
1573 uint64_t IsTrivial : 1;
1574
1575 /// This flag indicates whether this function is trivial for the purpose of
1576 /// calls. This is meaningful only when this function is a copy/move
1577 /// constructor or a destructor.
1578 uint64_t IsTrivialForCall : 1;
1579
1580 uint64_t IsDefaulted : 1;
1581 uint64_t IsExplicitlyDefaulted : 1;
1582 uint64_t HasDefaultedFunctionInfo : 1;
1583 uint64_t HasImplicitReturnZero : 1;
1584 uint64_t IsLateTemplateParsed : 1;
1585
1586 /// Kind of contexpr specifier as defined by ConstexprSpecKind.
1587 uint64_t ConstexprKind : 2;
1588 uint64_t InstantiationIsPending : 1;
1589
1590 /// Indicates if the function uses __try.
1591 uint64_t UsesSEHTry : 1;
1592
1593 /// Indicates if the function was a definition
1594 /// but its body was skipped.
1595 uint64_t HasSkippedBody : 1;
1596
1597 /// Indicates if the function declaration will
1598 /// have a body, once we're done parsing it.
1599 uint64_t WillHaveBody : 1;
1600
1601 /// Indicates that this function is a multiversioned
1602 /// function using attribute 'target'.
1603 uint64_t IsMultiVersion : 1;
1604
1605 /// [C++17] Only used by CXXDeductionGuideDecl. Indicates that
1606 /// the Deduction Guide is the implicitly generated 'copy
1607 /// deduction candidate' (is used during overload resolution).
1608 uint64_t IsCopyDeductionCandidate : 1;
1609
1610 /// Store the ODRHash after first calculation.
1611 uint64_t HasODRHash : 1;
1612
1613 /// Indicates if the function uses Floating Point Constrained Intrinsics
1614 uint64_t UsesFPIntrin : 1;
1615 };
1616
1617 /// Number of non-inherited bits in FunctionDeclBitfields.
1618 enum { NumFunctionDeclBits = 27 };
1619
1620 /// Stores the bits used by CXXConstructorDecl. If modified
1621 /// NumCXXConstructorDeclBits and the accessor
1622 /// methods in CXXConstructorDecl should be updated appropriately.
1623 class CXXConstructorDeclBitfields {
1624 friend class CXXConstructorDecl;
1625 /// For the bits in DeclContextBitfields.
1626 uint64_t : NumDeclContextBits;
1627 /// For the bits in FunctionDeclBitfields.
1628 uint64_t : NumFunctionDeclBits;
1629
1630 /// 24 bits to fit in the remaining available space.
1631 /// Note that this makes CXXConstructorDeclBitfields take
1632 /// exactly 64 bits and thus the width of NumCtorInitializers
1633 /// will need to be shrunk if some bit is added to NumDeclContextBitfields,
1634 /// NumFunctionDeclBitfields or CXXConstructorDeclBitfields.
1635 uint64_t NumCtorInitializers : 21;
1636 uint64_t IsInheritingConstructor : 1;
1637
1638 /// Whether this constructor has a trail-allocated explicit specifier.
1639 uint64_t HasTrailingExplicitSpecifier : 1;
1640 /// If this constructor does't have a trail-allocated explicit specifier.
1641 /// Whether this constructor is explicit specified.
1642 uint64_t IsSimpleExplicit : 1;
1643 };
1644
1645 /// Number of non-inherited bits in CXXConstructorDeclBitfields.
1646 enum {
1647 NumCXXConstructorDeclBits = 64 - NumDeclContextBits - NumFunctionDeclBits
1648 };
1649
1650 /// Stores the bits used by ObjCMethodDecl.
1651 /// If modified NumObjCMethodDeclBits and the accessor
1652 /// methods in ObjCMethodDecl should be updated appropriately.
1653 class ObjCMethodDeclBitfields {
1654 friend class ObjCMethodDecl;
1655
1656 /// For the bits in DeclContextBitfields.
1657 uint64_t : NumDeclContextBits;
1658
1659 /// The conventional meaning of this method; an ObjCMethodFamily.
1660 /// This is not serialized; instead, it is computed on demand and
1661 /// cached.
1662 mutable uint64_t Family : ObjCMethodFamilyBitWidth;
1663
1664 /// instance (true) or class (false) method.
1665 uint64_t IsInstance : 1;
1666 uint64_t IsVariadic : 1;
1667
1668 /// True if this method is the getter or setter for an explicit property.
1669 uint64_t IsPropertyAccessor : 1;
1670
1671 /// True if this method is a synthesized property accessor stub.
1672 uint64_t IsSynthesizedAccessorStub : 1;
1673
1674 /// Method has a definition.
1675 uint64_t IsDefined : 1;
1676
1677 /// Method redeclaration in the same interface.
1678 uint64_t IsRedeclaration : 1;
1679
1680 /// Is redeclared in the same interface.
1681 mutable uint64_t HasRedeclaration : 1;
1682
1683 /// \@required/\@optional
1684 uint64_t DeclImplementation : 2;
1685
1686 /// in, inout, etc.
1687 uint64_t objcDeclQualifier : 7;
1688
1689 /// Indicates whether this method has a related result type.
1690 uint64_t RelatedResultType : 1;
1691
1692 /// Whether the locations of the selector identifiers are in a
1693 /// "standard" position, a enum SelectorLocationsKind.
1694 uint64_t SelLocsKind : 2;
1695
1696 /// Whether this method overrides any other in the class hierarchy.
1697 ///
1698 /// A method is said to override any method in the class's
1699 /// base classes, its protocols, or its categories' protocols, that has
1700 /// the same selector and is of the same kind (class or instance).
1701 /// A method in an implementation is not considered as overriding the same
1702 /// method in the interface or its categories.
1703 uint64_t IsOverriding : 1;
1704
1705 /// Indicates if the method was a definition but its body was skipped.
1706 uint64_t HasSkippedBody : 1;
1707 };
1708
1709 /// Number of non-inherited bits in ObjCMethodDeclBitfields.
1710 enum { NumObjCMethodDeclBits = 24 };
1711
1712 /// Stores the bits used by ObjCContainerDecl.
1713 /// If modified NumObjCContainerDeclBits and the accessor
1714 /// methods in ObjCContainerDecl should be updated appropriately.
1715 class ObjCContainerDeclBitfields {
1716 friend class ObjCContainerDecl;
1717 /// For the bits in DeclContextBitfields
1718 uint32_t : NumDeclContextBits;
1719
1720 // Not a bitfield but this saves space.
1721 // Note that ObjCContainerDeclBitfields is full.
1722 SourceLocation AtStart;
1723 };
1724
1725 /// Number of non-inherited bits in ObjCContainerDeclBitfields.
1726 /// Note that here we rely on the fact that SourceLocation is 32 bits
1727 /// wide. We check this with the static_assert in the ctor of DeclContext.
1728 enum { NumObjCContainerDeclBits = 64 - NumDeclContextBits };
1729
1730 /// Stores the bits used by LinkageSpecDecl.
1731 /// If modified NumLinkageSpecDeclBits and the accessor
1732 /// methods in LinkageSpecDecl should be updated appropriately.
1733 class LinkageSpecDeclBitfields {
1734 friend class LinkageSpecDecl;
1735 /// For the bits in DeclContextBitfields.
1736 uint64_t : NumDeclContextBits;
1737
1738 /// The language for this linkage specification with values
1739 /// in the enum LinkageSpecDecl::LanguageIDs.
1740 uint64_t Language : 3;
1741
1742 /// True if this linkage spec has braces.
1743 /// This is needed so that hasBraces() returns the correct result while the
1744 /// linkage spec body is being parsed. Once RBraceLoc has been set this is
1745 /// not used, so it doesn't need to be serialized.
1746 uint64_t HasBraces : 1;
1747 };
1748
1749 /// Number of non-inherited bits in LinkageSpecDeclBitfields.
1750 enum { NumLinkageSpecDeclBits = 4 };
1751
1752 /// Stores the bits used by BlockDecl.
1753 /// If modified NumBlockDeclBits and the accessor
1754 /// methods in BlockDecl should be updated appropriately.
1755 class BlockDeclBitfields {
1756 friend class BlockDecl;
1757 /// For the bits in DeclContextBitfields.
1758 uint64_t : NumDeclContextBits;
1759
1760 uint64_t IsVariadic : 1;
1761 uint64_t CapturesCXXThis : 1;
1762 uint64_t BlockMissingReturnType : 1;
1763 uint64_t IsConversionFromLambda : 1;
1764
1765 /// A bit that indicates this block is passed directly to a function as a
1766 /// non-escaping parameter.
1767 uint64_t DoesNotEscape : 1;
1768
1769 /// A bit that indicates whether it's possible to avoid coying this block to
1770 /// the heap when it initializes or is assigned to a local variable with
1771 /// automatic storage.
1772 uint64_t CanAvoidCopyToHeap : 1;
1773 };
1774
1775 /// Number of non-inherited bits in BlockDeclBitfields.
1776 enum { NumBlockDeclBits = 5 };
1777
1778 /// Pointer to the data structure used to lookup declarations
1779 /// within this context (or a DependentStoredDeclsMap if this is a
1780 /// dependent context). We maintain the invariant that, if the map
1781 /// contains an entry for a DeclarationName (and we haven't lazily
1782 /// omitted anything), then it contains all relevant entries for that
1783 /// name (modulo the hasExternalDecls() flag).
1784 mutable StoredDeclsMap *LookupPtr = nullptr;
1785
1786protected:
1787 /// This anonymous union stores the bits belonging to DeclContext and classes
1788 /// deriving from it. The goal is to use otherwise wasted
1789 /// space in DeclContext to store data belonging to derived classes.
1790 /// The space saved is especially significient when pointers are aligned
1791 /// to 8 bytes. In this case due to alignment requirements we have a
1792 /// little less than 8 bytes free in DeclContext which we can use.
1793 /// We check that none of the classes in this union is larger than
1794 /// 8 bytes with static_asserts in the ctor of DeclContext.
1795 union {
1796 DeclContextBitfields DeclContextBits;
1797 TagDeclBitfields TagDeclBits;
1798 EnumDeclBitfields EnumDeclBits;
1799 RecordDeclBitfields RecordDeclBits;
1800 OMPDeclareReductionDeclBitfields OMPDeclareReductionDeclBits;
1801 FunctionDeclBitfields FunctionDeclBits;
1802 CXXConstructorDeclBitfields CXXConstructorDeclBits;
1803 ObjCMethodDeclBitfields ObjCMethodDeclBits;
1804 ObjCContainerDeclBitfields ObjCContainerDeclBits;
1805 LinkageSpecDeclBitfields LinkageSpecDeclBits;
1806 BlockDeclBitfields BlockDeclBits;
1807
1808 static_assert(sizeof(DeclContextBitfields) <= 8,
1809 "DeclContextBitfields is larger than 8 bytes!");
1810 static_assert(sizeof(TagDeclBitfields) <= 8,
1811 "TagDeclBitfields is larger than 8 bytes!");
1812 static_assert(sizeof(EnumDeclBitfields) <= 8,
1813 "EnumDeclBitfields is larger than 8 bytes!");
1814 static_assert(sizeof(RecordDeclBitfields) <= 8,
1815 "RecordDeclBitfields is larger than 8 bytes!");
1816 static_assert(sizeof(OMPDeclareReductionDeclBitfields) <= 8,
1817 "OMPDeclareReductionDeclBitfields is larger than 8 bytes!");
1818 static_assert(sizeof(FunctionDeclBitfields) <= 8,
1819 "FunctionDeclBitfields is larger than 8 bytes!");
1820 static_assert(sizeof(CXXConstructorDeclBitfields) <= 8,
1821 "CXXConstructorDeclBitfields is larger than 8 bytes!");
1822 static_assert(sizeof(ObjCMethodDeclBitfields) <= 8,
1823 "ObjCMethodDeclBitfields is larger than 8 bytes!");
1824 static_assert(sizeof(ObjCContainerDeclBitfields) <= 8,
1825 "ObjCContainerDeclBitfields is larger than 8 bytes!");
1826 static_assert(sizeof(LinkageSpecDeclBitfields) <= 8,
1827 "LinkageSpecDeclBitfields is larger than 8 bytes!");
1828 static_assert(sizeof(BlockDeclBitfields) <= 8,
1829 "BlockDeclBitfields is larger than 8 bytes!");
1830 };
1831
1832 /// FirstDecl - The first declaration stored within this declaration
1833 /// context.
1834 mutable Decl *FirstDecl = nullptr;
1835
1836 /// LastDecl - The last declaration stored within this declaration
1837 /// context. FIXME: We could probably cache this value somewhere
1838 /// outside of the DeclContext, to reduce the size of DeclContext by
1839 /// another pointer.
1840 mutable Decl *LastDecl = nullptr;
1841
1842 /// Build up a chain of declarations.
1843 ///
1844 /// \returns the first/last pair of declarations.
1845 static std::pair<Decl *, Decl *>
1846 BuildDeclChain(ArrayRef<Decl*> Decls, bool FieldsAlreadyLoaded);
1847
1848 DeclContext(Decl::Kind K);
1849
1850public:
1851 ~DeclContext();
1852
1853 Decl::Kind getDeclKind() const {
1854 return static_cast<Decl::Kind>(DeclContextBits.DeclKind);
1855 }
1856
1857 const char *getDeclKindName() const;
1858
1859 /// getParent - Returns the containing DeclContext.
1860 DeclContext *getParent() {
1861 return cast<Decl>(this)->getDeclContext();
1862 }
1863 const DeclContext *getParent() const {
1864 return const_cast<DeclContext*>(this)->getParent();
1865 }
1866
1867 /// getLexicalParent - Returns the containing lexical DeclContext. May be
1868 /// different from getParent, e.g.:
1869 ///
1870 /// namespace A {
1871 /// struct S;
1872 /// }
1873 /// struct A::S {}; // getParent() == namespace 'A'
1874 /// // getLexicalParent() == translation unit
1875 ///
1876 DeclContext *getLexicalParent() {
1877 return cast<Decl>(this)->getLexicalDeclContext();
1878 }
1879 const DeclContext *getLexicalParent() const {
1880 return const_cast<DeclContext*>(this)->getLexicalParent();
1881 }
1882
1883 DeclContext *getLookupParent();
1884
1885 const DeclContext *getLookupParent() const {
1886 return const_cast<DeclContext*>(this)->getLookupParent();
1887 }
1888
1889 ASTContext &getParentASTContext() const {
1890 return cast<Decl>(this)->getASTContext();
1891 }
1892
1893 bool isClosure() const { return getDeclKind() == Decl::Block; }
1894
1895 /// Return this DeclContext if it is a BlockDecl. Otherwise, return the
1896 /// innermost enclosing BlockDecl or null if there are no enclosing blocks.
1897 const BlockDecl *getInnermostBlockDecl() const;
1898
1899 bool isObjCContainer() const {
1900 switch (getDeclKind()) {
1901 case Decl::ObjCCategory:
1902 case Decl::ObjCCategoryImpl:
1903 case Decl::ObjCImplementation:
1904 case Decl::ObjCInterface:
1905 case Decl::ObjCProtocol:
1906 return true;
1907 default:
1908 return false;
1909 }
1910 }
1911
1912 bool isFunctionOrMethod() const {
1913 switch (getDeclKind()) {
1914 case Decl::Block:
1915 case Decl::Captured:
1916 case Decl::ObjCMethod:
1917 return true;
1918 default:
1919 return getDeclKind() >= Decl::firstFunction &&
1920 getDeclKind() <= Decl::lastFunction;
1921 }
1922 }
1923
1924 /// Test whether the context supports looking up names.
1925 bool isLookupContext() const {
1926 return !isFunctionOrMethod() && getDeclKind() != Decl::LinkageSpec &&
1927 getDeclKind() != Decl::Export;
1928 }
1929
1930 bool isFileContext() const {
1931 return getDeclKind() == Decl::TranslationUnit ||
1932 getDeclKind() == Decl::Namespace;
1933 }
1934
1935 bool isTranslationUnit() const {
1936 return getDeclKind() == Decl::TranslationUnit;
1937 }
1938
1939 bool isRecord() const {
1940 return getDeclKind() >= Decl::firstRecord &&
52
Assuming the condition is false
53
Returning zero, which participates in a condition later
1941 getDeclKind() <= Decl::lastRecord;
1942 }
1943
1944 bool isNamespace() const { return getDeclKind() == Decl::Namespace; }
1945
1946 bool isStdNamespace() const;
1947
1948 bool isInlineNamespace() const;
1949
1950 /// Determines whether this context is dependent on a
1951 /// template parameter.
1952 bool isDependentContext() const;
1953
1954 /// isTransparentContext - Determines whether this context is a
1955 /// "transparent" context, meaning that the members declared in this
1956 /// context are semantically declared in the nearest enclosing
1957 /// non-transparent (opaque) context but are lexically declared in
1958 /// this context. For example, consider the enumerators of an
1959 /// enumeration type:
1960 /// @code
1961 /// enum E {
1962 /// Val1
1963 /// };
1964 /// @endcode
1965 /// Here, E is a transparent context, so its enumerator (Val1) will
1966 /// appear (semantically) that it is in the same context of E.
1967 /// Examples of transparent contexts include: enumerations (except for
1968 /// C++0x scoped enums), and C++ linkage specifications.
1969 bool isTransparentContext() const;
1970
1971 /// Determines whether this context or some of its ancestors is a
1972 /// linkage specification context that specifies C linkage.
1973 bool isExternCContext() const;
1974
1975 /// Retrieve the nearest enclosing C linkage specification context.
1976 const LinkageSpecDecl *getExternCContext() const;
1977
1978 /// Determines whether this context or some of its ancestors is a
1979 /// linkage specification context that specifies C++ linkage.
1980 bool isExternCXXContext() const;
1981
1982 /// Determine whether this declaration context is equivalent
1983 /// to the declaration context DC.
1984 bool Equals(const DeclContext *DC) const {
1985 return DC && this->getPrimaryContext() == DC->getPrimaryContext();
1986 }
1987
1988 /// Determine whether this declaration context encloses the
1989 /// declaration context DC.
1990 bool Encloses(const DeclContext *DC) const;
1991
1992 /// Find the nearest non-closure ancestor of this context,
1993 /// i.e. the innermost semantic parent of this context which is not
1994 /// a closure. A context may be its own non-closure ancestor.
1995 Decl *getNonClosureAncestor();
1996 const Decl *getNonClosureAncestor() const {
1997 return const_cast<DeclContext*>(this)->getNonClosureAncestor();
1998 }
1999
2000 // Retrieve the nearest context that is not a transparent context.
2001 DeclContext *getNonTransparentContext();
2002 const DeclContext *getNonTransparentContext() const {
2003 return const_cast<DeclContext *>(this)->getNonTransparentContext();
2004 }
2005
2006 /// getPrimaryContext - There may be many different
2007 /// declarations of the same entity (including forward declarations
2008 /// of classes, multiple definitions of namespaces, etc.), each with
2009 /// a different set of declarations. This routine returns the
2010 /// "primary" DeclContext structure, which will contain the
2011 /// information needed to perform name lookup into this context.
2012 DeclContext *getPrimaryContext();
2013 const DeclContext *getPrimaryContext() const {
2014 return const_cast<DeclContext*>(this)->getPrimaryContext();
2015 }
2016
2017 /// getRedeclContext - Retrieve the context in which an entity conflicts with
2018 /// other entities of the same name, or where it is a redeclaration if the
2019 /// two entities are compatible. This skips through transparent contexts.
2020 DeclContext *getRedeclContext();
2021 const DeclContext *getRedeclContext() const {
2022 return const_cast<DeclContext *>(this)->getRedeclContext();
2023 }
2024
2025 /// Retrieve the nearest enclosing namespace context.
2026 DeclContext *getEnclosingNamespaceContext();
2027 const DeclContext *getEnclosingNamespaceContext() const {
2028 return const_cast<DeclContext *>(this)->getEnclosingNamespaceContext();
2029 }
2030
2031 /// Retrieve the outermost lexically enclosing record context.
2032 RecordDecl *getOuterLexicalRecordContext();
2033 const RecordDecl *getOuterLexicalRecordContext() const {
2034 return const_cast<DeclContext *>(this)->getOuterLexicalRecordContext();
2035 }
2036
2037 /// Test if this context is part of the enclosing namespace set of
2038 /// the context NS, as defined in C++0x [namespace.def]p9. If either context
2039 /// isn't a namespace, this is equivalent to Equals().
2040 ///
2041 /// The enclosing namespace set of a namespace is the namespace and, if it is
2042 /// inline, its enclosing namespace, recursively.
2043 bool InEnclosingNamespaceSetOf(const DeclContext *NS) const;
2044
2045 /// Collects all of the declaration contexts that are semantically
2046 /// connected to this declaration context.
2047 ///
2048 /// For declaration contexts that have multiple semantically connected but
2049 /// syntactically distinct contexts, such as C++ namespaces, this routine
2050 /// retrieves the complete set of such declaration contexts in source order.
2051 /// For example, given:
2052 ///
2053 /// \code
2054 /// namespace N {
2055 /// int x;
2056 /// }
2057 /// namespace N {
2058 /// int y;
2059 /// }
2060 /// \endcode
2061 ///
2062 /// The \c Contexts parameter will contain both definitions of N.
2063 ///
2064 /// \param Contexts Will be cleared and set to the set of declaration
2065 /// contexts that are semanticaly connected to this declaration context,
2066 /// in source order, including this context (which may be the only result,
2067 /// for non-namespace contexts).
2068 void collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts);
2069
2070 /// decl_iterator - Iterates through the declarations stored
2071 /// within this context.
2072 class decl_iterator {
2073 /// Current - The current declaration.
2074 Decl *Current = nullptr;
2075
2076 public:
2077 using value_type = Decl *;
2078 using reference = const value_type &;
2079 using pointer = const value_type *;
2080 using iterator_category = std::forward_iterator_tag;
2081 using difference_type = std::ptrdiff_t;
2082
2083 decl_iterator() = default;
2084 explicit decl_iterator(Decl *C) : Current(C) {}
2085
2086 reference operator*() const { return Current; }
2087
2088 // This doesn't meet the iterator requirements, but it's convenient
2089 value_type operator->() const { return Current; }
2090
2091 decl_iterator& operator++() {
2092 Current = Current->getNextDeclInContext();
2093 return *this;
2094 }
2095
2096 decl_iterator operator++(int) {
2097 decl_iterator tmp(*this);
2098 ++(*this);
2099 return tmp;
2100 }
2101
2102 friend bool operator==(decl_iterator x, decl_iterator y) {
2103 return x.Current == y.Current;
2104 }
2105
2106 friend bool operator!=(decl_iterator x, decl_iterator y) {
2107 return x.Current != y.Current;
2108 }
2109 };
2110
2111 using decl_range = llvm::iterator_range<decl_iterator>;
2112
2113 /// decls_begin/decls_end - Iterate over the declarations stored in
2114 /// this context.
2115 decl_range decls() const { return decl_range(decls_begin(), decls_end()); }
2116 decl_iterator decls_begin() const;
2117 decl_iterator decls_end() const { return decl_iterator(); }
2118 bool decls_empty() const;
2119
2120 /// noload_decls_begin/end - Iterate over the declarations stored in this
2121 /// context that are currently loaded; don't attempt to retrieve anything
2122 /// from an external source.
2123 decl_range noload_decls() const {
2124 return decl_range(noload_decls_begin(), noload_decls_end());
2125 }
2126 decl_iterator noload_decls_begin() const { return decl_iterator(FirstDecl); }
2127 decl_iterator noload_decls_end() const { return decl_iterator(); }
2128
2129 /// specific_decl_iterator - Iterates over a subrange of
2130 /// declarations stored in a DeclContext, providing only those that
2131 /// are of type SpecificDecl (or a class derived from it). This
2132 /// iterator is used, for example, to provide iteration over just
2133 /// the fields within a RecordDecl (with SpecificDecl = FieldDecl).
2134 template<typename SpecificDecl>
2135 class specific_decl_iterator {
2136 /// Current - The current, underlying declaration iterator, which
2137 /// will either be NULL or will point to a declaration of
2138 /// type SpecificDecl.
2139 DeclContext::decl_iterator Current;
2140
2141 /// SkipToNextDecl - Advances the current position up to the next
2142 /// declaration of type SpecificDecl that also meets the criteria
2143 /// required by Acceptable.
2144 void SkipToNextDecl() {
2145 while (*Current && !isa<SpecificDecl>(*Current))
2146 ++Current;
2147 }
2148
2149 public:
2150 using value_type = SpecificDecl *;
2151 // TODO: Add reference and pointer types (with some appropriate proxy type)
2152 // if we ever have a need for them.
2153 using reference = void;
2154 using pointer = void;
2155 using difference_type =
2156 std::iterator_traits<DeclContext::decl_iterator>::difference_type;
2157 using iterator_category = std::forward_iterator_tag;
2158
2159 specific_decl_iterator() = default;
2160
2161 /// specific_decl_iterator - Construct a new iterator over a
2162 /// subset of the declarations the range [C,
2163 /// end-of-declarations). If A is non-NULL, it is a pointer to a
2164 /// member function of SpecificDecl that should return true for
2165 /// all of the SpecificDecl instances that will be in the subset
2166 /// of iterators. For example, if you want Objective-C instance
2167 /// methods, SpecificDecl will be ObjCMethodDecl and A will be
2168 /// &ObjCMethodDecl::isInstanceMethod.
2169 explicit specific_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
2170 SkipToNextDecl();
2171 }
2172
2173 value_type operator*() const { return cast<SpecificDecl>(*Current); }
2174
2175 // This doesn't meet the iterator requirements, but it's convenient
2176 value_type operator->() const { return **this; }
2177
2178 specific_decl_iterator& operator++() {
2179 ++Current;
2180 SkipToNextDecl();
2181 return *this;
2182 }
2183
2184 specific_decl_iterator operator++(int) {
2185 specific_decl_iterator tmp(*this);
2186 ++(*this);
2187 return tmp;
2188 }
2189
2190 friend bool operator==(const specific_decl_iterator& x,
2191 const specific_decl_iterator& y) {
2192 return x.Current == y.Current;
2193 }
2194
2195 friend bool operator!=(const specific_decl_iterator& x,
2196 const specific_decl_iterator& y) {
2197 return x.Current != y.Current;
2198 }
2199 };
2200
2201 /// Iterates over a filtered subrange of declarations stored
2202 /// in a DeclContext.
2203 ///
2204 /// This iterator visits only those declarations that are of type
2205 /// SpecificDecl (or a class derived from it) and that meet some
2206 /// additional run-time criteria. This iterator is used, for
2207 /// example, to provide access to the instance methods within an
2208 /// Objective-C interface (with SpecificDecl = ObjCMethodDecl and
2209 /// Acceptable = ObjCMethodDecl::isInstanceMethod).
2210 template<typename SpecificDecl, bool (SpecificDecl::*Acceptable)() const>
2211 class filtered_decl_iterator {
2212 /// Current - The current, underlying declaration iterator, which
2213 /// will either be NULL or will point to a declaration of
2214 /// type SpecificDecl.
2215 DeclContext::decl_iterator Current;
2216
2217 /// SkipToNextDecl - Advances the current position up to the next
2218 /// declaration of type SpecificDecl that also meets the criteria
2219 /// required by Acceptable.
2220 void SkipToNextDecl() {
2221 while (*Current &&
2222 (!isa<SpecificDecl>(*Current) ||
2223 (Acceptable && !(cast<SpecificDecl>(*Current)->*Acceptable)())))
2224 ++Current;
2225 }
2226
2227 public:
2228 using value_type = SpecificDecl *;
2229 // TODO: Add reference and pointer types (with some appropriate proxy type)
2230 // if we ever have a need for them.
2231 using reference = void;
2232 using pointer = void;
2233 using difference_type =
2234 std::iterator_traits<DeclContext::decl_iterator>::difference_type;
2235 using iterator_category = std::forward_iterator_tag;
2236
2237 filtered_decl_iterator() = default;
2238
2239 /// filtered_decl_iterator - Construct a new iterator over a
2240 /// subset of the declarations the range [C,
2241 /// end-of-declarations). If A is non-NULL, it is a pointer to a
2242 /// member function of SpecificDecl that should return true for
2243 /// all of the SpecificDecl instances that will be in the subset
2244 /// of iterators. For example, if you want Objective-C instance
2245 /// methods, SpecificDecl will be ObjCMethodDecl and A will be
2246 /// &ObjCMethodDecl::isInstanceMethod.
2247 explicit filtered_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
2248 SkipToNextDecl();
2249 }
2250
2251 value_type operator*() const { return cast<SpecificDecl>(*Current); }
2252 value_type operator->() const { return cast<SpecificDecl>(*Current); }
2253
2254 filtered_decl_iterator& operator++() {
2255 ++Current;
2256 SkipToNextDecl();
2257 return *this;
2258 }
2259
2260 filtered_decl_iterator operator++(int) {
2261 filtered_decl_iterator tmp(*this);
2262 ++(*this);
2263 return tmp;
2264 }
2265
2266 friend bool operator==(const filtered_decl_iterator& x,
2267 const filtered_decl_iterator& y) {
2268 return x.Current == y.Current;
2269 }
2270
2271 friend bool operator!=(const filtered_decl_iterator& x,
2272 const filtered_decl_iterator& y) {
2273 return x.Current != y.Current;
2274 }
2275 };
2276
2277 /// Add the declaration D into this context.
2278 ///
2279 /// This routine should be invoked when the declaration D has first
2280 /// been declared, to place D into the context where it was
2281 /// (lexically) defined. Every declaration must be added to one
2282 /// (and only one!) context, where it can be visited via
2283 /// [decls_begin(), decls_end()). Once a declaration has been added
2284 /// to its lexical context, the corresponding DeclContext owns the
2285 /// declaration.
2286 ///
2287 /// If D is also a NamedDecl, it will be made visible within its
2288 /// semantic context via makeDeclVisibleInContext.
2289 void addDecl(Decl *D);
2290
2291 /// Add the declaration D into this context, but suppress
2292 /// searches for external declarations with the same name.
2293 ///
2294 /// Although analogous in function to addDecl, this removes an
2295 /// important check. This is only useful if the Decl is being
2296 /// added in response to an external search; in all other cases,
2297 /// addDecl() is the right function to use.
2298 /// See the ASTImporter for use cases.
2299 void addDeclInternal(Decl *D);
2300
2301 /// Add the declaration D to this context without modifying
2302 /// any lookup tables.
2303 ///
2304 /// This is useful for some operations in dependent contexts where
2305 /// the semantic context might not be dependent; this basically
2306 /// only happens with friends.
2307 void addHiddenDecl(Decl *D);
2308
2309 /// Removes a declaration from this context.
2310 void removeDecl(Decl *D);
2311
2312 /// Checks whether a declaration is in this context.
2313 bool containsDecl(Decl *D) const;
2314
2315 /// Checks whether a declaration is in this context.
2316 /// This also loads the Decls from the external source before the check.
2317 bool containsDeclAndLoad(Decl *D) const;
2318
2319 using lookup_result = DeclContextLookupResult;
2320 using lookup_iterator = lookup_result::iterator;
2321
2322 /// lookup - Find the declarations (if any) with the given Name in
2323 /// this context. Returns a range of iterators that contains all of
2324 /// the declarations with this name, with object, function, member,
2325 /// and enumerator names preceding any tag name. Note that this
2326 /// routine will not look into parent contexts.
2327 lookup_result lookup(DeclarationName Name) const;
2328
2329 /// Find the declarations with the given name that are visible
2330 /// within this context; don't attempt to retrieve anything from an
2331 /// external source.
2332 lookup_result noload_lookup(DeclarationName Name);
2333
2334 /// A simplistic name lookup mechanism that performs name lookup
2335 /// into this declaration context without consulting the external source.
2336 ///
2337 /// This function should almost never be used, because it subverts the
2338 /// usual relationship between a DeclContext and the external source.
2339 /// See the ASTImporter for the (few, but important) use cases.
2340 ///
2341 /// FIXME: This is very inefficient; replace uses of it with uses of
2342 /// noload_lookup.
2343 void localUncachedLookup(DeclarationName Name,
2344 SmallVectorImpl<NamedDecl *> &Results);
2345
2346 /// Makes a declaration visible within this context.
2347 ///
2348 /// This routine makes the declaration D visible to name lookup
2349 /// within this context and, if this is a transparent context,
2350 /// within its parent contexts up to the first enclosing
2351 /// non-transparent context. Making a declaration visible within a
2352 /// context does not transfer ownership of a declaration, and a
2353 /// declaration can be visible in many contexts that aren't its
2354 /// lexical context.
2355 ///
2356 /// If D is a redeclaration of an existing declaration that is
2357 /// visible from this context, as determined by
2358 /// NamedDecl::declarationReplaces, the previous declaration will be
2359 /// replaced with D.
2360 void makeDeclVisibleInContext(NamedDecl *D);
2361
2362 /// all_lookups_iterator - An iterator that provides a view over the results
2363 /// of looking up every possible name.
2364 class all_lookups_iterator;
2365
2366 using lookups_range = llvm::iterator_range<all_lookups_iterator>;
2367
2368 lookups_range lookups() const;
2369 // Like lookups(), but avoids loading external declarations.
2370 // If PreserveInternalState, avoids building lookup data structures too.
2371 lookups_range noload_lookups(bool PreserveInternalState) const;
2372
2373 /// Iterators over all possible lookups within this context.
2374 all_lookups_iterator lookups_begin() const;
2375 all_lookups_iterator lookups_end() const;
2376
2377 /// Iterators over all possible lookups within this context that are
2378 /// currently loaded; don't attempt to retrieve anything from an external
2379 /// source.
2380 all_lookups_iterator noload_lookups_begin() const;
2381 all_lookups_iterator noload_lookups_end() const;
2382
2383 struct udir_iterator;
2384
2385 using udir_iterator_base =
2386 llvm::iterator_adaptor_base<udir_iterator, lookup_iterator,
2387 typename lookup_iterator::iterator_category,
2388 UsingDirectiveDecl *>;
2389
2390 struct udir_iterator : udir_iterator_base {
2391 udir_iterator(lookup_iterator I) : udir_iterator_base(I) {}
2392
2393 UsingDirectiveDecl *operator*() const;
2394 };
2395
2396 using udir_range = llvm::iterator_range<udir_iterator>;
2397
2398 udir_range using_directives() const;
2399
2400 // These are all defined in DependentDiagnostic.h.
2401 class ddiag_iterator;
2402
2403 using ddiag_range = llvm::iterator_range<DeclContext::ddiag_iterator>;
2404
2405 inline ddiag_range ddiags() const;
2406
2407 // Low-level accessors
2408
2409 /// Mark that there are external lexical declarations that we need
2410 /// to include in our lookup table (and that are not available as external
2411 /// visible lookups). These extra lookup results will be found by walking
2412 /// the lexical declarations of this context. This should be used only if
2413 /// setHasExternalLexicalStorage() has been called on any decl context for
2414 /// which this is the primary context.
2415 void setMustBuildLookupTable() {
2416 assert(this == getPrimaryContext() &&(static_cast <bool> (this == getPrimaryContext() &&
"should only be called on primary context") ? void (0) : __assert_fail
("this == getPrimaryContext() && \"should only be called on primary context\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/include/clang/AST/DeclBase.h"
, 2417, __extension__ __PRETTY_FUNCTION__))
2417 "should only be called on primary context")(static_cast <bool> (this == getPrimaryContext() &&
"should only be called on primary context") ? void (0) : __assert_fail
("this == getPrimaryContext() && \"should only be called on primary context\""
, "/build/llvm-toolchain-snapshot-14~++20210825111122+868bd9938db1/clang/include/clang/AST/DeclBase.h"
, 2417, __extension__ __PRETTY_FUNCTION__))
;
2418 DeclContextBits.HasLazyExternalLexicalLookups = true;
2419 }
2420
2421 /// Retrieve the internal representation of the lookup structure.
2422 /// This may omit some names if we are lazily building the structure.
2423 StoredDeclsMap *getLookupPtr() const { return LookupPtr; }
2424
2425 /// Ensure the lookup structure is fully-built and return it.
2426 StoredDeclsMap *buildLookup();
2427
2428 /// Whether this DeclContext has external storage containing
2429 /// additional declarations that are lexically in this context.
2430 bool hasExternalLexicalStorage() const {
2431 return DeclContextBits.ExternalLexicalStorage;
2432 }
2433
2434 /// State whether this DeclContext has external storage for
2435 /// declarations lexically in this context.
2436 void setHasExternalLexicalStorage(bool ES = true) const {
2437 DeclContextBits.ExternalLexicalStorage = ES;
2438 }
2439
2440 /// Whether this DeclContext has external storage containing
2441 /// additional declarations that are visible in this context.
2442 bool hasExternalVisibleStorage() const {
2443 return DeclContextBits.ExternalVisibleStorage;
2444 }
2445
2446 /// State whether this DeclContext has external storage for
2447 /// declarations visible in this context.
2448 void setHasExternalVisibleStorage(bool ES = true) const {
2449 DeclContextBits.ExternalVisibleStorage = ES;
2450 if (ES && LookupPtr)
2451 DeclContextBits.NeedToReconcileExternalVisibleStorage = true;
2452 }
2453
2454 /// Determine whether the given declaration is stored in the list of
2455 /// declarations lexically within this context.
2456 bool isDeclInLexicalTraversal(const Decl *D) const {
2457 return D && (D->NextInContextAndBits.getPointer() || D == FirstDecl ||
2458 D == LastDecl);
2459 }
2460
2461 bool setUseQualifiedLookup(bool use = true) const {
2462 bool old_value = DeclContextBits.UseQualifiedLookup;
2463 DeclContextBits.UseQualifiedLookup = use;
2464 return old_value;
2465 }
2466
2467 bool shouldUseQualifiedLookup() const {
2468 return DeclContextBits.UseQualifiedLookup;
2469 }
2470
2471 static bool classof(const Decl *D);
2472 static bool classof(const DeclContext *D) { return true; }
2473
2474 void dumpDeclContext() const;
2475 void dumpLookups() const;
2476 void dumpLookups(llvm::raw_ostream &OS, bool DumpDecls = false,
2477 bool Deserialize = false) const;
2478
2479private:
2480 /// Whether this declaration context has had externally visible
2481 /// storage added since the last lookup. In this case, \c LookupPtr's
2482 /// invariant may not hold and needs to be fixed before we perform
2483 /// another lookup.
2484 bool hasNeedToReconcileExternalVisibleStorage() const {
2485 return DeclContextBits.NeedToReconcileExternalVisibleStorage;
2486 }
2487
2488 /// State that this declaration context has had externally visible
2489 /// storage added since the last lookup. In this case, \c LookupPtr's
2490 /// invariant may not hold and needs to be fixed before we perform
2491 /// another lookup.
2492 void setNeedToReconcileExternalVisibleStorage(bool Need = true) const {
2493 DeclContextBits.NeedToReconcileExternalVisibleStorage = Need;
2494 }
2495
2496 /// If \c true, this context may have local lexical declarations
2497 /// that are missing from the lookup table.
2498 bool hasLazyLocalLexicalLookups() const {
2499 return DeclContextBits.HasLazyLocalLexicalLookups;
2500 }
2501
2502 /// If \c true, this context may have local lexical declarations
2503 /// that are missing from the lookup table.
2504 void setHasLazyLocalLexicalLookups(bool HasLLLL = true) const {
2505 DeclContextBits.HasLazyLocalLexicalLookups = HasLLLL;
2506 }
2507
2508 /// If \c true, the external source may have lexical declarations
2509 /// that are missing from the lookup table.
2510 bool hasLazyExternalLexicalLookups() const {
2511 return DeclContextBits.HasLazyExternalLexicalLookups;
2512 }
2513
2514 /// If \c true, the external source may have lexical declarations
2515 /// that are missing from the lookup table.
2516 void setHasLazyExternalLexicalLookups(bool HasLELL = true) const {
2517 DeclContextBits.HasLazyExternalLexicalLookups = HasLELL;
2518 }
2519
2520 void reconcileExternalVisibleStorage() const;
2521 bool LoadLexicalDeclsFromExternalStorage() const;
2522
2523 /// Makes a declaration visible within this context, but
2524 /// suppresses searches for external declarations with the same
2525 /// name.
2526 ///
2527 /// Analogous to makeDeclVisibleInContext, but for the exclusive
2528 /// use of addDeclInternal().
2529 void makeDeclVisibleInContextInternal(NamedDecl *D);
2530
2531 StoredDeclsMap *CreateStoredDeclsMap(ASTContext &C) const;
2532
2533 void loadLazyLocalLexicalLookups();
2534 void buildLookupImpl(DeclContext *DCtx, bool Internal);
2535 void makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
2536 bool Rediscoverable);
2537 void makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal);
2538};
2539
2540inline bool Decl::isTemplateParameter() const {
2541 return getKind() == TemplateTypeParm || getKind() == NonTypeTemplateParm ||
2542 getKind() == TemplateTemplateParm;
2543}
2544
2545// Specialization selected when ToTy is not a known subclass of DeclContext.
2546template <class ToTy,
2547 bool IsKnownSubtype = ::std::is_base_of<DeclContext, ToTy>::value>
2548struct cast_convert_decl_context {
2549 static const ToTy *doit(const DeclContext *Val) {
2550 return static_cast<const ToTy*>(Decl::castFromDeclContext(Val));
2551 }
2552
2553 static ToTy *doit(DeclContext *Val) {
2554 return static_cast<ToTy*>(Decl::castFromDeclContext(Val));
2555 }
2556};
2557
2558// Specialization selected when ToTy is a known subclass of DeclContext.
2559template <class ToTy>
2560struct cast_convert_decl_context<ToTy, true> {
2561 static const ToTy *doit(const DeclContext *Val) {
2562 return static_cast<const ToTy*>(Val);
2563 }
2564
2565 static ToTy *doit(DeclContext *Val) {
2566 return static_cast<ToTy*>(Val);
2567 }
2568};
2569
2570} // namespace clang
2571
2572namespace llvm {
2573
2574/// isa<T>(DeclContext*)
2575template <typename To>
2576struct isa_impl<To, ::clang::DeclContext> {
2577 static bool doit(const ::clang::DeclContext &Val) {
2578 return To::classofKind(Val.getDeclKind());
2579 }
2580};
2581
2582/// cast<T>(DeclContext*)
2583template<class ToTy>
2584struct cast_convert_val<ToTy,
2585 const ::clang::DeclContext,const ::clang::DeclContext> {
2586 static const ToTy &doit(const ::clang::DeclContext &Val) {
2587 return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
2588 }
2589};
2590
2591template<class ToTy>
2592struct cast_convert_val<ToTy, ::clang::DeclContext, ::clang::DeclContext> {
2593 static ToTy &doit(::clang::DeclContext &Val) {
2594 return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
2595 }
2596};
2597
2598template<class ToTy>
2599struct cast_convert_val<ToTy,
2600 const ::clang::DeclContext*, const ::clang::DeclContext*> {
2601 static const ToTy *doit(const ::clang::DeclContext *Val) {
2602 return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
2603 }
2604};
2605
2606template<class ToTy>
2607struct cast_convert_val<ToTy, ::clang::DeclContext*, ::clang::DeclContext*> {
2608 static ToTy *doit(::clang::DeclContext *Val) {
2609 return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
2610 }
2611};
2612
2613/// Implement cast_convert_val for Decl -> DeclContext conversions.
2614template<class FromTy>
2615struct cast_convert_val< ::clang::DeclContext, FromTy, FromTy> {
2616 static ::clang::DeclContext &doit(const FromTy &Val) {
2617 return *FromTy::castToDeclContext(&Val);
2618 }
2619};
2620
2621template<class FromTy>
2622struct cast_convert_val< ::clang::DeclContext, FromTy*, FromTy*> {
2623 static ::clang::DeclContext *doit(const FromTy *Val) {
2624 return FromTy::castToDeclContext(Val);
2625 }
2626};
2627
2628template<class FromTy>
2629struct cast_convert_val< const ::clang::DeclContext, FromTy, FromTy> {
2630 static const ::clang::DeclContext &doit(const FromTy &Val) {
2631 return *FromTy::castToDeclContext(&Val);
2632 }
2633};
2634
2635template<class FromTy>
2636struct cast_convert_val< const ::clang::DeclContext, FromTy*, FromTy*> {
2637 static const ::clang::DeclContext *doit(const FromTy *Val) {
2638 return FromTy::castToDeclContext(Val);
2639 }
2640};
2641
2642} // namespace llvm
2643
2644#endif // LLVM_CLANG_AST_DECLBASE_H