Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -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 -fhalf-no-semantic-interposition -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-13~++20210413100635+64c24f493e5f/build-llvm/tools/clang/lib/Sema -resource-dir /usr/lib/llvm-13/lib/clang/13.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-13~++20210413100635+64c24f493e5f/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema -I /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include -I /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/build-llvm/include -I /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/lib/llvm-13/lib/clang/13.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../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-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f=. -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-04-14-063029-18377-1 -x c++ /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp

/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/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 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
438 (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
439 if (!IIDecl || (*Res)->getLocation() < IIDecl->getLocation())
440 IIDecl = *Res;
441 }
442 }
443
444 if (!IIDecl) {
445 // None of the entities we found is a type, so there is no way
446 // to even assume that the result is a type. In this case, don't
447 // complain about the ambiguity. The parser will either try to
448 // perform this lookup again (e.g., as an object name), which
449 // will produce the ambiguity, or will complain that it expected
450 // a type name.
451 Result.suppressDiagnostics();
452 return nullptr;
453 }
454
455 // We found a type within the ambiguous lookup; diagnose the
456 // ambiguity and then return that type. This might be the right
457 // answer, or it might not be, but it suppresses any attempt to
458 // perform the name lookup again.
459 break;
460
461 case LookupResult::Found:
462 IIDecl = Result.getFoundDecl();
463 break;
464 }
465
466 assert(IIDecl && "Didn't find decl")((IIDecl && "Didn't find decl") ? static_cast<void
> (0) : __assert_fail ("IIDecl && \"Didn't find decl\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 466, __PRETTY_FUNCTION__))
;
467
468 QualType T;
469 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
470 // C++ [class.qual]p2: A lookup that would find the injected-class-name
471 // instead names the constructors of the class, except when naming a class.
472 // This is ill-formed when we're not actually forming a ctor or dtor name.
473 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
474 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
475 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
476 FoundRD->isInjectedClassName() &&
477 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
478 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
479 << &II << /*Type*/1;
480
481 DiagnoseUseOfDecl(IIDecl, NameLoc);
482
483 T = Context.getTypeDeclType(TD);
484 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
485 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
486 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
487 if (!HasTrailingDot)
488 T = Context.getObjCInterfaceType(IDecl);
489 } else if (AllowDeducedTemplate) {
490 if (auto *TD = getAsTypeTemplateDecl(IIDecl))
491 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
492 QualType(), false);
493 }
494
495 if (T.isNull()) {
496 // If it's not plausibly a type, suppress diagnostics.
497 Result.suppressDiagnostics();
498 return nullptr;
499 }
500
501 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
502 // constructor or destructor name (in such a case, the scope specifier
503 // will be attached to the enclosing Expr or Decl node).
504 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
505 !isa<ObjCInterfaceDecl>(IIDecl)) {
506 if (WantNontrivialTypeSourceInfo) {
507 // Construct a type with type-source information.
508 TypeLocBuilder Builder;
509 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
510
511 T = getElaboratedType(ETK_None, *SS, T);
512 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
513 ElabTL.setElaboratedKeywordLoc(SourceLocation());
514 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
515 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
516 } else {
517 T = getElaboratedType(ETK_None, *SS, T);
518 }
519 }
520
521 return ParsedType::make(T);
522}
523
524// Builds a fake NNS for the given decl context.
525static NestedNameSpecifier *
526synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
527 for (;; DC = DC->getLookupParent()) {
528 DC = DC->getPrimaryContext();
529 auto *ND = dyn_cast<NamespaceDecl>(DC);
530 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
531 return NestedNameSpecifier::Create(Context, nullptr, ND);
532 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
533 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
534 RD->getTypeForDecl());
535 else if (isa<TranslationUnitDecl>(DC))
536 return NestedNameSpecifier::GlobalSpecifier(Context);
537 }
538 llvm_unreachable("something isn't in TU scope?")::llvm::llvm_unreachable_internal("something isn't in TU scope?"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 538)
;
539}
540
541/// Find the parent class with dependent bases of the innermost enclosing method
542/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
543/// up allowing unqualified dependent type names at class-level, which MSVC
544/// correctly rejects.
545static const CXXRecordDecl *
546findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
547 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
548 DC = DC->getPrimaryContext();
549 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
550 if (MD->getParent()->hasAnyDependentBases())
551 return MD->getParent();
552 }
553 return nullptr;
554}
555
556ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
557 SourceLocation NameLoc,
558 bool IsTemplateTypeArg) {
559 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode")((getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().MSVCCompat && \"shouldn't be called in non-MSVC mode\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 559, __PRETTY_FUNCTION__))
;
560
561 NestedNameSpecifier *NNS = nullptr;
562 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
563 // If we weren't able to parse a default template argument, delay lookup
564 // until instantiation time by making a non-dependent DependentTypeName. We
565 // pretend we saw a NestedNameSpecifier referring to the current scope, and
566 // lookup is retried.
567 // FIXME: This hurts our diagnostic quality, since we get errors like "no
568 // type named 'Foo' in 'current_namespace'" when the user didn't write any
569 // name specifiers.
570 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
571 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
572 } else if (const CXXRecordDecl *RD =
573 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
574 // Build a DependentNameType that will perform lookup into RD at
575 // instantiation time.
576 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
577 RD->getTypeForDecl());
578
579 // Diagnose that this identifier was undeclared, and retry the lookup during
580 // template instantiation.
581 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
582 << RD;
583 } else {
584 // This is not a situation that we should recover from.
585 return ParsedType();
586 }
587
588 QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
589
590 // Build type location information. We synthesized the qualifier, so we have
591 // to build a fake NestedNameSpecifierLoc.
592 NestedNameSpecifierLocBuilder NNSLocBuilder;
593 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
594 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
595
596 TypeLocBuilder Builder;
597 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
598 DepTL.setNameLoc(NameLoc);
599 DepTL.setElaboratedKeywordLoc(SourceLocation());
600 DepTL.setQualifierLoc(QualifierLoc);
601 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
602}
603
604/// isTagName() - This method is called *for error recovery purposes only*
605/// to determine if the specified name is a valid tag name ("struct foo"). If
606/// so, this returns the TST for the tag corresponding to it (TST_enum,
607/// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
608/// cases in C where the user forgot to specify the tag.
609DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
610 // Do a tag name lookup in this scope.
611 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
612 LookupName(R, S, false);
613 R.suppressDiagnostics();
614 if (R.getResultKind() == LookupResult::Found)
615 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
616 switch (TD->getTagKind()) {
617 case TTK_Struct: return DeclSpec::TST_struct;
618 case TTK_Interface: return DeclSpec::TST_interface;
619 case TTK_Union: return DeclSpec::TST_union;
620 case TTK_Class: return DeclSpec::TST_class;
621 case TTK_Enum: return DeclSpec::TST_enum;
622 }
623 }
624
625 return DeclSpec::TST_unspecified;
626}
627
628/// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
629/// if a CXXScopeSpec's type is equal to the type of one of the base classes
630/// then downgrade the missing typename error to a warning.
631/// This is needed for MSVC compatibility; Example:
632/// @code
633/// template<class T> class A {
634/// public:
635/// typedef int TYPE;
636/// };
637/// template<class T> class B : public A<T> {
638/// public:
639/// A<T>::TYPE a; // no typename required because A<T> is a base class.
640/// };
641/// @endcode
642bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
643 if (CurContext->isRecord()) {
644 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
645 return true;
646
647 const Type *Ty = SS->getScopeRep()->getAsType();
648
649 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
650 for (const auto &Base : RD->bases())
651 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
652 return true;
653 return S->isFunctionPrototypeScope();
654 }
655 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
656}
657
658void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
659 SourceLocation IILoc,
660 Scope *S,
661 CXXScopeSpec *SS,
662 ParsedType &SuggestedType,
663 bool IsTemplateName) {
664 // Don't report typename errors for editor placeholders.
665 if (II->isEditorPlaceholder())
666 return;
667 // We don't have anything to suggest (yet).
668 SuggestedType = nullptr;
669
670 // There may have been a typo in the name of the type. Look up typo
671 // results, in case we have something that we can suggest.
672 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
673 /*AllowTemplates=*/IsTemplateName,
674 /*AllowNonTemplates=*/!IsTemplateName);
675 if (TypoCorrection Corrected =
676 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
677 CCC, CTK_ErrorRecovery)) {
678 // FIXME: Support error recovery for the template-name case.
679 bool CanRecover = !IsTemplateName;
680 if (Corrected.isKeyword()) {
681 // We corrected to a keyword.
682 diagnoseTypo(Corrected,
683 PDiag(IsTemplateName ? diag::err_no_template_suggest
684 : diag::err_unknown_typename_suggest)
685 << II);
686 II = Corrected.getCorrectionAsIdentifierInfo();
687 } else {
688 // We found a similarly-named type or interface; suggest that.
689 if (!SS || !SS->isSet()) {
690 diagnoseTypo(Corrected,
691 PDiag(IsTemplateName ? diag::err_no_template_suggest
692 : diag::err_unknown_typename_suggest)
693 << II, CanRecover);
694 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
695 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
696 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
697 II->getName().equals(CorrectedStr);
698 diagnoseTypo(Corrected,
699 PDiag(IsTemplateName
700 ? diag::err_no_member_template_suggest
701 : diag::err_unknown_nested_typename_suggest)
702 << II << DC << DroppedSpecifier << SS->getRange(),
703 CanRecover);
704 } else {
705 llvm_unreachable("could not have corrected a typo here")::llvm::llvm_unreachable_internal("could not have corrected a typo here"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 705)
;
706 }
707
708 if (!CanRecover)
709 return;
710
711 CXXScopeSpec tmpSS;
712 if (Corrected.getCorrectionSpecifier())
713 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
714 SourceRange(IILoc));
715 // FIXME: Support class template argument deduction here.
716 SuggestedType =
717 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
718 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
719 /*IsCtorOrDtorName=*/false,
720 /*WantNontrivialTypeSourceInfo=*/true);
721 }
722 return;
723 }
724
725 if (getLangOpts().CPlusPlus && !IsTemplateName) {
726 // See if II is a class template that the user forgot to pass arguments to.
727 UnqualifiedId Name;
728 Name.setIdentifier(II, IILoc);
729 CXXScopeSpec EmptySS;
730 TemplateTy TemplateResult;
731 bool MemberOfUnknownSpecialization;
732 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
733 Name, nullptr, true, TemplateResult,
734 MemberOfUnknownSpecialization) == TNK_Type_template) {
735 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
736 return;
737 }
738 }
739
740 // FIXME: Should we move the logic that tries to recover from a missing tag
741 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
742
743 if (!SS || (!SS->isSet() && !SS->isInvalid()))
744 Diag(IILoc, IsTemplateName ? diag::err_no_template
745 : diag::err_unknown_typename)
746 << II;
747 else if (DeclContext *DC = computeDeclContext(*SS, false))
748 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
749 : diag::err_typename_nested_not_found)
750 << II << DC << SS->getRange();
751 else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
752 SuggestedType =
753 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
754 } else if (isDependentScopeSpecifier(*SS)) {
755 unsigned DiagID = diag::err_typename_missing;
756 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
757 DiagID = diag::ext_typename_missing;
758
759 Diag(SS->getRange().getBegin(), DiagID)
760 << SS->getScopeRep() << II->getName()
761 << SourceRange(SS->getRange().getBegin(), IILoc)
762 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
763 SuggestedType = ActOnTypenameType(S, SourceLocation(),
764 *SS, *II, IILoc).get();
765 } else {
766 assert(SS && SS->isInvalid() &&((SS && SS->isInvalid() && "Invalid scope specifier has already been diagnosed"
) ? static_cast<void> (0) : __assert_fail ("SS && SS->isInvalid() && \"Invalid scope specifier has already been diagnosed\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 767, __PRETTY_FUNCTION__))
767 "Invalid scope specifier has already been diagnosed")((SS && SS->isInvalid() && "Invalid scope specifier has already been diagnosed"
) ? static_cast<void> (0) : __assert_fail ("SS && SS->isInvalid() && \"Invalid scope specifier has already been diagnosed\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 767, __PRETTY_FUNCTION__))
;
768 }
769}
770
771/// Determine whether the given result set contains either a type name
772/// or
773static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
774 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
775 NextToken.is(tok::less);
776
777 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
778 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
779 return true;
780
781 if (CheckTemplate && isa<TemplateDecl>(*I))
782 return true;
783 }
784
785 return false;
786}
787
788static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
789 Scope *S, CXXScopeSpec &SS,
790 IdentifierInfo *&Name,
791 SourceLocation NameLoc) {
792 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
793 SemaRef.LookupParsedName(R, S, &SS);
794 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
795 StringRef FixItTagName;
796 switch (Tag->getTagKind()) {
797 case TTK_Class:
798 FixItTagName = "class ";
799 break;
800
801 case TTK_Enum:
802 FixItTagName = "enum ";
803 break;
804
805 case TTK_Struct:
806 FixItTagName = "struct ";
807 break;
808
809 case TTK_Interface:
810 FixItTagName = "__interface ";
811 break;
812
813 case TTK_Union:
814 FixItTagName = "union ";
815 break;
816 }
817
818 StringRef TagName = FixItTagName.drop_back();
819 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
820 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
821 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
822
823 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
824 I != IEnd; ++I)
825 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
826 << Name << TagName;
827
828 // Replace lookup results with just the tag decl.
829 Result.clear(Sema::LookupTagName);
830 SemaRef.LookupParsedName(Result, S, &SS);
831 return true;
832 }
833
834 return false;
835}
836
837/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
838static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
839 QualType T, SourceLocation NameLoc) {
840 ASTContext &Context = S.Context;
841
842 TypeLocBuilder Builder;
843 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
844
845 T = S.getElaboratedType(ETK_None, SS, T);
846 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
847 ElabTL.setElaboratedKeywordLoc(SourceLocation());
848 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
849 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
850}
851
852Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
853 IdentifierInfo *&Name,
854 SourceLocation NameLoc,
855 const Token &NextToken,
856 CorrectionCandidateCallback *CCC) {
857 DeclarationNameInfo NameInfo(Name, NameLoc);
858 ObjCMethodDecl *CurMethod = getCurMethodDecl();
859
860 assert(NextToken.isNot(tok::coloncolon) &&((NextToken.isNot(tok::coloncolon) && "parse nested name specifiers before calling ClassifyName"
) ? static_cast<void> (0) : __assert_fail ("NextToken.isNot(tok::coloncolon) && \"parse nested name specifiers before calling ClassifyName\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 861, __PRETTY_FUNCTION__))
861 "parse nested name specifiers before calling ClassifyName")((NextToken.isNot(tok::coloncolon) && "parse nested name specifiers before calling ClassifyName"
) ? static_cast<void> (0) : __assert_fail ("NextToken.isNot(tok::coloncolon) && \"parse nested name specifiers before calling ClassifyName\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 861, __PRETTY_FUNCTION__))
;
862 if (getLangOpts().CPlusPlus && SS.isSet() &&
863 isCurrentClassName(*Name, S, &SS)) {
864 // Per [class.qual]p2, this names the constructors of SS, not the
865 // injected-class-name. We don't have a classification for that.
866 // There's not much point caching this result, since the parser
867 // will reject it later.
868 return NameClassification::Unknown();
869 }
870
871 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
872 LookupParsedName(Result, S, &SS, !CurMethod);
873
874 if (SS.isInvalid())
875 return NameClassification::Error();
876
877 // For unqualified lookup in a class template in MSVC mode, look into
878 // dependent base classes where the primary class template is known.
879 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
880 if (ParsedType TypeInBase =
881 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
882 return TypeInBase;
883 }
884
885 // Perform lookup for Objective-C instance variables (including automatically
886 // synthesized instance variables), if we're in an Objective-C method.
887 // FIXME: This lookup really, really needs to be folded in to the normal
888 // unqualified lookup mechanism.
889 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
890 DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
891 if (Ivar.isInvalid())
892 return NameClassification::Error();
893 if (Ivar.isUsable())
894 return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
895
896 // We defer builtin creation until after ivar lookup inside ObjC methods.
897 if (Result.empty())
898 LookupBuiltin(Result);
899 }
900
901 bool SecondTry = false;
902 bool IsFilteredTemplateName = false;
903
904Corrected:
905 switch (Result.getResultKind()) {
906 case LookupResult::NotFound:
907 // If an unqualified-id is followed by a '(', then we have a function
908 // call.
909 if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
910 // In C++, this is an ADL-only call.
911 // FIXME: Reference?
912 if (getLangOpts().CPlusPlus)
913 return NameClassification::UndeclaredNonType();
914
915 // C90 6.3.2.2:
916 // If the expression that precedes the parenthesized argument list in a
917 // function call consists solely of an identifier, and if no
918 // declaration is visible for this identifier, the identifier is
919 // implicitly declared exactly as if, in the innermost block containing
920 // the function call, the declaration
921 //
922 // extern int identifier ();
923 //
924 // appeared.
925 //
926 // We also allow this in C99 as an extension.
927 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
928 return NameClassification::NonType(D);
929 }
930
931 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
932 // In C++20 onwards, this could be an ADL-only call to a function
933 // template, and we're required to assume that this is a template name.
934 //
935 // FIXME: Find a way to still do typo correction in this case.
936 TemplateName Template =
937 Context.getAssumedTemplateName(NameInfo.getName());
938 return NameClassification::UndeclaredTemplate(Template);
939 }
940
941 // In C, we first see whether there is a tag type by the same name, in
942 // which case it's likely that the user just forgot to write "enum",
943 // "struct", or "union".
944 if (!getLangOpts().CPlusPlus && !SecondTry &&
945 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
946 break;
947 }
948
949 // Perform typo correction to determine if there is another name that is
950 // close to this name.
951 if (!SecondTry && CCC) {
952 SecondTry = true;
953 if (TypoCorrection Corrected =
954 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
955 &SS, *CCC, CTK_ErrorRecovery)) {
956 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
957 unsigned QualifiedDiag = diag::err_no_member_suggest;
958
959 NamedDecl *FirstDecl = Corrected.getFoundDecl();
960 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
961 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
962 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
963 UnqualifiedDiag = diag::err_no_template_suggest;
964 QualifiedDiag = diag::err_no_member_template_suggest;
965 } else if (UnderlyingFirstDecl &&
966 (isa<TypeDecl>(UnderlyingFirstDecl) ||
967 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
968 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
969 UnqualifiedDiag = diag::err_unknown_typename_suggest;
970 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
971 }
972
973 if (SS.isEmpty()) {
974 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
975 } else {// FIXME: is this even reachable? Test it.
976 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
977 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
978 Name->getName().equals(CorrectedStr);
979 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
980 << Name << computeDeclContext(SS, false)
981 << DroppedSpecifier << SS.getRange());
982 }
983
984 // Update the name, so that the caller has the new name.
985 Name = Corrected.getCorrectionAsIdentifierInfo();
986
987 // Typo correction corrected to a keyword.
988 if (Corrected.isKeyword())
989 return Name;
990
991 // Also update the LookupResult...
992 // FIXME: This should probably go away at some point
993 Result.clear();
994 Result.setLookupName(Corrected.getCorrection());
995 if (FirstDecl)
996 Result.addDecl(FirstDecl);
997
998 // If we found an Objective-C instance variable, let
999 // LookupInObjCMethod build the appropriate expression to
1000 // reference the ivar.
1001 // FIXME: This is a gross hack.
1002 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1003 DeclResult R =
1004 LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1005 if (R.isInvalid())
1006 return NameClassification::Error();
1007 if (R.isUsable())
1008 return NameClassification::NonType(Ivar);
1009 }
1010
1011 goto Corrected;
1012 }
1013 }
1014
1015 // We failed to correct; just fall through and let the parser deal with it.
1016 Result.suppressDiagnostics();
1017 return NameClassification::Unknown();
1018
1019 case LookupResult::NotFoundInCurrentInstantiation: {
1020 // We performed name lookup into the current instantiation, and there were
1021 // dependent bases, so we treat this result the same way as any other
1022 // dependent nested-name-specifier.
1023
1024 // C++ [temp.res]p2:
1025 // A name used in a template declaration or definition and that is
1026 // dependent on a template-parameter is assumed not to name a type
1027 // unless the applicable name lookup finds a type name or the name is
1028 // qualified by the keyword typename.
1029 //
1030 // FIXME: If the next token is '<', we might want to ask the parser to
1031 // perform some heroics to see if we actually have a
1032 // template-argument-list, which would indicate a missing 'template'
1033 // keyword here.
1034 return NameClassification::DependentNonType();
1035 }
1036
1037 case LookupResult::Found:
1038 case LookupResult::FoundOverloaded:
1039 case LookupResult::FoundUnresolvedValue:
1040 break;
1041
1042 case LookupResult::Ambiguous:
1043 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1044 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1045 /*AllowDependent=*/false)) {
1046 // C++ [temp.local]p3:
1047 // A lookup that finds an injected-class-name (10.2) can result in an
1048 // ambiguity in certain cases (for example, if it is found in more than
1049 // one base class). If all of the injected-class-names that are found
1050 // refer to specializations of the same class template, and if the name
1051 // is followed by a template-argument-list, the reference refers to the
1052 // class template itself and not a specialization thereof, and is not
1053 // ambiguous.
1054 //
1055 // This filtering can make an ambiguous result into an unambiguous one,
1056 // so try again after filtering out template names.
1057 FilterAcceptableTemplateNames(Result);
1058 if (!Result.isAmbiguous()) {
1059 IsFilteredTemplateName = true;
1060 break;
1061 }
1062 }
1063
1064 // Diagnose the ambiguity and return an error.
1065 return NameClassification::Error();
1066 }
1067
1068 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1069 (IsFilteredTemplateName ||
1070 hasAnyAcceptableTemplateNames(
1071 Result, /*AllowFunctionTemplates=*/true,
1072 /*AllowDependent=*/false,
1073 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1074 getLangOpts().CPlusPlus20))) {
1075 // C++ [temp.names]p3:
1076 // After name lookup (3.4) finds that a name is a template-name or that
1077 // an operator-function-id or a literal- operator-id refers to a set of
1078 // overloaded functions any member of which is a function template if
1079 // this is followed by a <, the < is always taken as the delimiter of a
1080 // template-argument-list and never as the less-than operator.
1081 // C++2a [temp.names]p2:
1082 // A name is also considered to refer to a template if it is an
1083 // unqualified-id followed by a < and name lookup finds either one
1084 // or more functions or finds nothing.
1085 if (!IsFilteredTemplateName)
1086 FilterAcceptableTemplateNames(Result);
1087
1088 bool IsFunctionTemplate;
1089 bool IsVarTemplate;
1090 TemplateName Template;
1091 if (Result.end() - Result.begin() > 1) {
1092 IsFunctionTemplate = true;
1093 Template = Context.getOverloadedTemplateName(Result.begin(),
1094 Result.end());
1095 } else if (!Result.empty()) {
1096 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1097 *Result.begin(), /*AllowFunctionTemplates=*/true,
1098 /*AllowDependent=*/false));
1099 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1100 IsVarTemplate = isa<VarTemplateDecl>(TD);
1101
1102 if (SS.isNotEmpty())
1103 Template =
1104 Context.getQualifiedTemplateName(SS.getScopeRep(),
1105 /*TemplateKeyword=*/false, TD);
1106 else
1107 Template = TemplateName(TD);
1108 } else {
1109 // All results were non-template functions. This is a function template
1110 // name.
1111 IsFunctionTemplate = true;
1112 Template = Context.getAssumedTemplateName(NameInfo.getName());
1113 }
1114
1115 if (IsFunctionTemplate) {
1116 // Function templates always go through overload resolution, at which
1117 // point we'll perform the various checks (e.g., accessibility) we need
1118 // to based on which function we selected.
1119 Result.suppressDiagnostics();
1120
1121 return NameClassification::FunctionTemplate(Template);
1122 }
1123
1124 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1125 : NameClassification::TypeTemplate(Template);
1126 }
1127
1128 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1129 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1130 DiagnoseUseOfDecl(Type, NameLoc);
1131 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1132 QualType T = Context.getTypeDeclType(Type);
1133 if (SS.isNotEmpty())
1134 return buildNestedType(*this, SS, T, NameLoc);
1135 return ParsedType::make(T);
1136 }
1137
1138 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1139 if (!Class) {
1140 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1141 if (ObjCCompatibleAliasDecl *Alias =
1142 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1143 Class = Alias->getClassInterface();
1144 }
1145
1146 if (Class) {
1147 DiagnoseUseOfDecl(Class, NameLoc);
1148
1149 if (NextToken.is(tok::period)) {
1150 // Interface. <something> is parsed as a property reference expression.
1151 // Just return "unknown" as a fall-through for now.
1152 Result.suppressDiagnostics();
1153 return NameClassification::Unknown();
1154 }
1155
1156 QualType T = Context.getObjCInterfaceType(Class);
1157 return ParsedType::make(T);
1158 }
1159
1160 if (isa<ConceptDecl>(FirstDecl))
1161 return NameClassification::Concept(
1162 TemplateName(cast<TemplateDecl>(FirstDecl)));
1163
1164 // We can have a type template here if we're classifying a template argument.
1165 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1166 !isa<VarTemplateDecl>(FirstDecl))
1167 return NameClassification::TypeTemplate(
1168 TemplateName(cast<TemplateDecl>(FirstDecl)));
1169
1170 // Check for a tag type hidden by a non-type decl in a few cases where it
1171 // seems likely a type is wanted instead of the non-type that was found.
1172 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1173 if ((NextToken.is(tok::identifier) ||
1174 (NextIsOp &&
1175 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1176 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1177 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1178 DiagnoseUseOfDecl(Type, NameLoc);
1179 QualType T = Context.getTypeDeclType(Type);
1180 if (SS.isNotEmpty())
1181 return buildNestedType(*this, SS, T, NameLoc);
1182 return ParsedType::make(T);
1183 }
1184
1185 // If we already know which single declaration is referenced, just annotate
1186 // that declaration directly. Defer resolving even non-overloaded class
1187 // member accesses, as we need to defer certain access checks until we know
1188 // the context.
1189 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1190 if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember())
1191 return NameClassification::NonType(Result.getRepresentativeDecl());
1192
1193 // Otherwise, this is an overload set that we will need to resolve later.
1194 Result.suppressDiagnostics();
1195 return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1196 Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1197 Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
1198 Result.begin(), Result.end()));
1199}
1200
1201ExprResult
1202Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1203 SourceLocation NameLoc) {
1204 assert(getLangOpts().CPlusPlus && "ADL-only call in C?")((getLangOpts().CPlusPlus && "ADL-only call in C?") ?
static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"ADL-only call in C?\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 1204, __PRETTY_FUNCTION__))
;
1205 CXXScopeSpec SS;
1206 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1207 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1208}
1209
1210ExprResult
1211Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1212 IdentifierInfo *Name,
1213 SourceLocation NameLoc,
1214 bool IsAddressOfOperand) {
1215 DeclarationNameInfo NameInfo(Name, NameLoc);
1216 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1217 NameInfo, IsAddressOfOperand,
1218 /*TemplateArgs=*/nullptr);
1219}
1220
1221ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1222 NamedDecl *Found,
1223 SourceLocation NameLoc,
1224 const Token &NextToken) {
1225 if (getCurMethodDecl() && SS.isEmpty())
1226 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1227 return BuildIvarRefExpr(S, NameLoc, Ivar);
1228
1229 // Reconstruct the lookup result.
1230 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1231 Result.addDecl(Found);
1232 Result.resolveKind();
1233
1234 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1235 return BuildDeclarationNameExpr(SS, Result, ADL);
1236}
1237
1238ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1239 // For an implicit class member access, transform the result into a member
1240 // access expression if necessary.
1241 auto *ULE = cast<UnresolvedLookupExpr>(E);
1242 if ((*ULE->decls_begin())->isCXXClassMember()) {
1243 CXXScopeSpec SS;
1244 SS.Adopt(ULE->getQualifierLoc());
1245
1246 // Reconstruct the lookup result.
1247 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1248 LookupOrdinaryName);
1249 Result.setNamingClass(ULE->getNamingClass());
1250 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1251 Result.addDecl(*I, I.getAccess());
1252 Result.resolveKind();
1253 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1254 nullptr, S);
1255 }
1256
1257 // Otherwise, this is already in the form we needed, and no further checks
1258 // are necessary.
1259 return ULE;
1260}
1261
1262Sema::TemplateNameKindForDiagnostics
1263Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1264 auto *TD = Name.getAsTemplateDecl();
1265 if (!TD)
1266 return TemplateNameKindForDiagnostics::DependentTemplate;
1267 if (isa<ClassTemplateDecl>(TD))
1268 return TemplateNameKindForDiagnostics::ClassTemplate;
1269 if (isa<FunctionTemplateDecl>(TD))
1270 return TemplateNameKindForDiagnostics::FunctionTemplate;
1271 if (isa<VarTemplateDecl>(TD))
1272 return TemplateNameKindForDiagnostics::VarTemplate;
1273 if (isa<TypeAliasTemplateDecl>(TD))
1274 return TemplateNameKindForDiagnostics::AliasTemplate;
1275 if (isa<TemplateTemplateParmDecl>(TD))
1276 return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1277 if (isa<ConceptDecl>(TD))
1278 return TemplateNameKindForDiagnostics::Concept;
1279 return TemplateNameKindForDiagnostics::DependentTemplate;
1280}
1281
1282void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1283 assert(DC->getLexicalParent() == CurContext &&((DC->getLexicalParent() == CurContext && "The next DeclContext should be lexically contained in the current one."
) ? static_cast<void> (0) : __assert_fail ("DC->getLexicalParent() == CurContext && \"The next DeclContext should be lexically contained in the current one.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 1284, __PRETTY_FUNCTION__))
1284 "The next DeclContext should be lexically contained in the current one.")((DC->getLexicalParent() == CurContext && "The next DeclContext should be lexically contained in the current one."
) ? static_cast<void> (0) : __assert_fail ("DC->getLexicalParent() == CurContext && \"The next DeclContext should be lexically contained in the current one.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 1284, __PRETTY_FUNCTION__))
;
1285 CurContext = DC;
1286 S->setEntity(DC);
1287}
1288
1289void Sema::PopDeclContext() {
1290 assert(CurContext && "DeclContext imbalance!")((CurContext && "DeclContext imbalance!") ? static_cast
<void> (0) : __assert_fail ("CurContext && \"DeclContext imbalance!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 1290, __PRETTY_FUNCTION__))
;
1291
1292 CurContext = CurContext->getLexicalParent();
1293 assert(CurContext && "Popped translation unit!")((CurContext && "Popped translation unit!") ? static_cast
<void> (0) : __assert_fail ("CurContext && \"Popped translation unit!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 1293, __PRETTY_FUNCTION__))
;
1294}
1295
1296Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1297 Decl *D) {
1298 // Unlike PushDeclContext, the context to which we return is not necessarily
1299 // the containing DC of TD, because the new context will be some pre-existing
1300 // TagDecl definition instead of a fresh one.
1301 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1302 CurContext = cast<TagDecl>(D)->getDefinition();
1303 assert(CurContext && "skipping definition of undefined tag")((CurContext && "skipping definition of undefined tag"
) ? static_cast<void> (0) : __assert_fail ("CurContext && \"skipping definition of undefined tag\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 1303, __PRETTY_FUNCTION__))
;
1304 // Start lookups from the parent of the current context; we don't want to look
1305 // into the pre-existing complete definition.
1306 S->setEntity(CurContext->getLookupParent());
1307 return Result;
1308}
1309
1310void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1311 CurContext = static_cast<decltype(CurContext)>(Context);
1312}
1313
1314/// EnterDeclaratorContext - Used when we must lookup names in the context
1315/// of a declarator's nested name specifier.
1316///
1317void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1318 // C++0x [basic.lookup.unqual]p13:
1319 // A name used in the definition of a static data member of class
1320 // X (after the qualified-id of the static member) is looked up as
1321 // if the name was used in a member function of X.
1322 // C++0x [basic.lookup.unqual]p14:
1323 // If a variable member of a namespace is defined outside of the
1324 // scope of its namespace then any name used in the definition of
1325 // the variable member (after the declarator-id) is looked up as
1326 // if the definition of the variable member occurred in its
1327 // namespace.
1328 // Both of these imply that we should push a scope whose context
1329 // is the semantic context of the declaration. We can't use
1330 // PushDeclContext here because that context is not necessarily
1331 // lexically contained in the current context. Fortunately,
1332 // the containing scope should have the appropriate information.
1333
1334 assert(!S->getEntity() && "scope already has entity")((!S->getEntity() && "scope already has entity") ?
static_cast<void> (0) : __assert_fail ("!S->getEntity() && \"scope already has entity\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 1334, __PRETTY_FUNCTION__))
;
1335
1336#ifndef NDEBUG
1337 Scope *Ancestor = S->getParent();
1338 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1339 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch")((Ancestor->getEntity() == CurContext && "ancestor context mismatch"
) ? static_cast<void> (0) : __assert_fail ("Ancestor->getEntity() == CurContext && \"ancestor context mismatch\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 1339, __PRETTY_FUNCTION__))
;
1340#endif
1341
1342 CurContext = DC;
1343 S->setEntity(DC);
1344
1345 if (S->getParent()->isTemplateParamScope()) {
1346 // Also set the corresponding entities for all immediately-enclosing
1347 // template parameter scopes.
1348 EnterTemplatedContext(S->getParent(), DC);
1349 }
1350}
1351
1352void Sema::ExitDeclaratorContext(Scope *S) {
1353 assert(S->getEntity() == CurContext && "Context imbalance!")((S->getEntity() == CurContext && "Context imbalance!"
) ? static_cast<void> (0) : __assert_fail ("S->getEntity() == CurContext && \"Context imbalance!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 1353, __PRETTY_FUNCTION__))
;
1354
1355 // Switch back to the lexical context. The safety of this is
1356 // enforced by an assert in EnterDeclaratorContext.
1357 Scope *Ancestor = S->getParent();
1358 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1359 CurContext = Ancestor->getEntity();
1360
1361 // We don't need to do anything with the scope, which is going to
1362 // disappear.
1363}
1364
1365void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1366 assert(S->isTemplateParamScope() &&((S->isTemplateParamScope() && "expected to be initializing a template parameter scope"
) ? static_cast<void> (0) : __assert_fail ("S->isTemplateParamScope() && \"expected to be initializing a template parameter scope\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 1367, __PRETTY_FUNCTION__))
1367 "expected to be initializing a template parameter scope")((S->isTemplateParamScope() && "expected to be initializing a template parameter scope"
) ? static_cast<void> (0) : __assert_fail ("S->isTemplateParamScope() && \"expected to be initializing a template parameter scope\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 1367, __PRETTY_FUNCTION__))
;
1368
1369 // C++20 [temp.local]p7:
1370 // In the definition of a member of a class template that appears outside
1371 // of the class template definition, the name of a member of the class
1372 // template hides the name of a template-parameter of any enclosing class
1373 // templates (but not a template-parameter of the member if the member is a
1374 // class or function template).
1375 // C++20 [temp.local]p9:
1376 // In the definition of a class template or in the definition of a member
1377 // of such a template that appears outside of the template definition, for
1378 // each non-dependent base class (13.8.2.1), if the name of the base class
1379 // or the name of a member of the base class is the same as the name of a
1380 // template-parameter, the base class name or member name hides the
1381 // template-parameter name (6.4.10).
1382 //
1383 // This means that a template parameter scope should be searched immediately
1384 // after searching the DeclContext for which it is a template parameter
1385 // scope. For example, for
1386 // template<typename T> template<typename U> template<typename V>
1387 // void N::A<T>::B<U>::f(...)
1388 // we search V then B<U> (and base classes) then U then A<T> (and base
1389 // classes) then T then N then ::.
1390 unsigned ScopeDepth = getTemplateDepth(S);
1391 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1392 DeclContext *SearchDCAfterScope = DC;
1393 for (; DC; DC = DC->getLookupParent()) {
1394 if (const TemplateParameterList *TPL =
1395 cast<Decl>(DC)->getDescribedTemplateParams()) {
1396 unsigned DCDepth = TPL->getDepth() + 1;
1397 if (DCDepth > ScopeDepth)
1398 continue;
1399 if (ScopeDepth == DCDepth)
1400 SearchDCAfterScope = DC = DC->getLookupParent();
1401 break;
1402 }
1403 }
1404 S->setLookupEntity(SearchDCAfterScope);
1405 }
1406}
1407
1408void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1409 // We assume that the caller has already called
1410 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1411 FunctionDecl *FD = D->getAsFunction();
1412 if (!FD)
1413 return;
1414
1415 // Same implementation as PushDeclContext, but enters the context
1416 // from the lexical parent, rather than the top-level class.
1417 assert(CurContext == FD->getLexicalParent() &&((CurContext == FD->getLexicalParent() && "The next DeclContext should be lexically contained in the current one."
) ? static_cast<void> (0) : __assert_fail ("CurContext == FD->getLexicalParent() && \"The next DeclContext should be lexically contained in the current one.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 1418, __PRETTY_FUNCTION__))
1418 "The next DeclContext should be lexically contained in the current one.")((CurContext == FD->getLexicalParent() && "The next DeclContext should be lexically contained in the current one."
) ? static_cast<void> (0) : __assert_fail ("CurContext == FD->getLexicalParent() && \"The next DeclContext should be lexically contained in the current one.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 1418, __PRETTY_FUNCTION__))
;
1419 CurContext = FD;
1420 S->setEntity(CurContext);
1421
1422 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1423 ParmVarDecl *Param = FD->getParamDecl(P);
1424 // If the parameter has an identifier, then add it to the scope
1425 if (Param->getIdentifier()) {
1426 S->AddDecl(Param);
1427 IdResolver.AddDecl(Param);
1428 }
1429 }
1430}
1431
1432void Sema::ActOnExitFunctionContext() {
1433 // Same implementation as PopDeclContext, but returns to the lexical parent,
1434 // rather than the top-level class.
1435 assert(CurContext && "DeclContext imbalance!")((CurContext && "DeclContext imbalance!") ? static_cast
<void> (0) : __assert_fail ("CurContext && \"DeclContext imbalance!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 1435, __PRETTY_FUNCTION__))
;
1436 CurContext = CurContext->getLexicalParent();
1437 assert(CurContext && "Popped translation unit!")((CurContext && "Popped translation unit!") ? static_cast
<void> (0) : __assert_fail ("CurContext && \"Popped translation unit!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 1437, __PRETTY_FUNCTION__))
;
1438}
1439
1440/// Determine whether we allow overloading of the function
1441/// PrevDecl with another declaration.
1442///
1443/// This routine determines whether overloading is possible, not
1444/// whether some new function is actually an overload. It will return
1445/// true in C++ (where we can always provide overloads) or, as an
1446/// extension, in C when the previous function is already an
1447/// overloaded function declaration or has the "overloadable"
1448/// attribute.
1449static bool AllowOverloadingOfFunction(LookupResult &Previous,
1450 ASTContext &Context,
1451 const FunctionDecl *New) {
1452 if (Context.getLangOpts().CPlusPlus)
1453 return true;
1454
1455 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1456 return true;
1457
1458 return Previous.getResultKind() == LookupResult::Found &&
1459 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1460 New->hasAttr<OverloadableAttr>());
1461}
1462
1463/// Add this decl to the scope shadowed decl chains.
1464void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1465 // Move up the scope chain until we find the nearest enclosing
1466 // non-transparent context. The declaration will be introduced into this
1467 // scope.
1468 while (S->getEntity() && S->getEntity()->isTransparentContext())
1469 S = S->getParent();
1470
1471 // Add scoped declarations into their context, so that they can be
1472 // found later. Declarations without a context won't be inserted
1473 // into any context.
1474 if (AddToContext)
1475 CurContext->addDecl(D);
1476
1477 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1478 // are function-local declarations.
1479 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1480 return;
1481
1482 // Template instantiations should also not be pushed into scope.
1483 if (isa<FunctionDecl>(D) &&
1484 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1485 return;
1486
1487 // If this replaces anything in the current scope,
1488 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1489 IEnd = IdResolver.end();
1490 for (; I != IEnd; ++I) {
1491 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1492 S->RemoveDecl(*I);
1493 IdResolver.RemoveDecl(*I);
1494
1495 // Should only need to replace one decl.
1496 break;
1497 }
1498 }
1499
1500 S->AddDecl(D);
1501
1502 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1503 // Implicitly-generated labels may end up getting generated in an order that
1504 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1505 // the label at the appropriate place in the identifier chain.
1506 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1507 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1508 if (IDC == CurContext) {
1509 if (!S->isDeclScope(*I))
1510 continue;
1511 } else if (IDC->Encloses(CurContext))
1512 break;
1513 }
1514
1515 IdResolver.InsertDeclAfter(I, D);
1516 } else {
1517 IdResolver.AddDecl(D);
1518 }
1519}
1520
1521bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1522 bool AllowInlineNamespace) {
1523 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1524}
1525
1526Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1527 DeclContext *TargetDC = DC->getPrimaryContext();
1528 do {
1529 if (DeclContext *ScopeDC = S->getEntity())
1530 if (ScopeDC->getPrimaryContext() == TargetDC)
1531 return S;
1532 } while ((S = S->getParent()));
1533
1534 return nullptr;
1535}
1536
1537static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1538 DeclContext*,
1539 ASTContext&);
1540
1541/// Filters out lookup results that don't fall within the given scope
1542/// as determined by isDeclInScope.
1543void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1544 bool ConsiderLinkage,
1545 bool AllowInlineNamespace) {
1546 LookupResult::Filter F = R.makeFilter();
1547 while (F.hasNext()) {
1548 NamedDecl *D = F.next();
1549
1550 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1551 continue;
1552
1553 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1554 continue;
1555
1556 F.erase();
1557 }
1558
1559 F.done();
1560}
1561
1562/// We've determined that \p New is a redeclaration of \p Old. Check that they
1563/// have compatible owning modules.
1564bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1565 // FIXME: The Modules TS is not clear about how friend declarations are
1566 // to be treated. It's not meaningful to have different owning modules for
1567 // linkage in redeclarations of the same entity, so for now allow the
1568 // redeclaration and change the owning modules to match.
1569 if (New->getFriendObjectKind() &&
1570 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1571 New->setLocalOwningModule(Old->getOwningModule());
1572 makeMergedDefinitionVisible(New);
1573 return false;
1574 }
1575
1576 Module *NewM = New->getOwningModule();
1577 Module *OldM = Old->getOwningModule();
1578
1579 if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1580 NewM = NewM->Parent;
1581 if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1582 OldM = OldM->Parent;
1583
1584 if (NewM == OldM)
1585 return false;
1586
1587 bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1588 bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1589 if (NewIsModuleInterface || OldIsModuleInterface) {
1590 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1591 // if a declaration of D [...] appears in the purview of a module, all
1592 // other such declarations shall appear in the purview of the same module
1593 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1594 << New
1595 << NewIsModuleInterface
1596 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1597 << OldIsModuleInterface
1598 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1599 Diag(Old->getLocation(), diag::note_previous_declaration);
1600 New->setInvalidDecl();
1601 return true;
1602 }
1603
1604 return false;
1605}
1606
1607static bool isUsingDecl(NamedDecl *D) {
1608 return isa<UsingShadowDecl>(D) ||
1609 isa<UnresolvedUsingTypenameDecl>(D) ||
1610 isa<UnresolvedUsingValueDecl>(D);
1611}
1612
1613/// Removes using shadow declarations from the lookup results.
1614static void RemoveUsingDecls(LookupResult &R) {
1615 LookupResult::Filter F = R.makeFilter();
1616 while (F.hasNext())
1617 if (isUsingDecl(F.next()))
1618 F.erase();
1619
1620 F.done();
1621}
1622
1623/// Check for this common pattern:
1624/// @code
1625/// class S {
1626/// S(const S&); // DO NOT IMPLEMENT
1627/// void operator=(const S&); // DO NOT IMPLEMENT
1628/// };
1629/// @endcode
1630static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1631 // FIXME: Should check for private access too but access is set after we get
1632 // the decl here.
1633 if (D->doesThisDeclarationHaveABody())
1634 return false;
1635
1636 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1637 return CD->isCopyConstructor();
1638 return D->isCopyAssignmentOperator();
1639}
1640
1641// We need this to handle
1642//
1643// typedef struct {
1644// void *foo() { return 0; }
1645// } A;
1646//
1647// When we see foo we don't know if after the typedef we will get 'A' or '*A'
1648// for example. If 'A', foo will have external linkage. If we have '*A',
1649// foo will have no linkage. Since we can't know until we get to the end
1650// of the typedef, this function finds out if D might have non-external linkage.
1651// Callers should verify at the end of the TU if it D has external linkage or
1652// not.
1653bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1654 const DeclContext *DC = D->getDeclContext();
1655 while (!DC->isTranslationUnit()) {
1656 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1657 if (!RD->hasNameForLinkage())
1658 return true;
1659 }
1660 DC = DC->getParent();
1661 }
1662
1663 return !D->isExternallyVisible();
1664}
1665
1666// FIXME: This needs to be refactored; some other isInMainFile users want
1667// these semantics.
1668static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1669 if (S.TUKind != TU_Complete)
1670 return false;
1671 return S.SourceMgr.isInMainFile(Loc);
1672}
1673
1674bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1675 assert(D)((D) ? static_cast<void> (0) : __assert_fail ("D", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 1675, __PRETTY_FUNCTION__))
;
1676
1677 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1678 return false;
1679
1680 // Ignore all entities declared within templates, and out-of-line definitions
1681 // of members of class templates.
1682 if (D->getDeclContext()->isDependentContext() ||
1683 D->getLexicalDeclContext()->isDependentContext())
1684 return false;
1685
1686 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1687 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1688 return false;
1689 // A non-out-of-line declaration of a member specialization was implicitly
1690 // instantiated; it's the out-of-line declaration that we're interested in.
1691 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1692 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1693 return false;
1694
1695 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1696 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1697 return false;
1698 } else {
1699 // 'static inline' functions are defined in headers; don't warn.
1700 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1701 return false;
1702 }
1703
1704 if (FD->doesThisDeclarationHaveABody() &&
1705 Context.DeclMustBeEmitted(FD))
1706 return false;
1707 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1708 // Constants and utility variables are defined in headers with internal
1709 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1710 // like "inline".)
1711 if (!isMainFileLoc(*this, VD->getLocation()))
1712 return false;
1713
1714 if (Context.DeclMustBeEmitted(VD))
1715 return false;
1716
1717 if (VD->isStaticDataMember() &&
1718 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1719 return false;
1720 if (VD->isStaticDataMember() &&
1721 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1722 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1723 return false;
1724
1725 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1726 return false;
1727 } else {
1728 return false;
1729 }
1730
1731 // Only warn for unused decls internal to the translation unit.
1732 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1733 // for inline functions defined in the main source file, for instance.
1734 return mightHaveNonExternalLinkage(D);
1735}
1736
1737void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1738 if (!D)
1739 return;
1740
1741 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1742 const FunctionDecl *First = FD->getFirstDecl();
1743 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1744 return; // First should already be in the vector.
1745 }
1746
1747 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1748 const VarDecl *First = VD->getFirstDecl();
1749 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1750 return; // First should already be in the vector.
1751 }
1752
1753 if (ShouldWarnIfUnusedFileScopedDecl(D))
1754 UnusedFileScopedDecls.push_back(D);
1755}
1756
1757static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1758 if (D->isInvalidDecl())
1759 return false;
1760
1761 if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1762 // For a decomposition declaration, warn if none of the bindings are
1763 // referenced, instead of if the variable itself is referenced (which
1764 // it is, by the bindings' expressions).
1765 for (auto *BD : DD->bindings())
1766 if (BD->isReferenced())
1767 return false;
1768 } else if (!D->getDeclName()) {
1769 return false;
1770 } else if (D->isReferenced() || D->isUsed()) {
1771 return false;
1772 }
1773
1774 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>())
1775 return false;
1776
1777 if (isa<LabelDecl>(D))
1778 return true;
1779
1780 // Except for labels, we only care about unused decls that are local to
1781 // functions.
1782 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1783 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1784 // For dependent types, the diagnostic is deferred.
1785 WithinFunction =
1786 WithinFunction || (R->isLocalClass() && !R->isDependentType());
1787 if (!WithinFunction)
1788 return false;
1789
1790 if (isa<TypedefNameDecl>(D))
1791 return true;
1792
1793 // White-list anything that isn't a local variable.
1794 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1795 return false;
1796
1797 // Types of valid local variables should be complete, so this should succeed.
1798 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1799
1800 // White-list anything with an __attribute__((unused)) type.
1801 const auto *Ty = VD->getType().getTypePtr();
1802
1803 // Only look at the outermost level of typedef.
1804 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1805 if (TT->getDecl()->hasAttr<UnusedAttr>())
1806 return false;
1807 }
1808
1809 // If we failed to complete the type for some reason, or if the type is
1810 // dependent, don't diagnose the variable.
1811 if (Ty->isIncompleteType() || Ty->isDependentType())
1812 return false;
1813
1814 // Look at the element type to ensure that the warning behaviour is
1815 // consistent for both scalars and arrays.
1816 Ty = Ty->getBaseElementTypeUnsafe();
1817
1818 if (const TagType *TT = Ty->getAs<TagType>()) {
1819 const TagDecl *Tag = TT->getDecl();
1820 if (Tag->hasAttr<UnusedAttr>())
1821 return false;
1822
1823 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1824 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1825 return false;
1826
1827 if (const Expr *Init = VD->getInit()) {
1828 if (const ExprWithCleanups *Cleanups =
1829 dyn_cast<ExprWithCleanups>(Init))
1830 Init = Cleanups->getSubExpr();
1831 const CXXConstructExpr *Construct =
1832 dyn_cast<CXXConstructExpr>(Init);
1833 if (Construct && !Construct->isElidable()) {
1834 CXXConstructorDecl *CD = Construct->getConstructor();
1835 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1836 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1837 return false;
1838 }
1839
1840 // Suppress the warning if we don't know how this is constructed, and
1841 // it could possibly be non-trivial constructor.
1842 if (Init->isTypeDependent())
1843 for (const CXXConstructorDecl *Ctor : RD->ctors())
1844 if (!Ctor->isTrivial())
1845 return false;
1846 }
1847 }
1848 }
1849
1850 // TODO: __attribute__((unused)) templates?
1851 }
1852
1853 return true;
1854}
1855
1856static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1857 FixItHint &Hint) {
1858 if (isa<LabelDecl>(D)) {
1859 SourceLocation AfterColon = Lexer::findLocationAfterToken(
1860 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1861 true);
1862 if (AfterColon.isInvalid())
1863 return;
1864 Hint = FixItHint::CreateRemoval(
1865 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1866 }
1867}
1868
1869void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1870 if (D->getTypeForDecl()->isDependentType())
1871 return;
1872
1873 for (auto *TmpD : D->decls()) {
1874 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1875 DiagnoseUnusedDecl(T);
1876 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1877 DiagnoseUnusedNestedTypedefs(R);
1878 }
1879}
1880
1881/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1882/// unless they are marked attr(unused).
1883void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1884 if (!ShouldDiagnoseUnusedDecl(D))
1885 return;
1886
1887 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1888 // typedefs can be referenced later on, so the diagnostics are emitted
1889 // at end-of-translation-unit.
1890 UnusedLocalTypedefNameCandidates.insert(TD);
1891 return;
1892 }
1893
1894 FixItHint Hint;
1895 GenerateFixForUnusedDecl(D, Context, Hint);
1896
1897 unsigned DiagID;
1898 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1899 DiagID = diag::warn_unused_exception_param;
1900 else if (isa<LabelDecl>(D))
1901 DiagID = diag::warn_unused_label;
1902 else
1903 DiagID = diag::warn_unused_variable;
1904
1905 Diag(D->getLocation(), DiagID) << D << Hint;
1906}
1907
1908static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1909 // Verify that we have no forward references left. If so, there was a goto
1910 // or address of a label taken, but no definition of it. Label fwd
1911 // definitions are indicated with a null substmt which is also not a resolved
1912 // MS inline assembly label name.
1913 bool Diagnose = false;
1914 if (L->isMSAsmLabel())
1915 Diagnose = !L->isResolvedMSAsmLabel();
1916 else
1917 Diagnose = L->getStmt() == nullptr;
1918 if (Diagnose)
1919 S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L;
1920}
1921
1922void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1923 S->mergeNRVOIntoParent();
1924
1925 if (S->decl_empty()) return;
1926 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&(((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope
)) && "Scope shouldn't contain decls!") ? static_cast
<void> (0) : __assert_fail ("(S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && \"Scope shouldn't contain decls!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 1927, __PRETTY_FUNCTION__))
1927 "Scope shouldn't contain decls!")(((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope
)) && "Scope shouldn't contain decls!") ? static_cast
<void> (0) : __assert_fail ("(S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && \"Scope shouldn't contain decls!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 1927, __PRETTY_FUNCTION__))
;
1928
1929 for (auto *TmpD : S->decls()) {
1930 assert(TmpD && "This decl didn't get pushed??")((TmpD && "This decl didn't get pushed??") ? static_cast
<void> (0) : __assert_fail ("TmpD && \"This decl didn't get pushed??\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 1930, __PRETTY_FUNCTION__))
;
1931
1932 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?")((isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"
) ? static_cast<void> (0) : __assert_fail ("isa<NamedDecl>(TmpD) && \"Decl isn't NamedDecl?\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 1932, __PRETTY_FUNCTION__))
;
1933 NamedDecl *D = cast<NamedDecl>(TmpD);
1934
1935 // Diagnose unused variables in this scope.
1936 if (!S->hasUnrecoverableErrorOccurred()) {
1937 DiagnoseUnusedDecl(D);
1938 if (const auto *RD = dyn_cast<RecordDecl>(D))
1939 DiagnoseUnusedNestedTypedefs(RD);
1940 }
1941
1942 if (!D->getDeclName()) continue;
1943
1944 // If this was a forward reference to a label, verify it was defined.
1945 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1946 CheckPoppedLabel(LD, *this);
1947
1948 // Remove this name from our lexical scope, and warn on it if we haven't
1949 // already.
1950 IdResolver.RemoveDecl(D);
1951 auto ShadowI = ShadowingDecls.find(D);
1952 if (ShadowI != ShadowingDecls.end()) {
1953 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1954 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1955 << D << FD << FD->getParent();
1956 Diag(FD->getLocation(), diag::note_previous_declaration);
1957 }
1958 ShadowingDecls.erase(ShadowI);
1959 }
1960 }
1961}
1962
1963/// Look for an Objective-C class in the translation unit.
1964///
1965/// \param Id The name of the Objective-C class we're looking for. If
1966/// typo-correction fixes this name, the Id will be updated
1967/// to the fixed name.
1968///
1969/// \param IdLoc The location of the name in the translation unit.
1970///
1971/// \param DoTypoCorrection If true, this routine will attempt typo correction
1972/// if there is no class with the given name.
1973///
1974/// \returns The declaration of the named Objective-C class, or NULL if the
1975/// class could not be found.
1976ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1977 SourceLocation IdLoc,
1978 bool DoTypoCorrection) {
1979 // The third "scope" argument is 0 since we aren't enabling lazy built-in
1980 // creation from this context.
1981 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1982
1983 if (!IDecl && DoTypoCorrection) {
1984 // Perform typo correction at the given location, but only if we
1985 // find an Objective-C class name.
1986 DeclFilterCCC<ObjCInterfaceDecl> CCC{};
1987 if (TypoCorrection C =
1988 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
1989 TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
1990 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1991 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1992 Id = IDecl->getIdentifier();
1993 }
1994 }
1995 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1996 // This routine must always return a class definition, if any.
1997 if (Def && Def->getDefinition())
1998 Def = Def->getDefinition();
1999 return Def;
2000}
2001
2002/// getNonFieldDeclScope - Retrieves the innermost scope, starting
2003/// from S, where a non-field would be declared. This routine copes
2004/// with the difference between C and C++ scoping rules in structs and
2005/// unions. For example, the following code is well-formed in C but
2006/// ill-formed in C++:
2007/// @code
2008/// struct S6 {
2009/// enum { BAR } e;
2010/// };
2011///
2012/// void test_S6() {
2013/// struct S6 a;
2014/// a.e = BAR;
2015/// }
2016/// @endcode
2017/// For the declaration of BAR, this routine will return a different
2018/// scope. The scope S will be the scope of the unnamed enumeration
2019/// within S6. In C++, this routine will return the scope associated
2020/// with S6, because the enumeration's scope is a transparent
2021/// context but structures can contain non-field names. In C, this
2022/// routine will return the translation unit scope, since the
2023/// enumeration's scope is a transparent context and structures cannot
2024/// contain non-field names.
2025Scope *Sema::getNonFieldDeclScope(Scope *S) {
2026 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2027 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2028 (S->isClassScope() && !getLangOpts().CPlusPlus))
2029 S = S->getParent();
2030 return S;
2031}
2032
2033static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2034 ASTContext::GetBuiltinTypeError Error) {
2035 switch (Error) {
2036 case ASTContext::GE_None:
2037 return "";
2038 case ASTContext::GE_Missing_type:
2039 return BuiltinInfo.getHeaderName(ID);
2040 case ASTContext::GE_Missing_stdio:
2041 return "stdio.h";
2042 case ASTContext::GE_Missing_setjmp:
2043 return "setjmp.h";
2044 case ASTContext::GE_Missing_ucontext:
2045 return "ucontext.h";
2046 }
2047 llvm_unreachable("unhandled error kind")::llvm::llvm_unreachable_internal("unhandled error kind", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 2047)
;
2048}
2049
2050FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2051 unsigned ID, SourceLocation Loc) {
2052 DeclContext *Parent = Context.getTranslationUnitDecl();
2053
2054 if (getLangOpts().CPlusPlus) {
2055 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2056 Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
2057 CLinkageDecl->setImplicit();
2058 Parent->addDecl(CLinkageDecl);
2059 Parent = CLinkageDecl;
2060 }
2061
2062 FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2063 /*TInfo=*/nullptr, SC_Extern, false,
2064 Type->isFunctionProtoType());
2065 New->setImplicit();
2066 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2067
2068 // Create Decl objects for each parameter, adding them to the
2069 // FunctionDecl.
2070 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2071 SmallVector<ParmVarDecl *, 16> Params;
2072 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2073 ParmVarDecl *parm = ParmVarDecl::Create(
2074 Context, New, SourceLocation(), SourceLocation(), nullptr,
2075 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2076 parm->setScopeInfo(0, i);
2077 Params.push_back(parm);
2078 }
2079 New->setParams(Params);
2080 }
2081
2082 AddKnownFunctionAttributes(New);
2083 return New;
2084}
2085
2086/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2087/// file scope. lazily create a decl for it. ForRedeclaration is true
2088/// if we're creating this built-in in anticipation of redeclaring the
2089/// built-in.
2090NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2091 Scope *S, bool ForRedeclaration,
2092 SourceLocation Loc) {
2093 LookupNecessaryTypesForBuiltin(S, ID);
2094
2095 ASTContext::GetBuiltinTypeError Error;
2096 QualType R = Context.GetBuiltinType(ID, Error);
2097 if (Error) {
2098 if (!ForRedeclaration)
2099 return nullptr;
2100
2101 // If we have a builtin without an associated type we should not emit a
2102 // warning when we were not able to find a type for it.
2103 if (Error == ASTContext::GE_Missing_type ||
2104 Context.BuiltinInfo.allowTypeMismatch(ID))
2105 return nullptr;
2106
2107 // If we could not find a type for setjmp it is because the jmp_buf type was
2108 // not defined prior to the setjmp declaration.
2109 if (Error == ASTContext::GE_Missing_setjmp) {
2110 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2111 << Context.BuiltinInfo.getName(ID);
2112 return nullptr;
2113 }
2114
2115 // Generally, we emit a warning that the declaration requires the
2116 // appropriate header.
2117 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2118 << getHeaderName(Context.BuiltinInfo, ID, Error)
2119 << Context.BuiltinInfo.getName(ID);
2120 return nullptr;
2121 }
2122
2123 if (!ForRedeclaration &&
2124 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2125 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2126 Diag(Loc, diag::ext_implicit_lib_function_decl)
2127 << Context.BuiltinInfo.getName(ID) << R;
2128 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2129 Diag(Loc, diag::note_include_header_or_declare)
2130 << Header << Context.BuiltinInfo.getName(ID);
2131 }
2132
2133 if (R.isNull())
2134 return nullptr;
2135
2136 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2137 RegisterLocallyScopedExternCDecl(New, S);
2138
2139 // TUScope is the translation-unit scope to insert this function into.
2140 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2141 // relate Scopes to DeclContexts, and probably eliminate CurContext
2142 // entirely, but we're not there yet.
2143 DeclContext *SavedContext = CurContext;
2144 CurContext = New->getDeclContext();
2145 PushOnScopeChains(New, TUScope);
2146 CurContext = SavedContext;
2147 return New;
2148}
2149
2150/// Typedef declarations don't have linkage, but they still denote the same
2151/// entity if their types are the same.
2152/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2153/// isSameEntity.
2154static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2155 TypedefNameDecl *Decl,
2156 LookupResult &Previous) {
2157 // This is only interesting when modules are enabled.
2158 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2159 return;
2160
2161 // Empty sets are uninteresting.
2162 if (Previous.empty())
2163 return;
2164
2165 LookupResult::Filter Filter = Previous.makeFilter();
2166 while (Filter.hasNext()) {
2167 NamedDecl *Old = Filter.next();
2168
2169 // Non-hidden declarations are never ignored.
2170 if (S.isVisible(Old))
2171 continue;
2172
2173 // Declarations of the same entity are not ignored, even if they have
2174 // different linkages.
2175 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2176 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2177 Decl->getUnderlyingType()))
2178 continue;
2179
2180 // If both declarations give a tag declaration a typedef name for linkage
2181 // purposes, then they declare the same entity.
2182 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2183 Decl->getAnonDeclWithTypedefName())
2184 continue;
2185 }
2186
2187 Filter.erase();
2188 }
2189
2190 Filter.done();
2191}
2192
2193bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2194 QualType OldType;
2195 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2196 OldType = OldTypedef->getUnderlyingType();
2197 else
2198 OldType = Context.getTypeDeclType(Old);
2199 QualType NewType = New->getUnderlyingType();
2200
2201 if (NewType->isVariablyModifiedType()) {
2202 // Must not redefine a typedef with a variably-modified type.
2203 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2204 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2205 << Kind << NewType;
2206 if (Old->getLocation().isValid())
2207 notePreviousDefinition(Old, New->getLocation());
2208 New->setInvalidDecl();
2209 return true;
2210 }
2211
2212 if (OldType != NewType &&
2213 !OldType->isDependentType() &&
2214 !NewType->isDependentType() &&
2215 !Context.hasSameType(OldType, NewType)) {
2216 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2217 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2218 << Kind << NewType << OldType;
2219 if (Old->getLocation().isValid())
2220 notePreviousDefinition(Old, New->getLocation());
2221 New->setInvalidDecl();
2222 return true;
2223 }
2224 return false;
2225}
2226
2227/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2228/// same name and scope as a previous declaration 'Old'. Figure out
2229/// how to resolve this situation, merging decls or emitting
2230/// diagnostics as appropriate. If there was an error, set New to be invalid.
2231///
2232void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2233 LookupResult &OldDecls) {
2234 // If the new decl is known invalid already, don't bother doing any
2235 // merging checks.
2236 if (New->isInvalidDecl()) return;
2237
2238 // Allow multiple definitions for ObjC built-in typedefs.
2239 // FIXME: Verify the underlying types are equivalent!
2240 if (getLangOpts().ObjC) {
2241 const IdentifierInfo *TypeID = New->getIdentifier();
2242 switch (TypeID->getLength()) {
2243 default: break;
2244 case 2:
2245 {
2246 if (!TypeID->isStr("id"))
2247 break;
2248 QualType T = New->getUnderlyingType();
2249 if (!T->isPointerType())
2250 break;
2251 if (!T->isVoidPointerType()) {
2252 QualType PT = T->castAs<PointerType>()->getPointeeType();
2253 if (!PT->isStructureType())
2254 break;
2255 }
2256 Context.setObjCIdRedefinitionType(T);
2257 // Install the built-in type for 'id', ignoring the current definition.
2258 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2259 return;
2260 }
2261 case 5:
2262 if (!TypeID->isStr("Class"))
2263 break;
2264 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2265 // Install the built-in type for 'Class', ignoring the current definition.
2266 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2267 return;
2268 case 3:
2269 if (!TypeID->isStr("SEL"))
2270 break;
2271 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2272 // Install the built-in type for 'SEL', ignoring the current definition.
2273 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2274 return;
2275 }
2276 // Fall through - the typedef name was not a builtin type.
2277 }
2278
2279 // Verify the old decl was also a type.
2280 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2281 if (!Old) {
2282 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2283 << New->getDeclName();
2284
2285 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2286 if (OldD->getLocation().isValid())
2287 notePreviousDefinition(OldD, New->getLocation());
2288
2289 return New->setInvalidDecl();
2290 }
2291
2292 // If the old declaration is invalid, just give up here.
2293 if (Old->isInvalidDecl())
2294 return New->setInvalidDecl();
2295
2296 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2297 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2298 auto *NewTag = New->getAnonDeclWithTypedefName();
2299 NamedDecl *Hidden = nullptr;
2300 if (OldTag && NewTag &&
2301 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2302 !hasVisibleDefinition(OldTag, &Hidden)) {
2303 // There is a definition of this tag, but it is not visible. Use it
2304 // instead of our tag.
2305 New->setTypeForDecl(OldTD->getTypeForDecl());
2306 if (OldTD->isModed())
2307 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2308 OldTD->getUnderlyingType());
2309 else
2310 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2311
2312 // Make the old tag definition visible.
2313 makeMergedDefinitionVisible(Hidden);
2314
2315 // If this was an unscoped enumeration, yank all of its enumerators
2316 // out of the scope.
2317 if (isa<EnumDecl>(NewTag)) {
2318 Scope *EnumScope = getNonFieldDeclScope(S);
2319 for (auto *D : NewTag->decls()) {
2320 auto *ED = cast<EnumConstantDecl>(D);
2321 assert(EnumScope->isDeclScope(ED))((EnumScope->isDeclScope(ED)) ? static_cast<void> (0
) : __assert_fail ("EnumScope->isDeclScope(ED)", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 2321, __PRETTY_FUNCTION__))
;
2322 EnumScope->RemoveDecl(ED);
2323 IdResolver.RemoveDecl(ED);
2324 ED->getLexicalDeclContext()->removeDecl(ED);
2325 }
2326 }
2327 }
2328 }
2329
2330 // If the typedef types are not identical, reject them in all languages and
2331 // with any extensions enabled.
2332 if (isIncompatibleTypedef(Old, New))
2333 return;
2334
2335 // The types match. Link up the redeclaration chain and merge attributes if
2336 // the old declaration was a typedef.
2337 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2338 New->setPreviousDecl(Typedef);
2339 mergeDeclAttributes(New, Old);
2340 }
2341
2342 if (getLangOpts().MicrosoftExt)
2343 return;
2344
2345 if (getLangOpts().CPlusPlus) {
2346 // C++ [dcl.typedef]p2:
2347 // In a given non-class scope, a typedef specifier can be used to
2348 // redefine the name of any type declared in that scope to refer
2349 // to the type to which it already refers.
2350 if (!isa<CXXRecordDecl>(CurContext))
2351 return;
2352
2353 // C++0x [dcl.typedef]p4:
2354 // In a given class scope, a typedef specifier can be used to redefine
2355 // any class-name declared in that scope that is not also a typedef-name
2356 // to refer to the type to which it already refers.
2357 //
2358 // This wording came in via DR424, which was a correction to the
2359 // wording in DR56, which accidentally banned code like:
2360 //
2361 // struct S {
2362 // typedef struct A { } A;
2363 // };
2364 //
2365 // in the C++03 standard. We implement the C++0x semantics, which
2366 // allow the above but disallow
2367 //
2368 // struct S {
2369 // typedef int I;
2370 // typedef int I;
2371 // };
2372 //
2373 // since that was the intent of DR56.
2374 if (!isa<TypedefNameDecl>(Old))
2375 return;
2376
2377 Diag(New->getLocation(), diag::err_redefinition)
2378 << New->getDeclName();
2379 notePreviousDefinition(Old, New->getLocation());
2380 return New->setInvalidDecl();
2381 }
2382
2383 // Modules always permit redefinition of typedefs, as does C11.
2384 if (getLangOpts().Modules || getLangOpts().C11)
2385 return;
2386
2387 // If we have a redefinition of a typedef in C, emit a warning. This warning
2388 // is normally mapped to an error, but can be controlled with
2389 // -Wtypedef-redefinition. If either the original or the redefinition is
2390 // in a system header, don't emit this for compatibility with GCC.
2391 if (getDiagnostics().getSuppressSystemWarnings() &&
2392 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2393 (Old->isImplicit() ||
2394 Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2395 Context.getSourceManager().isInSystemHeader(New->getLocation())))
2396 return;
2397
2398 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2399 << New->getDeclName();
2400 notePreviousDefinition(Old, New->getLocation());
2401}
2402
2403/// DeclhasAttr - returns true if decl Declaration already has the target
2404/// attribute.
2405static bool DeclHasAttr(const Decl *D, const Attr *A) {
2406 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2407 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2408 for (const auto *i : D->attrs())
2409 if (i->getKind() == A->getKind()) {
2410 if (Ann) {
2411 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2412 return true;
2413 continue;
2414 }
2415 // FIXME: Don't hardcode this check
2416 if (OA && isa<OwnershipAttr>(i))
2417 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2418 return true;
2419 }
2420
2421 return false;
2422}
2423
2424static bool isAttributeTargetADefinition(Decl *D) {
2425 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2426 return VD->isThisDeclarationADefinition();
2427 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2428 return TD->isCompleteDefinition() || TD->isBeingDefined();
2429 return true;
2430}
2431
2432/// Merge alignment attributes from \p Old to \p New, taking into account the
2433/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2434///
2435/// \return \c true if any attributes were added to \p New.
2436static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2437 // Look for alignas attributes on Old, and pick out whichever attribute
2438 // specifies the strictest alignment requirement.
2439 AlignedAttr *OldAlignasAttr = nullptr;
2440 AlignedAttr *OldStrictestAlignAttr = nullptr;
2441 unsigned OldAlign = 0;
2442 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2443 // FIXME: We have no way of representing inherited dependent alignments
2444 // in a case like:
2445 // template<int A, int B> struct alignas(A) X;
2446 // template<int A, int B> struct alignas(B) X {};
2447 // For now, we just ignore any alignas attributes which are not on the
2448 // definition in such a case.
2449 if (I->isAlignmentDependent())
2450 return false;
2451
2452 if (I->isAlignas())
2453 OldAlignasAttr = I;
2454
2455 unsigned Align = I->getAlignment(S.Context);
2456 if (Align > OldAlign) {
2457 OldAlign = Align;
2458 OldStrictestAlignAttr = I;
2459 }
2460 }
2461
2462 // Look for alignas attributes on New.
2463 AlignedAttr *NewAlignasAttr = nullptr;
2464 unsigned NewAlign = 0;
2465 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2466 if (I->isAlignmentDependent())
2467 return false;
2468
2469 if (I->isAlignas())
2470 NewAlignasAttr = I;
2471
2472 unsigned Align = I->getAlignment(S.Context);
2473 if (Align > NewAlign)
2474 NewAlign = Align;
2475 }
2476
2477 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2478 // Both declarations have 'alignas' attributes. We require them to match.
2479 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2480 // fall short. (If two declarations both have alignas, they must both match
2481 // every definition, and so must match each other if there is a definition.)
2482
2483 // If either declaration only contains 'alignas(0)' specifiers, then it
2484 // specifies the natural alignment for the type.
2485 if (OldAlign == 0 || NewAlign == 0) {
2486 QualType Ty;
2487 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2488 Ty = VD->getType();
2489 else
2490 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2491
2492 if (OldAlign == 0)
2493 OldAlign = S.Context.getTypeAlign(Ty);
2494 if (NewAlign == 0)
2495 NewAlign = S.Context.getTypeAlign(Ty);
2496 }
2497
2498 if (OldAlign != NewAlign) {
2499 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2500 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2501 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2502 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2503 }
2504 }
2505
2506 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2507 // C++11 [dcl.align]p6:
2508 // if any declaration of an entity has an alignment-specifier,
2509 // every defining declaration of that entity shall specify an
2510 // equivalent alignment.
2511 // C11 6.7.5/7:
2512 // If the definition of an object does not have an alignment
2513 // specifier, any other declaration of that object shall also
2514 // have no alignment specifier.
2515 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2516 << OldAlignasAttr;
2517 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2518 << OldAlignasAttr;
2519 }
2520
2521 bool AnyAdded = false;
2522
2523 // Ensure we have an attribute representing the strictest alignment.
2524 if (OldAlign > NewAlign) {
2525 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2526 Clone->setInherited(true);
2527 New->addAttr(Clone);
2528 AnyAdded = true;
2529 }
2530
2531 // Ensure we have an alignas attribute if the old declaration had one.
2532 if (OldAlignasAttr && !NewAlignasAttr &&
2533 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2534 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2535 Clone->setInherited(true);
2536 New->addAttr(Clone);
2537 AnyAdded = true;
2538 }
2539
2540 return AnyAdded;
2541}
2542
2543#define WANT_DECL_MERGE_LOGIC
2544#include "clang/Sema/AttrParsedAttrImpl.inc"
2545#undef WANT_DECL_MERGE_LOGIC
2546
2547static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2548 const InheritableAttr *Attr,
2549 Sema::AvailabilityMergeKind AMK) {
2550 // Diagnose any mutual exclusions between the attribute that we want to add
2551 // and attributes that already exist on the declaration.
2552 if (!DiagnoseMutualExclusions(S, D, Attr))
2553 return false;
2554
2555 // This function copies an attribute Attr from a previous declaration to the
2556 // new declaration D if the new declaration doesn't itself have that attribute
2557 // yet or if that attribute allows duplicates.
2558 // If you're adding a new attribute that requires logic different from
2559 // "use explicit attribute on decl if present, else use attribute from
2560 // previous decl", for example if the attribute needs to be consistent
2561 // between redeclarations, you need to call a custom merge function here.
2562 InheritableAttr *NewAttr = nullptr;
2563 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2564 NewAttr = S.mergeAvailabilityAttr(
2565 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2566 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2567 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2568 AA->getPriority());
2569 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2570 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2571 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2572 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2573 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2574 NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2575 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2576 NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2577 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2578 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2579 FA->getFirstArg());
2580 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2581 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2582 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2583 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2584 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2585 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2586 IA->getInheritanceModel());
2587 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2588 NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2589 &S.Context.Idents.get(AA->getSpelling()));
2590 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2591 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2592 isa<CUDAGlobalAttr>(Attr))) {
2593 // CUDA target attributes are part of function signature for
2594 // overloading purposes and must not be merged.
2595 return false;
2596 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2597 NewAttr = S.mergeMinSizeAttr(D, *MA);
2598 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2599 NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2600 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2601 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2602 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2603 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2604 else if (isa<AlignedAttr>(Attr))
2605 // AlignedAttrs are handled separately, because we need to handle all
2606 // such attributes on a declaration at the same time.
2607 NewAttr = nullptr;
2608 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2609 (AMK == Sema::AMK_Override ||
2610 AMK == Sema::AMK_ProtocolImplementation))
2611 NewAttr = nullptr;
2612 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2613 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2614 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2615 NewAttr = S.mergeImportModuleAttr(D, *IMA);
2616 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2617 NewAttr = S.mergeImportNameAttr(D, *INA);
2618 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2619 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2620 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2621 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2622 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2623 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2624
2625 if (NewAttr) {
2626 NewAttr->setInherited(true);
2627 D->addAttr(NewAttr);
2628 if (isa<MSInheritanceAttr>(NewAttr))
2629 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2630 return true;
2631 }
2632
2633 return false;
2634}
2635
2636static const NamedDecl *getDefinition(const Decl *D) {
2637 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2638 return TD->getDefinition();
2639 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2640 const VarDecl *Def = VD->getDefinition();
2641 if (Def)
2642 return Def;
2643 return VD->getActingDefinition();
2644 }
2645 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2646 const FunctionDecl *Def = nullptr;
2647 if (FD->isDefined(Def, true))
2648 return Def;
2649 }
2650 return nullptr;
2651}
2652
2653static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2654 for (const auto *Attribute : D->attrs())
2655 if (Attribute->getKind() == Kind)
2656 return true;
2657 return false;
2658}
2659
2660/// checkNewAttributesAfterDef - If we already have a definition, check that
2661/// there are no new attributes in this declaration.
2662static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2663 if (!New->hasAttrs())
2664 return;
2665
2666 const NamedDecl *Def = getDefinition(Old);
2667 if (!Def || Def == New)
2668 return;
2669
2670 AttrVec &NewAttributes = New->getAttrs();
2671 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2672 const Attr *NewAttribute = NewAttributes[I];
2673
2674 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2675 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2676 Sema::SkipBodyInfo SkipBody;
2677 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2678
2679 // If we're skipping this definition, drop the "alias" attribute.
2680 if (SkipBody.ShouldSkip) {
2681 NewAttributes.erase(NewAttributes.begin() + I);
2682 --E;
2683 continue;
2684 }
2685 } else {
2686 VarDecl *VD = cast<VarDecl>(New);
2687 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2688 VarDecl::TentativeDefinition
2689 ? diag::err_alias_after_tentative
2690 : diag::err_redefinition;
2691 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2692 if (Diag == diag::err_redefinition)
2693 S.notePreviousDefinition(Def, VD->getLocation());
2694 else
2695 S.Diag(Def->getLocation(), diag::note_previous_definition);
2696 VD->setInvalidDecl();
2697 }
2698 ++I;
2699 continue;
2700 }
2701
2702 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2703 // Tentative definitions are only interesting for the alias check above.
2704 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2705 ++I;
2706 continue;
2707 }
2708 }
2709
2710 if (hasAttribute(Def, NewAttribute->getKind())) {
2711 ++I;
2712 continue; // regular attr merging will take care of validating this.
2713 }
2714
2715 if (isa<C11NoReturnAttr>(NewAttribute)) {
2716 // C's _Noreturn is allowed to be added to a function after it is defined.
2717 ++I;
2718 continue;
2719 } else if (isa<UuidAttr>(NewAttribute)) {
2720 // msvc will allow a subsequent definition to add an uuid to a class
2721 ++I;
2722 continue;
2723 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2724 if (AA->isAlignas()) {
2725 // C++11 [dcl.align]p6:
2726 // if any declaration of an entity has an alignment-specifier,
2727 // every defining declaration of that entity shall specify an
2728 // equivalent alignment.
2729 // C11 6.7.5/7:
2730 // If the definition of an object does not have an alignment
2731 // specifier, any other declaration of that object shall also
2732 // have no alignment specifier.
2733 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2734 << AA;
2735 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2736 << AA;
2737 NewAttributes.erase(NewAttributes.begin() + I);
2738 --E;
2739 continue;
2740 }
2741 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2742 // If there is a C definition followed by a redeclaration with this
2743 // attribute then there are two different definitions. In C++, prefer the
2744 // standard diagnostics.
2745 if (!S.getLangOpts().CPlusPlus) {
2746 S.Diag(NewAttribute->getLocation(),
2747 diag::err_loader_uninitialized_redeclaration);
2748 S.Diag(Def->getLocation(), diag::note_previous_definition);
2749 NewAttributes.erase(NewAttributes.begin() + I);
2750 --E;
2751 continue;
2752 }
2753 } else if (isa<SelectAnyAttr>(NewAttribute) &&
2754 cast<VarDecl>(New)->isInline() &&
2755 !cast<VarDecl>(New)->isInlineSpecified()) {
2756 // Don't warn about applying selectany to implicitly inline variables.
2757 // Older compilers and language modes would require the use of selectany
2758 // to make such variables inline, and it would have no effect if we
2759 // honored it.
2760 ++I;
2761 continue;
2762 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
2763 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
2764 // declarations after defintions.
2765 ++I;
2766 continue;
2767 }
2768
2769 S.Diag(NewAttribute->getLocation(),
2770 diag::warn_attribute_precede_definition);
2771 S.Diag(Def->getLocation(), diag::note_previous_definition);
2772 NewAttributes.erase(NewAttributes.begin() + I);
2773 --E;
2774 }
2775}
2776
2777static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2778 const ConstInitAttr *CIAttr,
2779 bool AttrBeforeInit) {
2780 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2781
2782 // Figure out a good way to write this specifier on the old declaration.
2783 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2784 // enough of the attribute list spelling information to extract that without
2785 // heroics.
2786 std::string SuitableSpelling;
2787 if (S.getLangOpts().CPlusPlus20)
2788 SuitableSpelling = std::string(
2789 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2790 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2791 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2792 InsertLoc, {tok::l_square, tok::l_square,
2793 S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2794 S.PP.getIdentifierInfo("require_constant_initialization"),
2795 tok::r_square, tok::r_square}));
2796 if (SuitableSpelling.empty())
2797 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2798 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2799 S.PP.getIdentifierInfo("require_constant_initialization"),
2800 tok::r_paren, tok::r_paren}));
2801 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
2802 SuitableSpelling = "constinit";
2803 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2804 SuitableSpelling = "[[clang::require_constant_initialization]]";
2805 if (SuitableSpelling.empty())
2806 SuitableSpelling = "__attribute__((require_constant_initialization))";
2807 SuitableSpelling += " ";
2808
2809 if (AttrBeforeInit) {
2810 // extern constinit int a;
2811 // int a = 0; // error (missing 'constinit'), accepted as extension
2812 assert(CIAttr->isConstinit() && "should not diagnose this for attribute")((CIAttr->isConstinit() && "should not diagnose this for attribute"
) ? static_cast<void> (0) : __assert_fail ("CIAttr->isConstinit() && \"should not diagnose this for attribute\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 2812, __PRETTY_FUNCTION__))
;
2813 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2814 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2815 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2816 } else {
2817 // int a = 0;
2818 // constinit extern int a; // error (missing 'constinit')
2819 S.Diag(CIAttr->getLocation(),
2820 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2821 : diag::warn_require_const_init_added_too_late)
2822 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2823 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2824 << CIAttr->isConstinit()
2825 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2826 }
2827}
2828
2829/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2830void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2831 AvailabilityMergeKind AMK) {
2832 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2833 UsedAttr *NewAttr = OldAttr->clone(Context);
2834 NewAttr->setInherited(true);
2835 New->addAttr(NewAttr);
2836 }
2837 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
2838 RetainAttr *NewAttr = OldAttr->clone(Context);
2839 NewAttr->setInherited(true);
2840 New->addAttr(NewAttr);
2841 }
2842
2843 if (!Old->hasAttrs() && !New->hasAttrs())
2844 return;
2845
2846 // [dcl.constinit]p1:
2847 // If the [constinit] specifier is applied to any declaration of a
2848 // variable, it shall be applied to the initializing declaration.
2849 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
2850 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
2851 if (bool(OldConstInit) != bool(NewConstInit)) {
2852 const auto *OldVD = cast<VarDecl>(Old);
2853 auto *NewVD = cast<VarDecl>(New);
2854
2855 // Find the initializing declaration. Note that we might not have linked
2856 // the new declaration into the redeclaration chain yet.
2857 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
2858 if (!InitDecl &&
2859 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
2860 InitDecl = NewVD;
2861
2862 if (InitDecl == NewVD) {
2863 // This is the initializing declaration. If it would inherit 'constinit',
2864 // that's ill-formed. (Note that we do not apply this to the attribute
2865 // form).
2866 if (OldConstInit && OldConstInit->isConstinit())
2867 diagnoseMissingConstinit(*this, NewVD, OldConstInit,
2868 /*AttrBeforeInit=*/true);
2869 } else if (NewConstInit) {
2870 // This is the first time we've been told that this declaration should
2871 // have a constant initializer. If we already saw the initializing
2872 // declaration, this is too late.
2873 if (InitDecl && InitDecl != NewVD) {
2874 diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
2875 /*AttrBeforeInit=*/false);
2876 NewVD->dropAttr<ConstInitAttr>();
2877 }
2878 }
2879 }
2880
2881 // Attributes declared post-definition are currently ignored.
2882 checkNewAttributesAfterDef(*this, New, Old);
2883
2884 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2885 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2886 if (!OldA->isEquivalent(NewA)) {
2887 // This redeclaration changes __asm__ label.
2888 Diag(New->getLocation(), diag::err_different_asm_label);
2889 Diag(OldA->getLocation(), diag::note_previous_declaration);
2890 }
2891 } else if (Old->isUsed()) {
2892 // This redeclaration adds an __asm__ label to a declaration that has
2893 // already been ODR-used.
2894 Diag(New->getLocation(), diag::err_late_asm_label_name)
2895 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2896 }
2897 }
2898
2899 // Re-declaration cannot add abi_tag's.
2900 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2901 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2902 for (const auto &NewTag : NewAbiTagAttr->tags()) {
2903 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2904 NewTag) == OldAbiTagAttr->tags_end()) {
2905 Diag(NewAbiTagAttr->getLocation(),
2906 diag::err_new_abi_tag_on_redeclaration)
2907 << NewTag;
2908 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2909 }
2910 }
2911 } else {
2912 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2913 Diag(Old->getLocation(), diag::note_previous_declaration);
2914 }
2915 }
2916
2917 // This redeclaration adds a section attribute.
2918 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2919 if (auto *VD = dyn_cast<VarDecl>(New)) {
2920 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2921 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2922 Diag(Old->getLocation(), diag::note_previous_declaration);
2923 }
2924 }
2925 }
2926
2927 // Redeclaration adds code-seg attribute.
2928 const auto *NewCSA = New->getAttr<CodeSegAttr>();
2929 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2930 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2931 Diag(New->getLocation(), diag::warn_mismatched_section)
2932 << 0 /*codeseg*/;
2933 Diag(Old->getLocation(), diag::note_previous_declaration);
2934 }
2935
2936 if (!Old->hasAttrs())
2937 return;
2938
2939 bool foundAny = New->hasAttrs();
2940
2941 // Ensure that any moving of objects within the allocated map is done before
2942 // we process them.
2943 if (!foundAny) New->setAttrs(AttrVec());
2944
2945 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2946 // Ignore deprecated/unavailable/availability attributes if requested.
2947 AvailabilityMergeKind LocalAMK = AMK_None;
2948 if (isa<DeprecatedAttr>(I) ||
2949 isa<UnavailableAttr>(I) ||
2950 isa<AvailabilityAttr>(I)) {
2951 switch (AMK) {
2952 case AMK_None:
2953 continue;
2954
2955 case AMK_Redeclaration:
2956 case AMK_Override:
2957 case AMK_ProtocolImplementation:
2958 LocalAMK = AMK;
2959 break;
2960 }
2961 }
2962
2963 // Already handled.
2964 if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
2965 continue;
2966
2967 if (mergeDeclAttribute(*this, New, I, LocalAMK))
2968 foundAny = true;
2969 }
2970
2971 if (mergeAlignedAttrs(*this, New, Old))
2972 foundAny = true;
2973
2974 if (!foundAny) New->dropAttrs();
2975}
2976
2977/// mergeParamDeclAttributes - Copy attributes from the old parameter
2978/// to the new one.
2979static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2980 const ParmVarDecl *oldDecl,
2981 Sema &S) {
2982 // C++11 [dcl.attr.depend]p2:
2983 // The first declaration of a function shall specify the
2984 // carries_dependency attribute for its declarator-id if any declaration
2985 // of the function specifies the carries_dependency attribute.
2986 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2987 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2988 S.Diag(CDA->getLocation(),
2989 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2990 // Find the first declaration of the parameter.
2991 // FIXME: Should we build redeclaration chains for function parameters?
2992 const FunctionDecl *FirstFD =
2993 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2994 const ParmVarDecl *FirstVD =
2995 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2996 S.Diag(FirstVD->getLocation(),
2997 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2998 }
2999
3000 if (!oldDecl->hasAttrs())
3001 return;
3002
3003 bool foundAny = newDecl->hasAttrs();
3004
3005 // Ensure that any moving of objects within the allocated map is
3006 // done before we process them.
3007 if (!foundAny) newDecl->setAttrs(AttrVec());
3008
3009 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3010 if (!DeclHasAttr(newDecl, I)) {
3011 InheritableAttr *newAttr =
3012 cast<InheritableParamAttr>(I->clone(S.Context));
3013 newAttr->setInherited(true);
3014 newDecl->addAttr(newAttr);
3015 foundAny = true;
3016 }
3017 }
3018
3019 if (!foundAny) newDecl->dropAttrs();
3020}
3021
3022static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3023 const ParmVarDecl *OldParam,
3024 Sema &S) {
3025 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3026 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3027 if (*Oldnullability != *Newnullability) {
3028 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3029 << DiagNullabilityKind(
3030 *Newnullability,
3031 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3032 != 0))
3033 << DiagNullabilityKind(
3034 *Oldnullability,
3035 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3036 != 0));
3037 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3038 }
3039 } else {
3040 QualType NewT = NewParam->getType();
3041 NewT = S.Context.getAttributedType(
3042 AttributedType::getNullabilityAttrKind(*Oldnullability),
3043 NewT, NewT);
3044 NewParam->setType(NewT);
3045 }
3046 }
3047}
3048
3049namespace {
3050
3051/// Used in MergeFunctionDecl to keep track of function parameters in
3052/// C.
3053struct GNUCompatibleParamWarning {
3054 ParmVarDecl *OldParm;
3055 ParmVarDecl *NewParm;
3056 QualType PromotedType;
3057};
3058
3059} // end anonymous namespace
3060
3061// Determine whether the previous declaration was a definition, implicit
3062// declaration, or a declaration.
3063template <typename T>
3064static std::pair<diag::kind, SourceLocation>
3065getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3066 diag::kind PrevDiag;
3067 SourceLocation OldLocation = Old->getLocation();
3068 if (Old->isThisDeclarationADefinition())
3069 PrevDiag = diag::note_previous_definition;
3070 else if (Old->isImplicit()) {
3071 PrevDiag = diag::note_previous_implicit_declaration;
3072 if (OldLocation.isInvalid())
3073 OldLocation = New->getLocation();
3074 } else
3075 PrevDiag = diag::note_previous_declaration;
3076 return std::make_pair(PrevDiag, OldLocation);
3077}
3078
3079/// canRedefineFunction - checks if a function can be redefined. Currently,
3080/// only extern inline functions can be redefined, and even then only in
3081/// GNU89 mode.
3082static bool canRedefineFunction(const FunctionDecl *FD,
3083 const LangOptions& LangOpts) {
3084 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3085 !LangOpts.CPlusPlus &&
3086 FD->isInlineSpecified() &&
3087 FD->getStorageClass() == SC_Extern);
3088}
3089
3090const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3091 const AttributedType *AT = T->getAs<AttributedType>();
3092 while (AT && !AT->isCallingConv())
3093 AT = AT->getModifiedType()->getAs<AttributedType>();
3094 return AT;
3095}
3096
3097template <typename T>
3098static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3099 const DeclContext *DC = Old->getDeclContext();
3100 if (DC->isRecord())
3101 return false;
3102
3103 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3104 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3105 return true;
3106 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3107 return true;
3108 return false;
3109}
3110
3111template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3112static bool isExternC(VarTemplateDecl *) { return false; }
3113
3114/// Check whether a redeclaration of an entity introduced by a
3115/// using-declaration is valid, given that we know it's not an overload
3116/// (nor a hidden tag declaration).
3117template<typename ExpectedDecl>
3118static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3119 ExpectedDecl *New) {
3120 // C++11 [basic.scope.declarative]p4:
3121 // Given a set of declarations in a single declarative region, each of
3122 // which specifies the same unqualified name,
3123 // -- they shall all refer to the same entity, or all refer to functions
3124 // and function templates; or
3125 // -- exactly one declaration shall declare a class name or enumeration
3126 // name that is not a typedef name and the other declarations shall all
3127 // refer to the same variable or enumerator, or all refer to functions
3128 // and function templates; in this case the class name or enumeration
3129 // name is hidden (3.3.10).
3130
3131 // C++11 [namespace.udecl]p14:
3132 // If a function declaration in namespace scope or block scope has the
3133 // same name and the same parameter-type-list as a function introduced
3134 // by a using-declaration, and the declarations do not declare the same
3135 // function, the program is ill-formed.
3136
3137 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3138 if (Old &&
3139 !Old->getDeclContext()->getRedeclContext()->Equals(
3140 New->getDeclContext()->getRedeclContext()) &&
3141 !(isExternC(Old) && isExternC(New)))
3142 Old = nullptr;
3143
3144 if (!Old) {
3145 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3146 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3147 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
3148 return true;
3149 }
3150 return false;
3151}
3152
3153static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3154 const FunctionDecl *B) {
3155 assert(A->getNumParams() == B->getNumParams())((A->getNumParams() == B->getNumParams()) ? static_cast
<void> (0) : __assert_fail ("A->getNumParams() == B->getNumParams()"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 3155, __PRETTY_FUNCTION__))
;
3156
3157 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3158 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3159 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3160 if (AttrA == AttrB)
3161 return true;
3162 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3163 AttrA->isDynamic() == AttrB->isDynamic();
3164 };
3165
3166 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3167}
3168
3169/// If necessary, adjust the semantic declaration context for a qualified
3170/// declaration to name the correct inline namespace within the qualifier.
3171static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3172 DeclaratorDecl *OldD) {
3173 // The only case where we need to update the DeclContext is when
3174 // redeclaration lookup for a qualified name finds a declaration
3175 // in an inline namespace within the context named by the qualifier:
3176 //
3177 // inline namespace N { int f(); }
3178 // int ::f(); // Sema DC needs adjusting from :: to N::.
3179 //
3180 // For unqualified declarations, the semantic context *can* change
3181 // along the redeclaration chain (for local extern declarations,
3182 // extern "C" declarations, and friend declarations in particular).
3183 if (!NewD->getQualifier())
3184 return;
3185
3186 // NewD is probably already in the right context.
3187 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3188 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3189 if (NamedDC->Equals(SemaDC))
3190 return;
3191
3192 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||(((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->
isInvalidDecl() || OldD->isInvalidDecl()) && "unexpected context for redeclaration"
) ? static_cast<void> (0) : __assert_fail ("(NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl()) && \"unexpected context for redeclaration\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 3194, __PRETTY_FUNCTION__))
3193 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&(((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->
isInvalidDecl() || OldD->isInvalidDecl()) && "unexpected context for redeclaration"
) ? static_cast<void> (0) : __assert_fail ("(NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl()) && \"unexpected context for redeclaration\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 3194, __PRETTY_FUNCTION__))
3194 "unexpected context for redeclaration")(((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->
isInvalidDecl() || OldD->isInvalidDecl()) && "unexpected context for redeclaration"
) ? static_cast<void> (0) : __assert_fail ("(NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl()) && \"unexpected context for redeclaration\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 3194, __PRETTY_FUNCTION__))
;
3195
3196 auto *LexDC = NewD->getLexicalDeclContext();
3197 auto FixSemaDC = [=](NamedDecl *D) {
3198 if (!D)
3199 return;
3200 D->setDeclContext(SemaDC);
3201 D->setLexicalDeclContext(LexDC);
3202 };
3203
3204 FixSemaDC(NewD);
3205 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3206 FixSemaDC(FD->getDescribedFunctionTemplate());
3207 else if (auto *VD = dyn_cast<VarDecl>(NewD))
3208 FixSemaDC(VD->getDescribedVarTemplate());
3209}
3210
3211/// MergeFunctionDecl - We just parsed a function 'New' from
3212/// declarator D which has the same name and scope as a previous
3213/// declaration 'Old'. Figure out how to resolve this situation,
3214/// merging decls or emitting diagnostics as appropriate.
3215///
3216/// In C++, New and Old must be declarations that are not
3217/// overloaded. Use IsOverload to determine whether New and Old are
3218/// overloaded, and to select the Old declaration that New should be
3219/// merged with.
3220///
3221/// Returns true if there was an error, false otherwise.
3222bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3223 Scope *S, bool MergeTypeWithOld) {
3224 // Verify the old decl was also a function.
3225 FunctionDecl *Old = OldD->getAsFunction();
3226 if (!Old) {
3227 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3228 if (New->getFriendObjectKind()) {
3229 Diag(New->getLocation(), diag::err_using_decl_friend);
3230 Diag(Shadow->getTargetDecl()->getLocation(),
3231 diag::note_using_decl_target);
3232 Diag(Shadow->getUsingDecl()->getLocation(),
3233 diag::note_using_decl) << 0;
3234 return true;
3235 }
3236
3237 // Check whether the two declarations might declare the same function.
3238 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3239 return true;
3240 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3241 } else {
3242 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3243 << New->getDeclName();
3244 notePreviousDefinition(OldD, New->getLocation());
3245 return true;
3246 }
3247 }
3248
3249 // If the old declaration was found in an inline namespace and the new
3250 // declaration was qualified, update the DeclContext to match.
3251 adjustDeclContextForDeclaratorDecl(New, Old);
3252
3253 // If the old declaration is invalid, just give up here.
3254 if (Old->isInvalidDecl())
3255 return true;
3256
3257 // Disallow redeclaration of some builtins.
3258 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3259 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3260 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3261 << Old << Old->getType();
3262 return true;
3263 }
3264
3265 diag::kind PrevDiag;
3266 SourceLocation OldLocation;
3267 std::tie(PrevDiag, OldLocation) =
3268 getNoteDiagForInvalidRedeclaration(Old, New);
3269
3270 // Don't complain about this if we're in GNU89 mode and the old function
3271 // is an extern inline function.
3272 // Don't complain about specializations. They are not supposed to have
3273 // storage classes.
3274 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3275 New->getStorageClass() == SC_Static &&
3276 Old->hasExternalFormalLinkage() &&
3277 !New->getTemplateSpecializationInfo() &&
3278 !canRedefineFunction(Old, getLangOpts())) {
3279 if (getLangOpts().MicrosoftExt) {
3280 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3281 Diag(OldLocation, PrevDiag);
3282 } else {
3283 Diag(New->getLocation(), diag::err_static_non_static) << New;
3284 Diag(OldLocation, PrevDiag);
3285 return true;
3286 }
3287 }
3288
3289 if (New->hasAttr<InternalLinkageAttr>() &&
3290 !Old->hasAttr<InternalLinkageAttr>()) {
3291 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3292 << New->getDeclName();
3293 notePreviousDefinition(Old, New->getLocation());
3294 New->dropAttr<InternalLinkageAttr>();
3295 }
3296
3297 if (CheckRedeclarationModuleOwnership(New, Old))
3298 return true;
3299
3300 if (!getLangOpts().CPlusPlus) {
3301 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3302 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3303 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3304 << New << OldOvl;
3305
3306 // Try our best to find a decl that actually has the overloadable
3307 // attribute for the note. In most cases (e.g. programs with only one
3308 // broken declaration/definition), this won't matter.
3309 //
3310 // FIXME: We could do this if we juggled some extra state in
3311 // OverloadableAttr, rather than just removing it.
3312 const Decl *DiagOld = Old;
3313 if (OldOvl) {
3314 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3315 const auto *A = D->getAttr<OverloadableAttr>();
3316 return A && !A->isImplicit();
3317 });
3318 // If we've implicitly added *all* of the overloadable attrs to this
3319 // chain, emitting a "previous redecl" note is pointless.
3320 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3321 }
3322
3323 if (DiagOld)
3324 Diag(DiagOld->getLocation(),
3325 diag::note_attribute_overloadable_prev_overload)
3326 << OldOvl;
3327
3328 if (OldOvl)
3329 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3330 else
3331 New->dropAttr<OverloadableAttr>();
3332 }
3333 }
3334
3335 // If a function is first declared with a calling convention, but is later
3336 // declared or defined without one, all following decls assume the calling
3337 // convention of the first.
3338 //
3339 // It's OK if a function is first declared without a calling convention,
3340 // but is later declared or defined with the default calling convention.
3341 //
3342 // To test if either decl has an explicit calling convention, we look for
3343 // AttributedType sugar nodes on the type as written. If they are missing or
3344 // were canonicalized away, we assume the calling convention was implicit.
3345 //
3346 // Note also that we DO NOT return at this point, because we still have
3347 // other tests to run.
3348 QualType OldQType = Context.getCanonicalType(Old->getType());
3349 QualType NewQType = Context.getCanonicalType(New->getType());
3350 const FunctionType *OldType = cast<FunctionType>(OldQType);
3351 const FunctionType *NewType = cast<FunctionType>(NewQType);
3352 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3353 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3354 bool RequiresAdjustment = false;
3355
3356 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3357 FunctionDecl *First = Old->getFirstDecl();
3358 const FunctionType *FT =
3359 First->getType().getCanonicalType()->castAs<FunctionType>();
3360 FunctionType::ExtInfo FI = FT->getExtInfo();
3361 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3362 if (!NewCCExplicit) {
3363 // Inherit the CC from the previous declaration if it was specified
3364 // there but not here.
3365 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3366 RequiresAdjustment = true;
3367 } else if (Old->getBuiltinID()) {
3368 // Builtin attribute isn't propagated to the new one yet at this point,
3369 // so we check if the old one is a builtin.
3370
3371 // Calling Conventions on a Builtin aren't really useful and setting a
3372 // default calling convention and cdecl'ing some builtin redeclarations is
3373 // common, so warn and ignore the calling convention on the redeclaration.
3374 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3375 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3376 << (int)CallingConventionIgnoredReason::BuiltinFunction;
3377 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3378 RequiresAdjustment = true;
3379 } else {
3380 // Calling conventions aren't compatible, so complain.
3381 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3382 Diag(New->getLocation(), diag::err_cconv_change)
3383 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3384 << !FirstCCExplicit
3385 << (!FirstCCExplicit ? "" :
3386 FunctionType::getNameForCallConv(FI.getCC()));
3387
3388 // Put the note on the first decl, since it is the one that matters.
3389 Diag(First->getLocation(), diag::note_previous_declaration);
3390 return true;
3391 }
3392 }
3393
3394 // FIXME: diagnose the other way around?
3395 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3396 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3397 RequiresAdjustment = true;
3398 }
3399
3400 // Merge regparm attribute.
3401 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3402 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3403 if (NewTypeInfo.getHasRegParm()) {
3404 Diag(New->getLocation(), diag::err_regparm_mismatch)
3405 << NewType->getRegParmType()
3406 << OldType->getRegParmType();
3407 Diag(OldLocation, diag::note_previous_declaration);
3408 return true;
3409 }
3410
3411 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3412 RequiresAdjustment = true;
3413 }
3414
3415 // Merge ns_returns_retained attribute.
3416 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3417 if (NewTypeInfo.getProducesResult()) {
3418 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3419 << "'ns_returns_retained'";
3420 Diag(OldLocation, diag::note_previous_declaration);
3421 return true;
3422 }
3423
3424 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3425 RequiresAdjustment = true;
3426 }
3427
3428 if (OldTypeInfo.getNoCallerSavedRegs() !=
3429 NewTypeInfo.getNoCallerSavedRegs()) {
3430 if (NewTypeInfo.getNoCallerSavedRegs()) {
3431 AnyX86NoCallerSavedRegistersAttr *Attr =
3432 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3433 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3434 Diag(OldLocation, diag::note_previous_declaration);
3435 return true;
3436 }
3437
3438 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3439 RequiresAdjustment = true;
3440 }
3441
3442 if (RequiresAdjustment) {
3443 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3444 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3445 New->setType(QualType(AdjustedType, 0));
3446 NewQType = Context.getCanonicalType(New->getType());
3447 }
3448
3449 // If this redeclaration makes the function inline, we may need to add it to
3450 // UndefinedButUsed.
3451 if (!Old->isInlined() && New->isInlined() &&
3452 !New->hasAttr<GNUInlineAttr>() &&
3453 !getLangOpts().GNUInline &&
3454 Old->isUsed(false) &&
3455 !Old->isDefined() && !New->isThisDeclarationADefinition())
3456 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3457 SourceLocation()));
3458
3459 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3460 // about it.
3461 if (New->hasAttr<GNUInlineAttr>() &&
3462 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3463 UndefinedButUsed.erase(Old->getCanonicalDecl());
3464 }
3465
3466 // If pass_object_size params don't match up perfectly, this isn't a valid
3467 // redeclaration.
3468 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3469 !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3470 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3471 << New->getDeclName();
3472 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3473 return true;
3474 }
3475
3476 if (getLangOpts().CPlusPlus) {
3477 // C++1z [over.load]p2
3478 // Certain function declarations cannot be overloaded:
3479 // -- Function declarations that differ only in the return type,
3480 // the exception specification, or both cannot be overloaded.
3481
3482 // Check the exception specifications match. This may recompute the type of
3483 // both Old and New if it resolved exception specifications, so grab the
3484 // types again after this. Because this updates the type, we do this before
3485 // any of the other checks below, which may update the "de facto" NewQType
3486 // but do not necessarily update the type of New.
3487 if (CheckEquivalentExceptionSpec(Old, New))
3488 return true;
3489 OldQType = Context.getCanonicalType(Old->getType());
3490 NewQType = Context.getCanonicalType(New->getType());
3491
3492 // Go back to the type source info to compare the declared return types,
3493 // per C++1y [dcl.type.auto]p13:
3494 // Redeclarations or specializations of a function or function template
3495 // with a declared return type that uses a placeholder type shall also
3496 // use that placeholder, not a deduced type.
3497 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3498 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3499 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3500 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3501 OldDeclaredReturnType)) {
3502 QualType ResQT;
3503 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3504 OldDeclaredReturnType->isObjCObjectPointerType())
3505 // FIXME: This does the wrong thing for a deduced return type.
3506 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3507 if (ResQT.isNull()) {
3508 if (New->isCXXClassMember() && New->isOutOfLine())
3509 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3510 << New << New->getReturnTypeSourceRange();
3511 else
3512 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3513 << New->getReturnTypeSourceRange();
3514 Diag(OldLocation, PrevDiag) << Old << Old->getType()
3515 << Old->getReturnTypeSourceRange();
3516 return true;
3517 }
3518 else
3519 NewQType = ResQT;
3520 }
3521
3522 QualType OldReturnType = OldType->getReturnType();
3523 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3524 if (OldReturnType != NewReturnType) {
3525 // If this function has a deduced return type and has already been
3526 // defined, copy the deduced value from the old declaration.
3527 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3528 if (OldAT && OldAT->isDeduced()) {
3529 New->setType(
3530 SubstAutoType(New->getType(),
3531 OldAT->isDependentType() ? Context.DependentTy
3532 : OldAT->getDeducedType()));
3533 NewQType = Context.getCanonicalType(
3534 SubstAutoType(NewQType,
3535 OldAT->isDependentType() ? Context.DependentTy
3536 : OldAT->getDeducedType()));
3537 }
3538 }
3539
3540 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3541 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3542 if (OldMethod && NewMethod) {
3543 // Preserve triviality.
3544 NewMethod->setTrivial(OldMethod->isTrivial());
3545
3546 // MSVC allows explicit template specialization at class scope:
3547 // 2 CXXMethodDecls referring to the same function will be injected.
3548 // We don't want a redeclaration error.
3549 bool IsClassScopeExplicitSpecialization =
3550 OldMethod->isFunctionTemplateSpecialization() &&
3551 NewMethod->isFunctionTemplateSpecialization();
3552 bool isFriend = NewMethod->getFriendObjectKind();
3553
3554 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3555 !IsClassScopeExplicitSpecialization) {
3556 // -- Member function declarations with the same name and the
3557 // same parameter types cannot be overloaded if any of them
3558 // is a static member function declaration.
3559 if (OldMethod->isStatic() != NewMethod->isStatic()) {
3560 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3561 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3562 return true;
3563 }
3564
3565 // C++ [class.mem]p1:
3566 // [...] A member shall not be declared twice in the
3567 // member-specification, except that a nested class or member
3568 // class template can be declared and then later defined.
3569 if (!inTemplateInstantiation()) {
3570 unsigned NewDiag;
3571 if (isa<CXXConstructorDecl>(OldMethod))
3572 NewDiag = diag::err_constructor_redeclared;
3573 else if (isa<CXXDestructorDecl>(NewMethod))
3574 NewDiag = diag::err_destructor_redeclared;
3575 else if (isa<CXXConversionDecl>(NewMethod))
3576 NewDiag = diag::err_conv_function_redeclared;
3577 else
3578 NewDiag = diag::err_member_redeclared;
3579
3580 Diag(New->getLocation(), NewDiag);
3581 } else {
3582 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3583 << New << New->getType();
3584 }
3585 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3586 return true;
3587
3588 // Complain if this is an explicit declaration of a special
3589 // member that was initially declared implicitly.
3590 //
3591 // As an exception, it's okay to befriend such methods in order
3592 // to permit the implicit constructor/destructor/operator calls.
3593 } else if (OldMethod->isImplicit()) {
3594 if (isFriend) {
3595 NewMethod->setImplicit();
3596 } else {
3597 Diag(NewMethod->getLocation(),
3598 diag::err_definition_of_implicitly_declared_member)
3599 << New << getSpecialMember(OldMethod);
3600 return true;
3601 }
3602 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3603 Diag(NewMethod->getLocation(),
3604 diag::err_definition_of_explicitly_defaulted_member)
3605 << getSpecialMember(OldMethod);
3606 return true;
3607 }
3608 }
3609
3610 // C++11 [dcl.attr.noreturn]p1:
3611 // The first declaration of a function shall specify the noreturn
3612 // attribute if any declaration of that function specifies the noreturn
3613 // attribute.
3614 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3615 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3616 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3617 Diag(Old->getFirstDecl()->getLocation(),
3618 diag::note_noreturn_missing_first_decl);
3619 }
3620
3621 // C++11 [dcl.attr.depend]p2:
3622 // The first declaration of a function shall specify the
3623 // carries_dependency attribute for its declarator-id if any declaration
3624 // of the function specifies the carries_dependency attribute.
3625 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3626 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3627 Diag(CDA->getLocation(),
3628 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3629 Diag(Old->getFirstDecl()->getLocation(),
3630 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3631 }
3632
3633 // (C++98 8.3.5p3):
3634 // All declarations for a function shall agree exactly in both the
3635 // return type and the parameter-type-list.
3636 // We also want to respect all the extended bits except noreturn.
3637
3638 // noreturn should now match unless the old type info didn't have it.
3639 QualType OldQTypeForComparison = OldQType;
3640 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3641 auto *OldType = OldQType->castAs<FunctionProtoType>();
3642 const FunctionType *OldTypeForComparison
3643 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3644 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3645 assert(OldQTypeForComparison.isCanonical())((OldQTypeForComparison.isCanonical()) ? static_cast<void>
(0) : __assert_fail ("OldQTypeForComparison.isCanonical()", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 3645, __PRETTY_FUNCTION__))
;
3646 }
3647
3648 if (haveIncompatibleLanguageLinkages(Old, New)) {
3649 // As a special case, retain the language linkage from previous
3650 // declarations of a friend function as an extension.
3651 //
3652 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3653 // and is useful because there's otherwise no way to specify language
3654 // linkage within class scope.
3655 //
3656 // Check cautiously as the friend object kind isn't yet complete.
3657 if (New->getFriendObjectKind() != Decl::FOK_None) {
3658 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3659 Diag(OldLocation, PrevDiag);
3660 } else {
3661 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3662 Diag(OldLocation, PrevDiag);
3663 return true;
3664 }
3665 }
3666
3667 // If the function types are compatible, merge the declarations. Ignore the
3668 // exception specifier because it was already checked above in
3669 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3670 // about incompatible types under -fms-compatibility.
3671 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3672 NewQType))
3673 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3674
3675 // If the types are imprecise (due to dependent constructs in friends or
3676 // local extern declarations), it's OK if they differ. We'll check again
3677 // during instantiation.
3678 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3679 return false;
3680
3681 // Fall through for conflicting redeclarations and redefinitions.
3682 }
3683
3684 // C: Function types need to be compatible, not identical. This handles
3685 // duplicate function decls like "void f(int); void f(enum X);" properly.
3686 if (!getLangOpts().CPlusPlus &&
3687 Context.typesAreCompatible(OldQType, NewQType)) {
3688 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3689 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3690 const FunctionProtoType *OldProto = nullptr;
3691 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3692 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3693 // The old declaration provided a function prototype, but the
3694 // new declaration does not. Merge in the prototype.
3695 assert(!OldProto->hasExceptionSpec() && "Exception spec in C")((!OldProto->hasExceptionSpec() && "Exception spec in C"
) ? static_cast<void> (0) : __assert_fail ("!OldProto->hasExceptionSpec() && \"Exception spec in C\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 3695, __PRETTY_FUNCTION__))
;
3696 SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3697 NewQType =
3698 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3699 OldProto->getExtProtoInfo());
3700 New->setType(NewQType);
3701 New->setHasInheritedPrototype();
3702
3703 // Synthesize parameters with the same types.
3704 SmallVector<ParmVarDecl*, 16> Params;
3705 for (const auto &ParamType : OldProto->param_types()) {
3706 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3707 SourceLocation(), nullptr,
3708 ParamType, /*TInfo=*/nullptr,
3709 SC_None, nullptr);
3710 Param->setScopeInfo(0, Params.size());
3711 Param->setImplicit();
3712 Params.push_back(Param);
3713 }
3714
3715 New->setParams(Params);
3716 }
3717
3718 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3719 }
3720
3721 // Check if the function types are compatible when pointer size address
3722 // spaces are ignored.
3723 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
3724 return false;
3725
3726 // GNU C permits a K&R definition to follow a prototype declaration
3727 // if the declared types of the parameters in the K&R definition
3728 // match the types in the prototype declaration, even when the
3729 // promoted types of the parameters from the K&R definition differ
3730 // from the types in the prototype. GCC then keeps the types from
3731 // the prototype.
3732 //
3733 // If a variadic prototype is followed by a non-variadic K&R definition,
3734 // the K&R definition becomes variadic. This is sort of an edge case, but
3735 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3736 // C99 6.9.1p8.
3737 if (!getLangOpts().CPlusPlus &&
3738 Old->hasPrototype() && !New->hasPrototype() &&
3739 New->getType()->getAs<FunctionProtoType>() &&
3740 Old->getNumParams() == New->getNumParams()) {
3741 SmallVector<QualType, 16> ArgTypes;
3742 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3743 const FunctionProtoType *OldProto
3744 = Old->getType()->getAs<FunctionProtoType>();
3745 const FunctionProtoType *NewProto
3746 = New->getType()->getAs<FunctionProtoType>();
3747
3748 // Determine whether this is the GNU C extension.
3749 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3750 NewProto->getReturnType());
3751 bool LooseCompatible = !MergedReturn.isNull();
3752 for (unsigned Idx = 0, End = Old->getNumParams();
3753 LooseCompatible && Idx != End; ++Idx) {
3754 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3755 ParmVarDecl *NewParm = New->getParamDecl(Idx);
3756 if (Context.typesAreCompatible(OldParm->getType(),
3757 NewProto->getParamType(Idx))) {
3758 ArgTypes.push_back(NewParm->getType());
3759 } else if (Context.typesAreCompatible(OldParm->getType(),
3760 NewParm->getType(),
3761 /*CompareUnqualified=*/true)) {
3762 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3763 NewProto->getParamType(Idx) };
3764 Warnings.push_back(Warn);
3765 ArgTypes.push_back(NewParm->getType());
3766 } else
3767 LooseCompatible = false;
3768 }
3769
3770 if (LooseCompatible) {
3771 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3772 Diag(Warnings[Warn].NewParm->getLocation(),
3773 diag::ext_param_promoted_not_compatible_with_prototype)
3774 << Warnings[Warn].PromotedType
3775 << Warnings[Warn].OldParm->getType();
3776 if (Warnings[Warn].OldParm->getLocation().isValid())
3777 Diag(Warnings[Warn].OldParm->getLocation(),
3778 diag::note_previous_declaration);
3779 }
3780
3781 if (MergeTypeWithOld)
3782 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3783 OldProto->getExtProtoInfo()));
3784 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3785 }
3786
3787 // Fall through to diagnose conflicting types.
3788 }
3789
3790 // A function that has already been declared has been redeclared or
3791 // defined with a different type; show an appropriate diagnostic.
3792
3793 // If the previous declaration was an implicitly-generated builtin
3794 // declaration, then at the very least we should use a specialized note.
3795 unsigned BuiltinID;
3796 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3797 // If it's actually a library-defined builtin function like 'malloc'
3798 // or 'printf', just warn about the incompatible redeclaration.
3799 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3800 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3801 Diag(OldLocation, diag::note_previous_builtin_declaration)
3802 << Old << Old->getType();
3803 return false;
3804 }
3805
3806 PrevDiag = diag::note_previous_builtin_declaration;
3807 }
3808
3809 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3810 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3811 return true;
3812}
3813
3814/// Completes the merge of two function declarations that are
3815/// known to be compatible.
3816///
3817/// This routine handles the merging of attributes and other
3818/// properties of function declarations from the old declaration to
3819/// the new declaration, once we know that New is in fact a
3820/// redeclaration of Old.
3821///
3822/// \returns false
3823bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3824 Scope *S, bool MergeTypeWithOld) {
3825 // Merge the attributes
3826 mergeDeclAttributes(New, Old);
3827
3828 // Merge "pure" flag.
3829 if (Old->isPure())
3830 New->setPure();
3831
3832 // Merge "used" flag.
3833 if (Old->getMostRecentDecl()->isUsed(false))
3834 New->setIsUsed();
3835
3836 // Merge attributes from the parameters. These can mismatch with K&R
3837 // declarations.
3838 if (New->getNumParams() == Old->getNumParams())
3839 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3840 ParmVarDecl *NewParam = New->getParamDecl(i);
3841 ParmVarDecl *OldParam = Old->getParamDecl(i);
3842 mergeParamDeclAttributes(NewParam, OldParam, *this);
3843 mergeParamDeclTypes(NewParam, OldParam, *this);
3844 }
3845
3846 if (getLangOpts().CPlusPlus)
3847 return MergeCXXFunctionDecl(New, Old, S);
3848
3849 // Merge the function types so the we get the composite types for the return
3850 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3851 // was visible.
3852 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3853 if (!Merged.isNull() && MergeTypeWithOld)
3854 New->setType(Merged);
3855
3856 return false;
3857}
3858
3859void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3860 ObjCMethodDecl *oldMethod) {
3861 // Merge the attributes, including deprecated/unavailable
3862 AvailabilityMergeKind MergeKind =
3863 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3864 ? AMK_ProtocolImplementation
3865 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3866 : AMK_Override;
3867
3868 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3869
3870 // Merge attributes from the parameters.
3871 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3872 oe = oldMethod->param_end();
3873 for (ObjCMethodDecl::param_iterator
3874 ni = newMethod->param_begin(), ne = newMethod->param_end();
3875 ni != ne && oi != oe; ++ni, ++oi)
3876 mergeParamDeclAttributes(*ni, *oi, *this);
3877
3878 CheckObjCMethodOverride(newMethod, oldMethod);
3879}
3880
3881static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3882 assert(!S.Context.hasSameType(New->getType(), Old->getType()))((!S.Context.hasSameType(New->getType(), Old->getType()
)) ? static_cast<void> (0) : __assert_fail ("!S.Context.hasSameType(New->getType(), Old->getType())"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 3882, __PRETTY_FUNCTION__))
;
3883
3884 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3885 ? diag::err_redefinition_different_type
3886 : diag::err_redeclaration_different_type)
3887 << New->getDeclName() << New->getType() << Old->getType();
3888
3889 diag::kind PrevDiag;
3890 SourceLocation OldLocation;
3891 std::tie(PrevDiag, OldLocation)
3892 = getNoteDiagForInvalidRedeclaration(Old, New);
3893 S.Diag(OldLocation, PrevDiag);
3894 New->setInvalidDecl();
3895}
3896
3897/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3898/// scope as a previous declaration 'Old'. Figure out how to merge their types,
3899/// emitting diagnostics as appropriate.
3900///
3901/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3902/// to here in AddInitializerToDecl. We can't check them before the initializer
3903/// is attached.
3904void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3905 bool MergeTypeWithOld) {
3906 if (New->isInvalidDecl() || Old->isInvalidDecl())
3907 return;
3908
3909 QualType MergedT;
3910 if (getLangOpts().CPlusPlus) {
3911 if (New->getType()->isUndeducedType()) {
3912 // We don't know what the new type is until the initializer is attached.
3913 return;
3914 } else if (Context.hasSameType(New->getType(), Old->getType())) {
3915 // These could still be something that needs exception specs checked.
3916 return MergeVarDeclExceptionSpecs(New, Old);
3917 }
3918 // C++ [basic.link]p10:
3919 // [...] the types specified by all declarations referring to a given
3920 // object or function shall be identical, except that declarations for an
3921 // array object can specify array types that differ by the presence or
3922 // absence of a major array bound (8.3.4).
3923 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3924 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3925 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3926
3927 // We are merging a variable declaration New into Old. If it has an array
3928 // bound, and that bound differs from Old's bound, we should diagnose the
3929 // mismatch.
3930 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3931 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3932 PrevVD = PrevVD->getPreviousDecl()) {
3933 QualType PrevVDTy = PrevVD->getType();
3934 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3935 continue;
3936
3937 if (!Context.hasSameType(New->getType(), PrevVDTy))
3938 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3939 }
3940 }
3941
3942 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3943 if (Context.hasSameType(OldArray->getElementType(),
3944 NewArray->getElementType()))
3945 MergedT = New->getType();
3946 }
3947 // FIXME: Check visibility. New is hidden but has a complete type. If New
3948 // has no array bound, it should not inherit one from Old, if Old is not
3949 // visible.
3950 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3951 if (Context.hasSameType(OldArray->getElementType(),
3952 NewArray->getElementType()))
3953 MergedT = Old->getType();
3954 }
3955 }
3956 else if (New->getType()->isObjCObjectPointerType() &&
3957 Old->getType()->isObjCObjectPointerType()) {
3958 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3959 Old->getType());
3960 }
3961 } else {
3962 // C 6.2.7p2:
3963 // All declarations that refer to the same object or function shall have
3964 // compatible type.
3965 MergedT = Context.mergeTypes(New->getType(), Old->getType());
3966 }
3967 if (MergedT.isNull()) {
3968 // It's OK if we couldn't merge types if either type is dependent, for a
3969 // block-scope variable. In other cases (static data members of class
3970 // templates, variable templates, ...), we require the types to be
3971 // equivalent.
3972 // FIXME: The C++ standard doesn't say anything about this.
3973 if ((New->getType()->isDependentType() ||
3974 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3975 // If the old type was dependent, we can't merge with it, so the new type
3976 // becomes dependent for now. We'll reproduce the original type when we
3977 // instantiate the TypeSourceInfo for the variable.
3978 if (!New->getType()->isDependentType() && MergeTypeWithOld)
3979 New->setType(Context.DependentTy);
3980 return;
3981 }
3982 return diagnoseVarDeclTypeMismatch(*this, New, Old);
3983 }
3984
3985 // Don't actually update the type on the new declaration if the old
3986 // declaration was an extern declaration in a different scope.
3987 if (MergeTypeWithOld)
3988 New->setType(MergedT);
3989}
3990
3991static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3992 LookupResult &Previous) {
3993 // C11 6.2.7p4:
3994 // For an identifier with internal or external linkage declared
3995 // in a scope in which a prior declaration of that identifier is
3996 // visible, if the prior declaration specifies internal or
3997 // external linkage, the type of the identifier at the later
3998 // declaration becomes the composite type.
3999 //
4000 // If the variable isn't visible, we do not merge with its type.
4001 if (Previous.isShadowed())
4002 return false;
4003
4004 if (S.getLangOpts().CPlusPlus) {
4005 // C++11 [dcl.array]p3:
4006 // If there is a preceding declaration of the entity in the same
4007 // scope in which the bound was specified, an omitted array bound
4008 // is taken to be the same as in that earlier declaration.
4009 return NewVD->isPreviousDeclInSameBlockScope() ||
4010 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4011 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4012 } else {
4013 // If the old declaration was function-local, don't merge with its
4014 // type unless we're in the same function.
4015 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4016 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4017 }
4018}
4019
4020/// MergeVarDecl - We just parsed a variable 'New' which has the same name
4021/// and scope as a previous declaration 'Old'. Figure out how to resolve this
4022/// situation, merging decls or emitting diagnostics as appropriate.
4023///
4024/// Tentative definition rules (C99 6.9.2p2) are checked by
4025/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4026/// definitions here, since the initializer hasn't been attached.
4027///
4028void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4029 // If the new decl is already invalid, don't do any other checking.
4030 if (New->isInvalidDecl())
4031 return;
4032
4033 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4034 return;
4035
4036 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4037
4038 // Verify the old decl was also a variable or variable template.
4039 VarDecl *Old = nullptr;
4040 VarTemplateDecl *OldTemplate = nullptr;
4041 if (Previous.isSingleResult()) {
4042 if (NewTemplate) {
4043 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4044 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4045
4046 if (auto *Shadow =
4047 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4048 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4049 return New->setInvalidDecl();
4050 } else {
4051 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4052
4053 if (auto *Shadow =
4054 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4055 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4056 return New->setInvalidDecl();
4057 }
4058 }
4059 if (!Old) {
4060 Diag(New->getLocation(), diag::err_redefinition_different_kind)
4061 << New->getDeclName();
4062 notePreviousDefinition(Previous.getRepresentativeDecl(),
4063 New->getLocation());
4064 return New->setInvalidDecl();
4065 }
4066
4067 // If the old declaration was found in an inline namespace and the new
4068 // declaration was qualified, update the DeclContext to match.
4069 adjustDeclContextForDeclaratorDecl(New, Old);
4070
4071 // Ensure the template parameters are compatible.
4072 if (NewTemplate &&
4073 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4074 OldTemplate->getTemplateParameters(),
4075 /*Complain=*/true, TPL_TemplateMatch))
4076 return New->setInvalidDecl();
4077
4078 // C++ [class.mem]p1:
4079 // A member shall not be declared twice in the member-specification [...]
4080 //
4081 // Here, we need only consider static data members.
4082 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4083 Diag(New->getLocation(), diag::err_duplicate_member)
4084 << New->getIdentifier();
4085 Diag(Old->getLocation(), diag::note_previous_declaration);
4086 New->setInvalidDecl();
4087 }
4088
4089 mergeDeclAttributes(New, Old);
4090 // Warn if an already-declared variable is made a weak_import in a subsequent
4091 // declaration
4092 if (New->hasAttr<WeakImportAttr>() &&
4093 Old->getStorageClass() == SC_None &&
4094 !Old->hasAttr<WeakImportAttr>()) {
4095 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4096 notePreviousDefinition(Old, New->getLocation());
4097 // Remove weak_import attribute on new declaration.
4098 New->dropAttr<WeakImportAttr>();
4099 }
4100
4101 if (New->hasAttr<InternalLinkageAttr>() &&
4102 !Old->hasAttr<InternalLinkageAttr>()) {
4103 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
4104 << New->getDeclName();
4105 notePreviousDefinition(Old, New->getLocation());
4106 New->dropAttr<InternalLinkageAttr>();
4107 }
4108
4109 // Merge the types.
4110 VarDecl *MostRecent = Old->getMostRecentDecl();
4111 if (MostRecent != Old) {
4112 MergeVarDeclTypes(New, MostRecent,
4113 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4114 if (New->isInvalidDecl())
4115 return;
4116 }
4117
4118 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4119 if (New->isInvalidDecl())
4120 return;
4121
4122 diag::kind PrevDiag;
4123 SourceLocation OldLocation;
4124 std::tie(PrevDiag, OldLocation) =
4125 getNoteDiagForInvalidRedeclaration(Old, New);
4126
4127 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4128 if (New->getStorageClass() == SC_Static &&
4129 !New->isStaticDataMember() &&
4130 Old->hasExternalFormalLinkage()) {
4131 if (getLangOpts().MicrosoftExt) {
4132 Diag(New->getLocation(), diag::ext_static_non_static)
4133 << New->getDeclName();
4134 Diag(OldLocation, PrevDiag);
4135 } else {
4136 Diag(New->getLocation(), diag::err_static_non_static)
4137 << New->getDeclName();
4138 Diag(OldLocation, PrevDiag);
4139 return New->setInvalidDecl();
4140 }
4141 }
4142 // C99 6.2.2p4:
4143 // For an identifier declared with the storage-class specifier
4144 // extern in a scope in which a prior declaration of that
4145 // identifier is visible,23) if the prior declaration specifies
4146 // internal or external linkage, the linkage of the identifier at
4147 // the later declaration is the same as the linkage specified at
4148 // the prior declaration. If no prior declaration is visible, or
4149 // if the prior declaration specifies no linkage, then the
4150 // identifier has external linkage.
4151 if (New->hasExternalStorage() && Old->hasLinkage())
4152 /* Okay */;
4153 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4154 !New->isStaticDataMember() &&
4155 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4156 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4157 Diag(OldLocation, PrevDiag);
4158 return New->setInvalidDecl();
4159 }
4160
4161 // Check if extern is followed by non-extern and vice-versa.
4162 if (New->hasExternalStorage() &&
4163 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4164 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4165 Diag(OldLocation, PrevDiag);
4166 return New->setInvalidDecl();
4167 }
4168 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4169 !New->hasExternalStorage()) {
4170 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4171 Diag(OldLocation, PrevDiag);
4172 return New->setInvalidDecl();
4173 }
4174
4175 if (CheckRedeclarationModuleOwnership(New, Old))
4176 return;
4177
4178 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4179
4180 // FIXME: The test for external storage here seems wrong? We still
4181 // need to check for mismatches.
4182 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4183 // Don't complain about out-of-line definitions of static members.
4184 !(Old->getLexicalDeclContext()->isRecord() &&
4185 !New->getLexicalDeclContext()->isRecord())) {
4186 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4187 Diag(OldLocation, PrevDiag);
4188 return New->setInvalidDecl();
4189 }
4190
4191 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4192 if (VarDecl *Def = Old->getDefinition()) {
4193 // C++1z [dcl.fcn.spec]p4:
4194 // If the definition of a variable appears in a translation unit before
4195 // its first declaration as inline, the program is ill-formed.
4196 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4197 Diag(Def->getLocation(), diag::note_previous_definition);
4198 }
4199 }
4200
4201 // If this redeclaration makes the variable inline, we may need to add it to
4202 // UndefinedButUsed.
4203 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4204 !Old->getDefinition() && !New->isThisDeclarationADefinition())
4205 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4206 SourceLocation()));
4207
4208 if (New->getTLSKind() != Old->getTLSKind()) {
4209 if (!Old->getTLSKind()) {
4210 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4211 Diag(OldLocation, PrevDiag);
4212 } else if (!New->getTLSKind()) {
4213 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4214 Diag(OldLocation, PrevDiag);
4215 } else {
4216 // Do not allow redeclaration to change the variable between requiring
4217 // static and dynamic initialization.
4218 // FIXME: GCC allows this, but uses the TLS keyword on the first
4219 // declaration to determine the kind. Do we need to be compatible here?
4220 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4221 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4222 Diag(OldLocation, PrevDiag);
4223 }
4224 }
4225
4226 // C++ doesn't have tentative definitions, so go right ahead and check here.
4227 if (getLangOpts().CPlusPlus &&
4228 New->isThisDeclarationADefinition() == VarDecl::Definition) {
4229 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4230 Old->getCanonicalDecl()->isConstexpr()) {
4231 // This definition won't be a definition any more once it's been merged.
4232 Diag(New->getLocation(),
4233 diag::warn_deprecated_redundant_constexpr_static_def);
4234 } else if (VarDecl *Def = Old->getDefinition()) {
4235 if (checkVarDeclRedefinition(Def, New))
4236 return;
4237 }
4238 }
4239
4240 if (haveIncompatibleLanguageLinkages(Old, New)) {
4241 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4242 Diag(OldLocation, PrevDiag);
4243 New->setInvalidDecl();
4244 return;
4245 }
4246
4247 // Merge "used" flag.
4248 if (Old->getMostRecentDecl()->isUsed(false))
4249 New->setIsUsed();
4250
4251 // Keep a chain of previous declarations.
4252 New->setPreviousDecl(Old);
4253 if (NewTemplate)
4254 NewTemplate->setPreviousDecl(OldTemplate);
4255
4256 // Inherit access appropriately.
4257 New->setAccess(Old->getAccess());
4258 if (NewTemplate)
4259 NewTemplate->setAccess(New->getAccess());
4260
4261 if (Old->isInline())
4262 New->setImplicitlyInline();
4263}
4264
4265void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4266 SourceManager &SrcMgr = getSourceManager();
4267 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4268 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4269 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4270 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4271 auto &HSI = PP.getHeaderSearchInfo();
4272 StringRef HdrFilename =
4273 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4274
4275 auto noteFromModuleOrInclude = [&](Module *Mod,
4276 SourceLocation IncLoc) -> bool {
4277 // Redefinition errors with modules are common with non modular mapped
4278 // headers, example: a non-modular header H in module A that also gets
4279 // included directly in a TU. Pointing twice to the same header/definition
4280 // is confusing, try to get better diagnostics when modules is on.
4281 if (IncLoc.isValid()) {
4282 if (Mod) {
4283 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4284 << HdrFilename.str() << Mod->getFullModuleName();
4285 if (!Mod->DefinitionLoc.isInvalid())
4286 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4287 << Mod->getFullModuleName();
4288 } else {
4289 Diag(IncLoc, diag::note_redefinition_include_same_file)
4290 << HdrFilename.str();
4291 }
4292 return true;
4293 }
4294
4295 return false;
4296 };
4297
4298 // Is it the same file and same offset? Provide more information on why
4299 // this leads to a redefinition error.
4300 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4301 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4302 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4303 bool EmittedDiag =
4304 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4305 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4306
4307 // If the header has no guards, emit a note suggesting one.
4308 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4309 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4310
4311 if (EmittedDiag)
4312 return;
4313 }
4314
4315 // Redefinition coming from different files or couldn't do better above.
4316 if (Old->getLocation().isValid())
4317 Diag(Old->getLocation(), diag::note_previous_definition);
4318}
4319
4320/// We've just determined that \p Old and \p New both appear to be definitions
4321/// of the same variable. Either diagnose or fix the problem.
4322bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4323 if (!hasVisibleDefinition(Old) &&
4324 (New->getFormalLinkage() == InternalLinkage ||
4325 New->isInline() ||
4326 New->getDescribedVarTemplate() ||
4327 New->getNumTemplateParameterLists() ||
4328 New->getDeclContext()->isDependentContext())) {
4329 // The previous definition is hidden, and multiple definitions are
4330 // permitted (in separate TUs). Demote this to a declaration.
4331 New->demoteThisDefinitionToDeclaration();
4332
4333 // Make the canonical definition visible.
4334 if (auto *OldTD = Old->getDescribedVarTemplate())
4335 makeMergedDefinitionVisible(OldTD);
4336 makeMergedDefinitionVisible(Old);
4337 return false;
4338 } else {
4339 Diag(New->getLocation(), diag::err_redefinition) << New;
4340 notePreviousDefinition(Old, New->getLocation());
4341 New->setInvalidDecl();
4342 return true;
4343 }
4344}
4345
4346/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4347/// no declarator (e.g. "struct foo;") is parsed.
4348Decl *
4349Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4350 RecordDecl *&AnonRecord) {
4351 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4352 AnonRecord);
4353}
4354
4355// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4356// disambiguate entities defined in different scopes.
4357// While the VS2015 ABI fixes potential miscompiles, it is also breaks
4358// compatibility.
4359// We will pick our mangling number depending on which version of MSVC is being
4360// targeted.
4361static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4362 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4363 ? S->getMSCurManglingNumber()
4364 : S->getMSLastManglingNumber();
4365}
4366
4367void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4368 if (!Context.getLangOpts().CPlusPlus)
4369 return;
4370
4371 if (isa<CXXRecordDecl>(Tag->getParent())) {
4372 // If this tag is the direct child of a class, number it if
4373 // it is anonymous.
4374 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4375 return;
4376 MangleNumberingContext &MCtx =
4377 Context.getManglingNumberContext(Tag->getParent());
4378 Context.setManglingNumber(
4379 Tag, MCtx.getManglingNumber(
4380 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4381 return;
4382 }
4383
4384 // If this tag isn't a direct child of a class, number it if it is local.
4385 MangleNumberingContext *MCtx;
4386 Decl *ManglingContextDecl;
4387 std::tie(MCtx, ManglingContextDecl) =
4388 getCurrentMangleNumberContext(Tag->getDeclContext());
4389 if (MCtx) {
4390 Context.setManglingNumber(
4391 Tag, MCtx->getManglingNumber(
4392 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4393 }
4394}
4395
4396namespace {
4397struct NonCLikeKind {
4398 enum {
4399 None,
4400 BaseClass,
4401 DefaultMemberInit,
4402 Lambda,
4403 Friend,
4404 OtherMember,
4405 Invalid,
4406 } Kind = None;
4407 SourceRange Range;
4408
4409 explicit operator bool() { return Kind != None; }
4410};
4411}
4412
4413/// Determine whether a class is C-like, according to the rules of C++
4414/// [dcl.typedef] for anonymous classes with typedef names for linkage.
4415static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4416 if (RD->isInvalidDecl())
4417 return {NonCLikeKind::Invalid, {}};
4418
4419 // C++ [dcl.typedef]p9: [P1766R1]
4420 // An unnamed class with a typedef name for linkage purposes shall not
4421 //
4422 // -- have any base classes
4423 if (RD->getNumBases())
4424 return {NonCLikeKind::BaseClass,
4425 SourceRange(RD->bases_begin()->getBeginLoc(),
4426 RD->bases_end()[-1].getEndLoc())};
4427 bool Invalid = false;
4428 for (Decl *D : RD->decls()) {
4429 // Don't complain about things we already diagnosed.
4430 if (D->isInvalidDecl()) {
4431 Invalid = true;
4432 continue;
4433 }
4434
4435 // -- have any [...] default member initializers
4436 if (auto *FD = dyn_cast<FieldDecl>(D)) {
4437 if (FD->hasInClassInitializer()) {
4438 auto *Init = FD->getInClassInitializer();
4439 return {NonCLikeKind::DefaultMemberInit,
4440 Init ? Init->getSourceRange() : D->getSourceRange()};
4441 }
4442 continue;
4443 }
4444
4445 // FIXME: We don't allow friend declarations. This violates the wording of
4446 // P1766, but not the intent.
4447 if (isa<FriendDecl>(D))
4448 return {NonCLikeKind::Friend, D->getSourceRange()};
4449
4450 // -- declare any members other than non-static data members, member
4451 // enumerations, or member classes,
4452 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4453 isa<EnumDecl>(D))
4454 continue;
4455 auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4456 if (!MemberRD) {
4457 if (D->isImplicit())
4458 continue;
4459 return {NonCLikeKind::OtherMember, D->getSourceRange()};
4460 }
4461
4462 // -- contain a lambda-expression,
4463 if (MemberRD->isLambda())
4464 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4465
4466 // and all member classes shall also satisfy these requirements
4467 // (recursively).
4468 if (MemberRD->isThisDeclarationADefinition()) {
4469 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4470 return Kind;
4471 }
4472 }
4473
4474 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4475}
4476
4477void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4478 TypedefNameDecl *NewTD) {
4479 if (TagFromDeclSpec->isInvalidDecl())
4480 return;
4481
4482 // Do nothing if the tag already has a name for linkage purposes.
4483 if (TagFromDeclSpec->hasNameForLinkage())
4484 return;
4485
4486 // A well-formed anonymous tag must always be a TUK_Definition.
4487 assert(TagFromDeclSpec->isThisDeclarationADefinition())((TagFromDeclSpec->isThisDeclarationADefinition()) ? static_cast
<void> (0) : __assert_fail ("TagFromDeclSpec->isThisDeclarationADefinition()"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 4487, __PRETTY_FUNCTION__))
;
4488
4489 // The type must match the tag exactly; no qualifiers allowed.
4490 if (!Context.hasSameType(NewTD->getUnderlyingType(),
4491 Context.getTagDeclType(TagFromDeclSpec))) {
4492 if (getLangOpts().CPlusPlus)
4493 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4494 return;
4495 }
4496
4497 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4498 // An unnamed class with a typedef name for linkage purposes shall [be
4499 // C-like].
4500 //
4501 // FIXME: Also diagnose if we've already computed the linkage. That ideally
4502 // shouldn't happen, but there are constructs that the language rule doesn't
4503 // disallow for which we can't reasonably avoid computing linkage early.
4504 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4505 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4506 : NonCLikeKind();
4507 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4508 if (NonCLike || ChangesLinkage) {
4509 if (NonCLike.Kind == NonCLikeKind::Invalid)
4510 return;
4511
4512 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4513 if (ChangesLinkage) {
4514 // If the linkage changes, we can't accept this as an extension.
4515 if (NonCLike.Kind == NonCLikeKind::None)
4516 DiagID = diag::err_typedef_changes_linkage;
4517 else
4518 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4519 }
4520
4521 SourceLocation FixitLoc =
4522 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4523 llvm::SmallString<40> TextToInsert;
4524 TextToInsert += ' ';
4525 TextToInsert += NewTD->getIdentifier()->getName();
4526
4527 Diag(FixitLoc, DiagID)
4528 << isa<TypeAliasDecl>(NewTD)
4529 << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4530 if (NonCLike.Kind != NonCLikeKind::None) {
4531 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4532 << NonCLike.Kind - 1 << NonCLike.Range;
4533 }
4534 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4535 << NewTD << isa<TypeAliasDecl>(NewTD);
4536
4537 if (ChangesLinkage)
4538 return;
4539 }
4540
4541 // Otherwise, set this as the anon-decl typedef for the tag.
4542 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4543}
4544
4545static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4546 switch (T) {
4547 case DeclSpec::TST_class:
4548 return 0;
4549 case DeclSpec::TST_struct:
4550 return 1;
4551 case DeclSpec::TST_interface:
4552 return 2;
4553 case DeclSpec::TST_union:
4554 return 3;
4555 case DeclSpec::TST_enum:
4556 return 4;
4557 default:
4558 llvm_unreachable("unexpected type specifier")::llvm::llvm_unreachable_internal("unexpected type specifier"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 4558)
;
4559 }
4560}
4561
4562/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4563/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4564/// parameters to cope with template friend declarations.
4565Decl *
4566Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4567 MultiTemplateParamsArg TemplateParams,
4568 bool IsExplicitInstantiation,
4569 RecordDecl *&AnonRecord) {
4570 Decl *TagD = nullptr;
4571 TagDecl *Tag = nullptr;
4572 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4573 DS.getTypeSpecType() == DeclSpec::TST_struct ||
4574 DS.getTypeSpecType() == DeclSpec::TST_interface ||
4575 DS.getTypeSpecType() == DeclSpec::TST_union ||
4576 DS.getTypeSpecType() == DeclSpec::TST_enum) {
4577 TagD = DS.getRepAsDecl();
4578
4579 if (!TagD) // We probably had an error
4580 return nullptr;
4581
4582 // Note that the above type specs guarantee that the
4583 // type rep is a Decl, whereas in many of the others
4584 // it's a Type.
4585 if (isa<TagDecl>(TagD))
4586 Tag = cast<TagDecl>(TagD);
4587 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4588 Tag = CTD->getTemplatedDecl();
4589 }
4590
4591 if (Tag) {
4592 handleTagNumbering(Tag, S);
4593 Tag->setFreeStanding();
4594 if (Tag->isInvalidDecl())
4595 return Tag;
4596 }
4597
4598 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4599 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4600 // or incomplete types shall not be restrict-qualified."
4601 if (TypeQuals & DeclSpec::TQ_restrict)
4602 Diag(DS.getRestrictSpecLoc(),
4603 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4604 << DS.getSourceRange();
4605 }
4606
4607 if (DS.isInlineSpecified())
4608 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4609 << getLangOpts().CPlusPlus17;
4610
4611 if (DS.hasConstexprSpecifier()) {
4612 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4613 // and definitions of functions and variables.
4614 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4615 // the declaration of a function or function template
4616 if (Tag)
4617 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4618 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4619 << static_cast<int>(DS.getConstexprSpecifier());
4620 else
4621 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4622 << static_cast<int>(DS.getConstexprSpecifier());
4623 // Don't emit warnings after this error.
4624 return TagD;
4625 }
4626
4627 DiagnoseFunctionSpecifiers(DS);
4628
4629 if (DS.isFriendSpecified()) {
4630 // If we're dealing with a decl but not a TagDecl, assume that
4631 // whatever routines created it handled the friendship aspect.
4632 if (TagD && !Tag)
4633 return nullptr;
4634 return ActOnFriendTypeDecl(S, DS, TemplateParams);
4635 }
4636
4637 const CXXScopeSpec &SS = DS.getTypeSpecScope();
4638 bool IsExplicitSpecialization =
4639 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4640 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4641 !IsExplicitInstantiation && !IsExplicitSpecialization &&
4642 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4643 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4644 // nested-name-specifier unless it is an explicit instantiation
4645 // or an explicit specialization.
4646 //
4647 // FIXME: We allow class template partial specializations here too, per the
4648 // obvious intent of DR1819.
4649 //
4650 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4651 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4652 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4653 return nullptr;
4654 }
4655
4656 // Track whether this decl-specifier declares anything.
4657 bool DeclaresAnything = true;
4658
4659 // Handle anonymous struct definitions.
4660 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4661 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4662 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4663 if (getLangOpts().CPlusPlus ||
4664 Record->getDeclContext()->isRecord()) {
4665 // If CurContext is a DeclContext that can contain statements,
4666 // RecursiveASTVisitor won't visit the decls that
4667 // BuildAnonymousStructOrUnion() will put into CurContext.
4668 // Also store them here so that they can be part of the
4669 // DeclStmt that gets created in this case.
4670 // FIXME: Also return the IndirectFieldDecls created by
4671 // BuildAnonymousStructOr union, for the same reason?
4672 if (CurContext->isFunctionOrMethod())
4673 AnonRecord = Record;
4674 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4675 Context.getPrintingPolicy());
4676 }
4677
4678 DeclaresAnything = false;
4679 }
4680 }
4681
4682 // C11 6.7.2.1p2:
4683 // A struct-declaration that does not declare an anonymous structure or
4684 // anonymous union shall contain a struct-declarator-list.
4685 //
4686 // This rule also existed in C89 and C99; the grammar for struct-declaration
4687 // did not permit a struct-declaration without a struct-declarator-list.
4688 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4689 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4690 // Check for Microsoft C extension: anonymous struct/union member.
4691 // Handle 2 kinds of anonymous struct/union:
4692 // struct STRUCT;
4693 // union UNION;
4694 // and
4695 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
4696 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
4697 if ((Tag && Tag->getDeclName()) ||
4698 DS.getTypeSpecType() == DeclSpec::TST_typename) {
4699 RecordDecl *Record = nullptr;
4700 if (Tag)
4701 Record = dyn_cast<RecordDecl>(Tag);
4702 else if (const RecordType *RT =
4703 DS.getRepAsType().get()->getAsStructureType())
4704 Record = RT->getDecl();
4705 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4706 Record = UT->getDecl();
4707
4708 if (Record && getLangOpts().MicrosoftExt) {
4709 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4710 << Record->isUnion() << DS.getSourceRange();
4711 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4712 }
4713
4714 DeclaresAnything = false;
4715 }
4716 }
4717
4718 // Skip all the checks below if we have a type error.
4719 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4720 (TagD && TagD->isInvalidDecl()))
4721 return TagD;
4722
4723 if (getLangOpts().CPlusPlus &&
4724 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4725 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4726 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4727 !Enum->getIdentifier() && !Enum->isInvalidDecl())
4728 DeclaresAnything = false;
4729
4730 if (!DS.isMissingDeclaratorOk()) {
4731 // Customize diagnostic for a typedef missing a name.
4732 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4733 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4734 << DS.getSourceRange();
4735 else
4736 DeclaresAnything = false;
4737 }
4738
4739 if (DS.isModulePrivateSpecified() &&
4740 Tag && Tag->getDeclContext()->isFunctionOrMethod())
4741 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4742 << Tag->getTagKind()
4743 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4744
4745 ActOnDocumentableDecl(TagD);
4746
4747 // C 6.7/2:
4748 // A declaration [...] shall declare at least a declarator [...], a tag,
4749 // or the members of an enumeration.
4750 // C++ [dcl.dcl]p3:
4751 // [If there are no declarators], and except for the declaration of an
4752 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
4753 // names into the program, or shall redeclare a name introduced by a
4754 // previous declaration.
4755 if (!DeclaresAnything) {
4756 // In C, we allow this as a (popular) extension / bug. Don't bother
4757 // producing further diagnostics for redundant qualifiers after this.
4758 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
4759 ? diag::err_no_declarators
4760 : diag::ext_no_declarators)
4761 << DS.getSourceRange();
4762 return TagD;
4763 }
4764
4765 // C++ [dcl.stc]p1:
4766 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4767 // init-declarator-list of the declaration shall not be empty.
4768 // C++ [dcl.fct.spec]p1:
4769 // If a cv-qualifier appears in a decl-specifier-seq, the
4770 // init-declarator-list of the declaration shall not be empty.
4771 //
4772 // Spurious qualifiers here appear to be valid in C.
4773 unsigned DiagID = diag::warn_standalone_specifier;
4774 if (getLangOpts().CPlusPlus)
4775 DiagID = diag::ext_standalone_specifier;
4776
4777 // Note that a linkage-specification sets a storage class, but
4778 // 'extern "C" struct foo;' is actually valid and not theoretically
4779 // useless.
4780 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4781 if (SCS == DeclSpec::SCS_mutable)
4782 // Since mutable is not a viable storage class specifier in C, there is
4783 // no reason to treat it as an extension. Instead, diagnose as an error.
4784 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4785 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4786 Diag(DS.getStorageClassSpecLoc(), DiagID)
4787 << DeclSpec::getSpecifierName(SCS);
4788 }
4789
4790 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4791 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4792 << DeclSpec::getSpecifierName(TSCS);
4793 if (DS.getTypeQualifiers()) {
4794 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4795 Diag(DS.getConstSpecLoc(), DiagID) << "const";
4796 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4797 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4798 // Restrict is covered above.
4799 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4800 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4801 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4802 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4803 }
4804
4805 // Warn about ignored type attributes, for example:
4806 // __attribute__((aligned)) struct A;
4807 // Attributes should be placed after tag to apply to type declaration.
4808 if (!DS.getAttributes().empty()) {
4809 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4810 if (TypeSpecType == DeclSpec::TST_class ||
4811 TypeSpecType == DeclSpec::TST_struct ||
4812 TypeSpecType == DeclSpec::TST_interface ||
4813 TypeSpecType == DeclSpec::TST_union ||
4814 TypeSpecType == DeclSpec::TST_enum) {
4815 for (const ParsedAttr &AL : DS.getAttributes())
4816 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4817 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
4818 }
4819 }
4820
4821 return TagD;
4822}
4823
4824/// We are trying to inject an anonymous member into the given scope;
4825/// check if there's an existing declaration that can't be overloaded.
4826///
4827/// \return true if this is a forbidden redeclaration
4828static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4829 Scope *S,
4830 DeclContext *Owner,
4831 DeclarationName Name,
4832 SourceLocation NameLoc,
4833 bool IsUnion) {
4834 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4835 Sema::ForVisibleRedeclaration);
4836 if (!SemaRef.LookupName(R, S)) return false;
4837
4838 // Pick a representative declaration.
4839 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4840 assert(PrevDecl && "Expected a non-null Decl")((PrevDecl && "Expected a non-null Decl") ? static_cast
<void> (0) : __assert_fail ("PrevDecl && \"Expected a non-null Decl\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 4840, __PRETTY_FUNCTION__))
;
4841
4842 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4843 return false;
4844
4845 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4846 << IsUnion << Name;
4847 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4848
4849 return true;
4850}
4851
4852/// InjectAnonymousStructOrUnionMembers - Inject the members of the
4853/// anonymous struct or union AnonRecord into the owning context Owner
4854/// and scope S. This routine will be invoked just after we realize
4855/// that an unnamed union or struct is actually an anonymous union or
4856/// struct, e.g.,
4857///
4858/// @code
4859/// union {
4860/// int i;
4861/// float f;
4862/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4863/// // f into the surrounding scope.x
4864/// @endcode
4865///
4866/// This routine is recursive, injecting the names of nested anonymous
4867/// structs/unions into the owning context and scope as well.
4868static bool
4869InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4870 RecordDecl *AnonRecord, AccessSpecifier AS,
4871 SmallVectorImpl<NamedDecl *> &Chaining) {
4872 bool Invalid = false;
4873
4874 // Look every FieldDecl and IndirectFieldDecl with a name.
4875 for (auto *D : AnonRecord->decls()) {
4876 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4877 cast<NamedDecl>(D)->getDeclName()) {
4878 ValueDecl *VD = cast<ValueDecl>(D);
4879 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4880 VD->getLocation(),
4881 AnonRecord->isUnion())) {
4882 // C++ [class.union]p2:
4883 // The names of the members of an anonymous union shall be
4884 // distinct from the names of any other entity in the
4885 // scope in which the anonymous union is declared.
4886 Invalid = true;
4887 } else {
4888 // C++ [class.union]p2:
4889 // For the purpose of name lookup, after the anonymous union
4890 // definition, the members of the anonymous union are
4891 // considered to have been defined in the scope in which the
4892 // anonymous union is declared.
4893 unsigned OldChainingSize = Chaining.size();
4894 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4895 Chaining.append(IF->chain_begin(), IF->chain_end());
4896 else
4897 Chaining.push_back(VD);
4898
4899 assert(Chaining.size() >= 2)((Chaining.size() >= 2) ? static_cast<void> (0) : __assert_fail
("Chaining.size() >= 2", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 4899, __PRETTY_FUNCTION__))
;
4900 NamedDecl **NamedChain =
4901 new (SemaRef.Context)NamedDecl*[Chaining.size()];
4902 for (unsigned i = 0; i < Chaining.size(); i++)
4903 NamedChain[i] = Chaining[i];
4904
4905 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4906 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4907 VD->getType(), {NamedChain, Chaining.size()});
4908
4909 for (const auto *Attr : VD->attrs())
4910 IndirectField->addAttr(Attr->clone(SemaRef.Context));
4911
4912 IndirectField->setAccess(AS);
4913 IndirectField->setImplicit();
4914 SemaRef.PushOnScopeChains(IndirectField, S);
4915
4916 // That includes picking up the appropriate access specifier.
4917 if (AS != AS_none) IndirectField->setAccess(AS);
4918
4919 Chaining.resize(OldChainingSize);
4920 }
4921 }
4922 }
4923
4924 return Invalid;
4925}
4926
4927/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4928/// a VarDecl::StorageClass. Any error reporting is up to the caller:
4929/// illegal input values are mapped to SC_None.
4930static StorageClass
4931StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4932 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4933 assert(StorageClassSpec != DeclSpec::SCS_typedef &&((StorageClassSpec != DeclSpec::SCS_typedef && "Parser allowed 'typedef' as storage class VarDecl."
) ? static_cast<void> (0) : __assert_fail ("StorageClassSpec != DeclSpec::SCS_typedef && \"Parser allowed 'typedef' as storage class VarDecl.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 4934, __PRETTY_FUNCTION__))
4934 "Parser allowed 'typedef' as storage class VarDecl.")((StorageClassSpec != DeclSpec::SCS_typedef && "Parser allowed 'typedef' as storage class VarDecl."
) ? static_cast<void> (0) : __assert_fail ("StorageClassSpec != DeclSpec::SCS_typedef && \"Parser allowed 'typedef' as storage class VarDecl.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 4934, __PRETTY_FUNCTION__))
;
4935 switch (StorageClassSpec) {
4936 case DeclSpec::SCS_unspecified: return SC_None;
4937 case DeclSpec::SCS_extern:
4938 if (DS.isExternInLinkageSpec())
4939 return SC_None;
4940 return SC_Extern;
4941 case DeclSpec::SCS_static: return SC_Static;
4942 case DeclSpec::SCS_auto: return SC_Auto;
4943 case DeclSpec::SCS_register: return SC_Register;
4944 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4945 // Illegal SCSs map to None: error reporting is up to the caller.
4946 case DeclSpec::SCS_mutable: // Fall through.
4947 case DeclSpec::SCS_typedef: return SC_None;
4948 }
4949 llvm_unreachable("unknown storage class specifier")::llvm::llvm_unreachable_internal("unknown storage class specifier"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 4949)
;
4950}
4951
4952static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4953 assert(Record->hasInClassInitializer())((Record->hasInClassInitializer()) ? static_cast<void>
(0) : __assert_fail ("Record->hasInClassInitializer()", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 4953, __PRETTY_FUNCTION__))
;
4954
4955 for (const auto *I : Record->decls()) {
4956 const auto *FD = dyn_cast<FieldDecl>(I);
4957 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4958 FD = IFD->getAnonField();
4959 if (FD && FD->hasInClassInitializer())
4960 return FD->getLocation();
4961 }
4962
4963 llvm_unreachable("couldn't find in-class initializer")::llvm::llvm_unreachable_internal("couldn't find in-class initializer"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 4963)
;
4964}
4965
4966static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4967 SourceLocation DefaultInitLoc) {
4968 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4969 return;
4970
4971 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4972 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4973}
4974
4975static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4976 CXXRecordDecl *AnonUnion) {
4977 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4978 return;
4979
4980 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4981}
4982
4983/// BuildAnonymousStructOrUnion - Handle the declaration of an
4984/// anonymous structure or union. Anonymous unions are a C++ feature
4985/// (C++ [class.union]) and a C11 feature; anonymous structures
4986/// are a C11 feature and GNU C++ extension.
4987Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4988 AccessSpecifier AS,
4989 RecordDecl *Record,
4990 const PrintingPolicy &Policy) {
4991 DeclContext *Owner = Record->getDeclContext();
4992
4993 // Diagnose whether this anonymous struct/union is an extension.
4994 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4995 Diag(Record->getLocation(), diag::ext_anonymous_union);
4996 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4997 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4998 else if (!Record->isUnion() && !getLangOpts().C11)
4999 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5000
5001 // C and C++ require different kinds of checks for anonymous
5002 // structs/unions.
5003 bool Invalid = false;
5004 if (getLangOpts().CPlusPlus) {
5005 const char *PrevSpec = nullptr;
5006 if (Record->isUnion()) {
5007 // C++ [class.union]p6:
5008 // C++17 [class.union.anon]p2:
5009 // Anonymous unions declared in a named namespace or in the
5010 // global namespace shall be declared static.
5011 unsigned DiagID;
5012 DeclContext *OwnerScope = Owner->getRedeclContext();
5013 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5014 (OwnerScope->isTranslationUnit() ||
5015 (OwnerScope->isNamespace() &&
5016 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5017 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5018 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5019
5020 // Recover by adding 'static'.
5021 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5022 PrevSpec, DiagID, Policy);
5023 }
5024 // C++ [class.union]p6:
5025 // A storage class is not allowed in a declaration of an
5026 // anonymous union in a class scope.
5027 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5028 isa<RecordDecl>(Owner)) {
5029 Diag(DS.getStorageClassSpecLoc(),
5030 diag::err_anonymous_union_with_storage_spec)
5031 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5032
5033 // Recover by removing the storage specifier.
5034 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5035 SourceLocation(),
5036 PrevSpec, DiagID, Context.getPrintingPolicy());
5037 }
5038 }
5039
5040 // Ignore const/volatile/restrict qualifiers.
5041 if (DS.getTypeQualifiers()) {
5042 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5043 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5044 << Record->isUnion() << "const"
5045 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5046 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5047 Diag(DS.getVolatileSpecLoc(),
5048 diag::ext_anonymous_struct_union_qualified)
5049 << Record->isUnion() << "volatile"
5050 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5051 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5052 Diag(DS.getRestrictSpecLoc(),
5053 diag::ext_anonymous_struct_union_qualified)
5054 << Record->isUnion() << "restrict"
5055 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5056 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5057 Diag(DS.getAtomicSpecLoc(),
5058 diag::ext_anonymous_struct_union_qualified)
5059 << Record->isUnion() << "_Atomic"
5060 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5061 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5062 Diag(DS.getUnalignedSpecLoc(),
5063 diag::ext_anonymous_struct_union_qualified)
5064 << Record->isUnion() << "__unaligned"
5065 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5066
5067 DS.ClearTypeQualifiers();
5068 }
5069
5070 // C++ [class.union]p2:
5071 // The member-specification of an anonymous union shall only
5072 // define non-static data members. [Note: nested types and
5073 // functions cannot be declared within an anonymous union. ]
5074 for (auto *Mem : Record->decls()) {
5075 // Ignore invalid declarations; we already diagnosed them.
5076 if (Mem->isInvalidDecl())
5077 continue;
5078
5079 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5080 // C++ [class.union]p3:
5081 // An anonymous union shall not have private or protected
5082 // members (clause 11).
5083 assert(FD->getAccess() != AS_none)((FD->getAccess() != AS_none) ? static_cast<void> (0
) : __assert_fail ("FD->getAccess() != AS_none", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 5083, __PRETTY_FUNCTION__))
;
5084 if (FD->getAccess() != AS_public) {
5085 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5086 << Record->isUnion() << (FD->getAccess() == AS_protected);
5087 Invalid = true;
5088 }
5089
5090 // C++ [class.union]p1
5091 // An object of a class with a non-trivial constructor, a non-trivial
5092 // copy constructor, a non-trivial destructor, or a non-trivial copy
5093 // assignment operator cannot be a member of a union, nor can an
5094 // array of such objects.
5095 if (CheckNontrivialField(FD))
5096 Invalid = true;
5097 } else if (Mem->isImplicit()) {
5098 // Any implicit members are fine.
5099 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5100 // This is a type that showed up in an
5101 // elaborated-type-specifier inside the anonymous struct or
5102 // union, but which actually declares a type outside of the
5103 // anonymous struct or union. It's okay.
5104 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5105 if (!MemRecord->isAnonymousStructOrUnion() &&
5106 MemRecord->getDeclName()) {
5107 // Visual C++ allows type definition in anonymous struct or union.
5108 if (getLangOpts().MicrosoftExt)
5109 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5110 << Record->isUnion();
5111 else {
5112 // This is a nested type declaration.
5113 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5114 << Record->isUnion();
5115 Invalid = true;
5116 }
5117 } else {
5118 // This is an anonymous type definition within another anonymous type.
5119 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5120 // not part of standard C++.
5121 Diag(MemRecord->getLocation(),
5122 diag::ext_anonymous_record_with_anonymous_type)
5123 << Record->isUnion();
5124 }
5125 } else if (isa<AccessSpecDecl>(Mem)) {
5126 // Any access specifier is fine.
5127 } else if (isa<StaticAssertDecl>(Mem)) {
5128 // In C++1z, static_assert declarations are also fine.
5129 } else {
5130 // We have something that isn't a non-static data
5131 // member. Complain about it.
5132 unsigned DK = diag::err_anonymous_record_bad_member;
5133 if (isa<TypeDecl>(Mem))
5134 DK = diag::err_anonymous_record_with_type;
5135 else if (isa<FunctionDecl>(Mem))
5136 DK = diag::err_anonymous_record_with_function;
5137 else if (isa<VarDecl>(Mem))
5138 DK = diag::err_anonymous_record_with_static;
5139
5140 // Visual C++ allows type definition in anonymous struct or union.
5141 if (getLangOpts().MicrosoftExt &&
5142 DK == diag::err_anonymous_record_with_type)
5143 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5144 << Record->isUnion();
5145 else {
5146 Diag(Mem->getLocation(), DK) << Record->isUnion();
5147 Invalid = true;
5148 }
5149 }
5150 }
5151
5152 // C++11 [class.union]p8 (DR1460):
5153 // At most one variant member of a union may have a
5154 // brace-or-equal-initializer.
5155 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5156 Owner->isRecord())
5157 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5158 cast<CXXRecordDecl>(Record));
5159 }
5160
5161 if (!Record->isUnion() && !Owner->isRecord()) {
5162 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5163 << getLangOpts().CPlusPlus;
5164 Invalid = true;
5165 }
5166
5167 // C++ [dcl.dcl]p3:
5168 // [If there are no declarators], and except for the declaration of an
5169 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5170 // names into the program
5171 // C++ [class.mem]p2:
5172 // each such member-declaration shall either declare at least one member
5173 // name of the class or declare at least one unnamed bit-field
5174 //
5175 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5176 if (getLangOpts().CPlusPlus && Record->field_empty())
5177 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5178
5179 // Mock up a declarator.
5180 Declarator Dc(DS, DeclaratorContext::Member);
5181 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5182 assert(TInfo && "couldn't build declarator info for anonymous struct/union")((TInfo && "couldn't build declarator info for anonymous struct/union"
) ? static_cast<void> (0) : __assert_fail ("TInfo && \"couldn't build declarator info for anonymous struct/union\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 5182, __PRETTY_FUNCTION__))
;
5183
5184 // Create a declaration for this anonymous struct/union.
5185 NamedDecl *Anon = nullptr;
5186 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5187 Anon = FieldDecl::Create(
5188 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5189 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5190 /*BitWidth=*/nullptr, /*Mutable=*/false,
5191 /*InitStyle=*/ICIS_NoInit);
5192 Anon->setAccess(AS);
5193 ProcessDeclAttributes(S, Anon, Dc);
5194
5195 if (getLangOpts().CPlusPlus)
5196 FieldCollector->Add(cast<FieldDecl>(Anon));
5197 } else {
5198 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5199 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5200 if (SCSpec == DeclSpec::SCS_mutable) {
5201 // mutable can only appear on non-static class members, so it's always
5202 // an error here
5203 Diag(Record->getLocation(), diag::err_mutable_nonmember);
5204 Invalid = true;
5205 SC = SC_None;
5206 }
5207
5208 assert(DS.getAttributes().empty() && "No attribute expected")((DS.getAttributes().empty() && "No attribute expected"
) ? static_cast<void> (0) : __assert_fail ("DS.getAttributes().empty() && \"No attribute expected\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 5208, __PRETTY_FUNCTION__))
;
5209 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5210 Record->getLocation(), /*IdentifierInfo=*/nullptr,
5211 Context.getTypeDeclType(Record), TInfo, SC);
5212
5213 // Default-initialize the implicit variable. This initialization will be
5214 // trivial in almost all cases, except if a union member has an in-class
5215 // initializer:
5216 // union { int n = 0; };
5217 if (!Invalid)
5218 ActOnUninitializedDecl(Anon);
5219 }
5220 Anon->setImplicit();
5221
5222 // Mark this as an anonymous struct/union type.
5223 Record->setAnonymousStructOrUnion(true);
5224
5225 // Add the anonymous struct/union object to the current
5226 // context. We'll be referencing this object when we refer to one of
5227 // its members.
5228 Owner->addDecl(Anon);
5229
5230 // Inject the members of the anonymous struct/union into the owning
5231 // context and into the identifier resolver chain for name lookup
5232 // purposes.
5233 SmallVector<NamedDecl*, 2> Chain;
5234 Chain.push_back(Anon);
5235
5236 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5237 Invalid = true;
5238
5239 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5240 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5241 MangleNumberingContext *MCtx;
5242 Decl *ManglingContextDecl;
5243 std::tie(MCtx, ManglingContextDecl) =
5244 getCurrentMangleNumberContext(NewVD->getDeclContext());
5245 if (MCtx) {
5246 Context.setManglingNumber(
5247 NewVD, MCtx->getManglingNumber(
5248 NewVD, getMSManglingNumber(getLangOpts(), S)));
5249 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5250 }
5251 }
5252 }
5253
5254 if (Invalid)
5255 Anon->setInvalidDecl();
5256
5257 return Anon;
5258}
5259
5260/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5261/// Microsoft C anonymous structure.
5262/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5263/// Example:
5264///
5265/// struct A { int a; };
5266/// struct B { struct A; int b; };
5267///
5268/// void foo() {
5269/// B var;
5270/// var.a = 3;
5271/// }
5272///
5273Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5274 RecordDecl *Record) {
5275 assert(Record && "expected a record!")((Record && "expected a record!") ? static_cast<void
> (0) : __assert_fail ("Record && \"expected a record!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 5275, __PRETTY_FUNCTION__))
;
5276
5277 // Mock up a declarator.
5278 Declarator Dc(DS, DeclaratorContext::TypeName);
5279 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5280 assert(TInfo && "couldn't build declarator info for anonymous struct")((TInfo && "couldn't build declarator info for anonymous struct"
) ? static_cast<void> (0) : __assert_fail ("TInfo && \"couldn't build declarator info for anonymous struct\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 5280, __PRETTY_FUNCTION__))
;
5281
5282 auto *ParentDecl = cast<RecordDecl>(CurContext);
5283 QualType RecTy = Context.getTypeDeclType(Record);
5284
5285 // Create a declaration for this anonymous struct.
5286 NamedDecl *Anon =
5287 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5288 /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5289 /*BitWidth=*/nullptr, /*Mutable=*/false,
5290 /*InitStyle=*/ICIS_NoInit);
5291 Anon->setImplicit();
5292
5293 // Add the anonymous struct object to the current context.
5294 CurContext->addDecl(Anon);
5295
5296 // Inject the members of the anonymous struct into the current
5297 // context and into the identifier resolver chain for name lookup
5298 // purposes.
5299 SmallVector<NamedDecl*, 2> Chain;
5300 Chain.push_back(Anon);
5301
5302 RecordDecl *RecordDef = Record->getDefinition();
5303 if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5304 diag::err_field_incomplete_or_sizeless) ||
5305 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5306 AS_none, Chain)) {
5307 Anon->setInvalidDecl();
5308 ParentDecl->setInvalidDecl();
5309 }
5310
5311 return Anon;
5312}
5313
5314/// GetNameForDeclarator - Determine the full declaration name for the
5315/// given Declarator.
5316DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5317 return GetNameFromUnqualifiedId(D.getName());
5318}
5319
5320/// Retrieves the declaration name from a parsed unqualified-id.
5321DeclarationNameInfo
5322Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5323 DeclarationNameInfo NameInfo;
5324 NameInfo.setLoc(Name.StartLocation);
5325
5326 switch (Name.getKind()) {
5327
5328 case UnqualifiedIdKind::IK_ImplicitSelfParam:
5329 case UnqualifiedIdKind::IK_Identifier:
5330 NameInfo.setName(Name.Identifier);
5331 return NameInfo;
5332
5333 case UnqualifiedIdKind::IK_DeductionGuideName: {
5334 // C++ [temp.deduct.guide]p3:
5335 // The simple-template-id shall name a class template specialization.
5336 // The template-name shall be the same identifier as the template-name
5337 // of the simple-template-id.
5338 // These together intend to imply that the template-name shall name a
5339 // class template.
5340 // FIXME: template<typename T> struct X {};
5341 // template<typename T> using Y = X<T>;
5342 // Y(int) -> Y<int>;
5343 // satisfies these rules but does not name a class template.
5344 TemplateName TN = Name.TemplateName.get().get();
5345 auto *Template = TN.getAsTemplateDecl();
5346 if (!Template || !isa<ClassTemplateDecl>(Template)) {
5347 Diag(Name.StartLocation,
5348 diag::err_deduction_guide_name_not_class_template)
5349 << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5350 if (Template)
5351 Diag(Template->getLocation(), diag::note_template_decl_here);
5352 return DeclarationNameInfo();
5353 }
5354
5355 NameInfo.setName(
5356 Context.DeclarationNames.getCXXDeductionGuideName(Template));
5357 return NameInfo;
5358 }
5359
5360 case UnqualifiedIdKind::IK_OperatorFunctionId:
5361 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5362 Name.OperatorFunctionId.Operator));
5363 NameInfo.setCXXOperatorNameRange(SourceRange(
5364 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5365 return NameInfo;
5366
5367 case UnqualifiedIdKind::IK_LiteralOperatorId:
5368 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5369 Name.Identifier));
5370 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5371 return NameInfo;
5372
5373 case UnqualifiedIdKind::IK_ConversionFunctionId: {
5374 TypeSourceInfo *TInfo;
5375 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5376 if (Ty.isNull())
5377 return DeclarationNameInfo();
5378 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5379 Context.getCanonicalType(Ty)));
5380 NameInfo.setNamedTypeInfo(TInfo);
5381 return NameInfo;
5382 }
5383
5384 case UnqualifiedIdKind::IK_ConstructorName: {
5385 TypeSourceInfo *TInfo;
5386 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5387 if (Ty.isNull())
5388 return DeclarationNameInfo();
5389 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5390 Context.getCanonicalType(Ty)));
5391 NameInfo.setNamedTypeInfo(TInfo);
5392 return NameInfo;
5393 }
5394
5395 case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5396 // In well-formed code, we can only have a constructor
5397 // template-id that refers to the current context, so go there
5398 // to find the actual type being constructed.
5399 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5400 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5401 return DeclarationNameInfo();
5402
5403 // Determine the type of the class being constructed.
5404 QualType CurClassType = Context.getTypeDeclType(CurClass);
5405
5406 // FIXME: Check two things: that the template-id names the same type as
5407 // CurClassType, and that the template-id does not occur when the name
5408 // was qualified.
5409
5410 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5411 Context.getCanonicalType(CurClassType)));
5412 // FIXME: should we retrieve TypeSourceInfo?
5413 NameInfo.setNamedTypeInfo(nullptr);
5414 return NameInfo;
5415 }
5416
5417 case UnqualifiedIdKind::IK_DestructorName: {
5418 TypeSourceInfo *TInfo;
5419 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5420 if (Ty.isNull())
5421 return DeclarationNameInfo();
5422 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5423 Context.getCanonicalType(Ty)));
5424 NameInfo.setNamedTypeInfo(TInfo);
5425 return NameInfo;
5426 }
5427
5428 case UnqualifiedIdKind::IK_TemplateId: {
5429 TemplateName TName = Name.TemplateId->Template.get();
5430 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5431 return Context.getNameForTemplate(TName, TNameLoc);
5432 }
5433
5434 } // switch (Name.getKind())
5435
5436 llvm_unreachable("Unknown name kind")::llvm::llvm_unreachable_internal("Unknown name kind", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 5436)
;
5437}
5438
5439static QualType getCoreType(QualType Ty) {
5440 do {
5441 if (Ty->isPointerType() || Ty->isReferenceType())
5442 Ty = Ty->getPointeeType();
5443 else if (Ty->isArrayType())
5444 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5445 else
5446 return Ty.withoutLocalFastQualifiers();
5447 } while (true);
5448}
5449
5450/// hasSimilarParameters - Determine whether the C++ functions Declaration
5451/// and Definition have "nearly" matching parameters. This heuristic is
5452/// used to improve diagnostics in the case where an out-of-line function
5453/// definition doesn't match any declaration within the class or namespace.
5454/// Also sets Params to the list of indices to the parameters that differ
5455/// between the declaration and the definition. If hasSimilarParameters
5456/// returns true and Params is empty, then all of the parameters match.
5457static bool hasSimilarParameters(ASTContext &Context,
5458 FunctionDecl *Declaration,
5459 FunctionDecl *Definition,
5460 SmallVectorImpl<unsigned> &Params) {
5461 Params.clear();
5462 if (Declaration->param_size() != Definition->param_size())
5463 return false;
5464 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5465 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5466 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5467
5468 // The parameter types are identical
5469 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5470 continue;
5471
5472 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5473 QualType DefParamBaseTy = getCoreType(DefParamTy);
5474 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5475 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5476
5477 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5478 (DeclTyName && DeclTyName == DefTyName))
5479 Params.push_back(Idx);
5480 else // The two parameters aren't even close
5481 return false;
5482 }
5483
5484 return true;
5485}
5486
5487/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5488/// declarator needs to be rebuilt in the current instantiation.
5489/// Any bits of declarator which appear before the name are valid for
5490/// consideration here. That's specifically the type in the decl spec
5491/// and the base type in any member-pointer chunks.
5492static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5493 DeclarationName Name) {
5494 // The types we specifically need to rebuild are:
5495 // - typenames, typeofs, and decltypes
5496 // - types which will become injected class names
5497 // Of course, we also need to rebuild any type referencing such a
5498 // type. It's safest to just say "dependent", but we call out a
5499 // few cases here.
5500
5501 DeclSpec &DS = D.getMutableDeclSpec();
5502 switch (DS.getTypeSpecType()) {
5503 case DeclSpec::TST_typename:
5504 case DeclSpec::TST_typeofType:
5505 case DeclSpec::TST_underlyingType:
5506 case DeclSpec::TST_atomic: {
5507 // Grab the type from the parser.
5508 TypeSourceInfo *TSI = nullptr;
5509 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5510 if (T.isNull() || !T->isInstantiationDependentType()) break;
5511
5512 // Make sure there's a type source info. This isn't really much
5513 // of a waste; most dependent types should have type source info
5514 // attached already.
5515 if (!TSI)
5516 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5517
5518 // Rebuild the type in the current instantiation.
5519 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5520 if (!TSI) return true;
5521
5522 // Store the new type back in the decl spec.
5523 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5524 DS.UpdateTypeRep(LocType);
5525 break;
5526 }
5527
5528 case DeclSpec::TST_decltype:
5529 case DeclSpec::TST_typeofExpr: {
5530 Expr *E = DS.getRepAsExpr();
5531 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5532 if (Result.isInvalid()) return true;
5533 DS.UpdateExprRep(Result.get());
5534 break;
5535 }
5536
5537 default:
5538 // Nothing to do for these decl specs.
5539 break;
5540 }
5541
5542 // It doesn't matter what order we do this in.
5543 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5544 DeclaratorChunk &Chunk = D.getTypeObject(I);
5545
5546 // The only type information in the declarator which can come
5547 // before the declaration name is the base type of a member
5548 // pointer.
5549 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5550 continue;
5551
5552 // Rebuild the scope specifier in-place.
5553 CXXScopeSpec &SS = Chunk.Mem.Scope();
5554 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5555 return true;
5556 }
5557
5558 return false;
5559}
5560
5561Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5562 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
5563 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5564
5565 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5566 Dcl && Dcl->getDeclContext()->isFileContext())
5567 Dcl->setTopLevelDeclInObjCContainer();
5568
5569 if (getLangOpts().OpenCL)
5570 setCurrentOpenCLExtensionForDecl(Dcl);
5571
5572 return Dcl;
5573}
5574
5575/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5576/// If T is the name of a class, then each of the following shall have a
5577/// name different from T:
5578/// - every static data member of class T;
5579/// - every member function of class T
5580/// - every member of class T that is itself a type;
5581/// \returns true if the declaration name violates these rules.
5582bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5583 DeclarationNameInfo NameInfo) {
5584 DeclarationName Name = NameInfo.getName();
5585
5586 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5587 while (Record && Record->isAnonymousStructOrUnion())
5588 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5589 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5590 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5591 return true;
5592 }
5593
5594 return false;
5595}
5596
5597/// Diagnose a declaration whose declarator-id has the given
5598/// nested-name-specifier.
5599///
5600/// \param SS The nested-name-specifier of the declarator-id.
5601///
5602/// \param DC The declaration context to which the nested-name-specifier
5603/// resolves.
5604///
5605/// \param Name The name of the entity being declared.
5606///
5607/// \param Loc The location of the name of the entity being declared.
5608///
5609/// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5610/// we're declaring an explicit / partial specialization / instantiation.
5611///
5612/// \returns true if we cannot safely recover from this error, false otherwise.
5613bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5614 DeclarationName Name,
5615 SourceLocation Loc, bool IsTemplateId) {
5616 DeclContext *Cur = CurContext;
5617 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5618 Cur = Cur->getParent();
5619
5620 // If the user provided a superfluous scope specifier that refers back to the
5621 // class in which the entity is already declared, diagnose and ignore it.
5622 //
5623 // class X {
5624 // void X::f();
5625 // };
5626 //
5627 // Note, it was once ill-formed to give redundant qualification in all
5628 // contexts, but that rule was removed by DR482.
5629 if (Cur->Equals(DC)) {
5630 if (Cur->isRecord()) {
5631 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5632 : diag::err_member_extra_qualification)
5633 << Name << FixItHint::CreateRemoval(SS.getRange());
5634 SS.clear();
5635 } else {
5636 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5637 }
5638 return false;
5639 }
5640
5641 // Check whether the qualifying scope encloses the scope of the original
5642 // declaration. For a template-id, we perform the checks in
5643 // CheckTemplateSpecializationScope.
5644 if (!Cur->Encloses(DC) && !IsTemplateId) {
5645 if (Cur->isRecord())
5646 Diag(Loc, diag::err_member_qualification)
5647 << Name << SS.getRange();
5648 else if (isa<TranslationUnitDecl>(DC))
5649 Diag(Loc, diag::err_invalid_declarator_global_scope)
5650 << Name << SS.getRange();
5651 else if (isa<FunctionDecl>(Cur))
5652 Diag(Loc, diag::err_invalid_declarator_in_function)
5653 << Name << SS.getRange();
5654 else if (isa<BlockDecl>(Cur))
5655 Diag(Loc, diag::err_invalid_declarator_in_block)
5656 << Name << SS.getRange();
5657 else
5658 Diag(Loc, diag::err_invalid_declarator_scope)
5659 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5660
5661 return true;
5662 }
5663
5664 if (Cur->isRecord()) {
5665 // Cannot qualify members within a class.
5666 Diag(Loc, diag::err_member_qualification)
5667 << Name << SS.getRange();
5668 SS.clear();
5669
5670 // C++ constructors and destructors with incorrect scopes can break
5671 // our AST invariants by having the wrong underlying types. If
5672 // that's the case, then drop this declaration entirely.
5673 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5674 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5675 !Context.hasSameType(Name.getCXXNameType(),
5676 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5677 return true;
5678
5679 return false;
5680 }
5681
5682 // C++11 [dcl.meaning]p1:
5683 // [...] "The nested-name-specifier of the qualified declarator-id shall
5684 // not begin with a decltype-specifer"
5685 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5686 while (SpecLoc.getPrefix())
5687 SpecLoc = SpecLoc.getPrefix();
5688 if (dyn_cast_or_null<DecltypeType>(
5689 SpecLoc.getNestedNameSpecifier()->getAsType()))
5690 Diag(Loc, diag::err_decltype_in_declarator)
5691 << SpecLoc.getTypeLoc().getSourceRange();
5692
5693 return false;
5694}
5695
5696NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5697 MultiTemplateParamsArg TemplateParamLists) {
5698 // TODO: consider using NameInfo for diagnostic.
5699 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5700 DeclarationName Name = NameInfo.getName();
5701
5702 // All of these full declarators require an identifier. If it doesn't have
5703 // one, the ParsedFreeStandingDeclSpec action should be used.
5704 if (D.isDecompositionDeclarator()) {
5705 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5706 } else if (!Name) {
5707 if (!D.isInvalidType()) // Reject this if we think it is valid.
5708 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5709 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5710 return nullptr;
5711 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5712 return nullptr;
5713
5714 // The scope passed in may not be a decl scope. Zip up the scope tree until
5715 // we find one that is.
5716 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5717 (S->getFlags() & Scope::TemplateParamScope) != 0)
5718 S = S->getParent();
5719
5720 DeclContext *DC = CurContext;
5721 if (D.getCXXScopeSpec().isInvalid())
5722 D.setInvalidType();
5723 else if (D.getCXXScopeSpec().isSet()) {
5724 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5725 UPPC_DeclarationQualifier))
5726 return nullptr;
5727
5728 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5729 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5730 if (!DC || isa<EnumDecl>(DC)) {
5731 // If we could not compute the declaration context, it's because the
5732 // declaration context is dependent but does not refer to a class,
5733 // class template, or class template partial specialization. Complain
5734 // and return early, to avoid the coming semantic disaster.
5735 Diag(D.getIdentifierLoc(),
5736 diag::err_template_qualified_declarator_no_match)
5737 << D.getCXXScopeSpec().getScopeRep()
5738 << D.getCXXScopeSpec().getRange();
5739 return nullptr;
5740 }
5741 bool IsDependentContext = DC->isDependentContext();
5742
5743 if (!IsDependentContext &&
5744 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5745 return nullptr;
5746
5747 // If a class is incomplete, do not parse entities inside it.
5748 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5749 Diag(D.getIdentifierLoc(),
5750 diag::err_member_def_undefined_record)
5751 << Name << DC << D.getCXXScopeSpec().getRange();
5752 return nullptr;
5753 }
5754 if (!D.getDeclSpec().isFriendSpecified()) {
5755 if (diagnoseQualifiedDeclaration(
5756 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5757 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5758 if (DC->isRecord())
5759 return nullptr;
5760
5761 D.setInvalidType();
5762 }
5763 }
5764
5765 // Check whether we need to rebuild the type of the given
5766 // declaration in the current instantiation.
5767 if (EnteringContext && IsDependentContext &&
5768 TemplateParamLists.size() != 0) {
5769 ContextRAII SavedContext(*this, DC);
5770 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5771 D.setInvalidType();
5772 }
5773 }
5774
5775 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5776 QualType R = TInfo->getType();
5777
5778 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5779 UPPC_DeclarationType))
5780 D.setInvalidType();
5781
5782 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5783 forRedeclarationInCurContext());
5784
5785 // See if this is a redefinition of a variable in the same scope.
5786 if (!D.getCXXScopeSpec().isSet()) {
5787 bool IsLinkageLookup = false;
5788 bool CreateBuiltins = false;
5789
5790 // If the declaration we're planning to build will be a function
5791 // or object with linkage, then look for another declaration with
5792 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5793 //
5794 // If the declaration we're planning to build will be declared with
5795 // external linkage in the translation unit, create any builtin with
5796 // the same name.
5797 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5798 /* Do nothing*/;
5799 else if (CurContext->isFunctionOrMethod() &&
5800 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5801 R->isFunctionType())) {
5802 IsLinkageLookup = true;
5803 CreateBuiltins =
5804 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5805 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5806 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5807 CreateBuiltins = true;
5808
5809 if (IsLinkageLookup) {
5810 Previous.clear(LookupRedeclarationWithLinkage);
5811 Previous.setRedeclarationKind(ForExternalRedeclaration);
5812 }
5813
5814 LookupName(Previous, S, CreateBuiltins);
5815 } else { // Something like "int foo::x;"
5816 LookupQualifiedName(Previous, DC);
5817
5818 // C++ [dcl.meaning]p1:
5819 // When the declarator-id is qualified, the declaration shall refer to a
5820 // previously declared member of the class or namespace to which the
5821 // qualifier refers (or, in the case of a namespace, of an element of the
5822 // inline namespace set of that namespace (7.3.1)) or to a specialization
5823 // thereof; [...]
5824 //
5825 // Note that we already checked the context above, and that we do not have
5826 // enough information to make sure that Previous contains the declaration
5827 // we want to match. For example, given:
5828 //
5829 // class X {
5830 // void f();
5831 // void f(float);
5832 // };
5833 //
5834 // void X::f(int) { } // ill-formed
5835 //
5836 // In this case, Previous will point to the overload set
5837 // containing the two f's declared in X, but neither of them
5838 // matches.
5839
5840 // C++ [dcl.meaning]p1:
5841 // [...] the member shall not merely have been introduced by a
5842 // using-declaration in the scope of the class or namespace nominated by
5843 // the nested-name-specifier of the declarator-id.
5844 RemoveUsingDecls(Previous);
5845 }
5846
5847 if (Previous.isSingleResult() &&
5848 Previous.getFoundDecl()->isTemplateParameter()) {
5849 // Maybe we will complain about the shadowed template parameter.
5850 if (!D.isInvalidType())
5851 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5852 Previous.getFoundDecl());
5853
5854 // Just pretend that we didn't see the previous declaration.
5855 Previous.clear();
5856 }
5857
5858 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5859 // Forget that the previous declaration is the injected-class-name.
5860 Previous.clear();
5861
5862 // In C++, the previous declaration we find might be a tag type
5863 // (class or enum). In this case, the new declaration will hide the
5864 // tag type. Note that this applies to functions, function templates, and
5865 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5866 if (Previous.isSingleTagDecl() &&
5867 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5868 (TemplateParamLists.size() == 0 || R->isFunctionType()))
5869 Previous.clear();
5870
5871 // Check that there are no default arguments other than in the parameters
5872 // of a function declaration (C++ only).
5873 if (getLangOpts().CPlusPlus)
5874 CheckExtraCXXDefaultArguments(D);
5875
5876 NamedDecl *New;
5877
5878 bool AddToScope = true;
5879 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5880 if (TemplateParamLists.size()) {
5881 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5882 return nullptr;
5883 }
5884
5885 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5886 } else if (R->isFunctionType()) {
5887 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5888 TemplateParamLists,
5889 AddToScope);
5890 } else {
5891 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5892 AddToScope);
5893 }
5894
5895 if (!New)
5896 return nullptr;
5897
5898 // If this has an identifier and is not a function template specialization,
5899 // add it to the scope stack.
5900 if (New->getDeclName() && AddToScope)
5901 PushOnScopeChains(New, S);
5902
5903 if (isInOpenMPDeclareTargetContext())
5904 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5905
5906 return New;
5907}
5908
5909/// Helper method to turn variable array types into constant array
5910/// types in certain situations which would otherwise be errors (for
5911/// GCC compatibility).
5912static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5913 ASTContext &Context,
5914 bool &SizeIsNegative,
5915 llvm::APSInt &Oversized) {
5916 // This method tries to turn a variable array into a constant
5917 // array even when the size isn't an ICE. This is necessary
5918 // for compatibility with code that depends on gcc's buggy
5919 // constant expression folding, like struct {char x[(int)(char*)2];}
5920 SizeIsNegative = false;
5921 Oversized = 0;
5922
5923 if (T->isDependentType())
5924 return QualType();
5925
5926 QualifierCollector Qs;
5927 const Type *Ty = Qs.strip(T);
5928
5929 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5930 QualType Pointee = PTy->getPointeeType();
5931 QualType FixedType =
5932 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5933 Oversized);
5934 if (FixedType.isNull()) return FixedType;
5935 FixedType = Context.getPointerType(FixedType);
5936 return Qs.apply(Context, FixedType);
5937 }
5938 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5939 QualType Inner = PTy->getInnerType();
5940 QualType FixedType =
5941 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5942 Oversized);
5943 if (FixedType.isNull()) return FixedType;
5944 FixedType = Context.getParenType(FixedType);
5945 return Qs.apply(Context, FixedType);
5946 }
5947
5948 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5949 if (!VLATy)
5950 return QualType();
5951
5952 QualType ElemTy = VLATy->getElementType();
5953 if (ElemTy->isVariablyModifiedType()) {
5954 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
5955 SizeIsNegative, Oversized);
5956 if (ElemTy.isNull())
5957 return QualType();
5958 }
5959
5960 Expr::EvalResult Result;
5961 if (!VLATy->getSizeExpr() ||
5962 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
5963 return QualType();
5964
5965 llvm::APSInt Res = Result.Val.getInt();
5966
5967 // Check whether the array size is negative.
5968 if (Res.isSigned() && Res.isNegative()) {
5969 SizeIsNegative = true;
5970 return QualType();
5971 }
5972
5973 // Check whether the array is too large to be addressed.
5974 unsigned ActiveSizeBits =
5975 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
5976 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
5977 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
5978 : Res.getActiveBits();
5979 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5980 Oversized = Res;
5981 return QualType();
5982 }
5983
5984 QualType FoldedArrayType = Context.getConstantArrayType(
5985 ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
5986 return Qs.apply(Context, FoldedArrayType);
5987}
5988
5989static void
5990FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5991 SrcTL = SrcTL.getUnqualifiedLoc();
5992 DstTL = DstTL.getUnqualifiedLoc();
5993 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5994 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5995 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5996 DstPTL.getPointeeLoc());
5997 DstPTL.setStarLoc(SrcPTL.getStarLoc());
5998 return;
5999 }
6000 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6001 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6002 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6003 DstPTL.getInnerLoc());
6004 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6005 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6006 return;
6007 }
6008 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6009 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6010 TypeLoc SrcElemTL = SrcATL.getElementLoc();
6011 TypeLoc DstElemTL = DstATL.getElementLoc();
6012 if (VariableArrayTypeLoc SrcElemATL =
6013 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6014 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6015 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6016 } else {
6017 DstElemTL.initializeFullCopy(SrcElemTL);
6018 }
6019 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6020 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6021 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6022}
6023
6024/// Helper method to turn variable array types into constant array
6025/// types in certain situations which would otherwise be errors (for
6026/// GCC compatibility).
6027static TypeSourceInfo*
6028TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6029 ASTContext &Context,
6030 bool &SizeIsNegative,
6031 llvm::APSInt &Oversized) {
6032 QualType FixedTy
6033 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6034 SizeIsNegative, Oversized);
6035 if (FixedTy.isNull())
6036 return nullptr;
6037 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6038 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6039 FixedTInfo->getTypeLoc());
6040 return FixedTInfo;
6041}
6042
6043/// Attempt to fold a variable-sized type to a constant-sized type, returning
6044/// true if we were successful.
6045static bool tryToFixVariablyModifiedVarType(Sema &S, TypeSourceInfo *&TInfo,
6046 QualType &T, SourceLocation Loc,
6047 unsigned FailedFoldDiagID) {
6048 bool SizeIsNegative;
6049 llvm::APSInt Oversized;
6050 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6051 TInfo, S.Context, SizeIsNegative, Oversized);
6052 if (FixedTInfo) {
6053 S.Diag(Loc, diag::ext_vla_folded_to_constant);
6054 TInfo = FixedTInfo;
6055 T = FixedTInfo->getType();
6056 return true;
6057 }
6058
6059 if (SizeIsNegative)
6060 S.Diag(Loc, diag::err_typecheck_negative_array_size);
6061 else if (Oversized.getBoolValue())
6062 S.Diag(Loc, diag::err_array_too_large) << Oversized.toString(10);
6063 else if (FailedFoldDiagID)
6064 S.Diag(Loc, FailedFoldDiagID);
6065 return false;
6066}
6067
6068/// Register the given locally-scoped extern "C" declaration so
6069/// that it can be found later for redeclarations. We include any extern "C"
6070/// declaration that is not visible in the translation unit here, not just
6071/// function-scope declarations.
6072void
6073Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6074 if (!getLangOpts().CPlusPlus &&
6075 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6076 // Don't need to track declarations in the TU in C.
6077 return;
6078
6079 // Note that we have a locally-scoped external with this name.
6080 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6081}
6082
6083NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6084 // FIXME: We can have multiple results via __attribute__((overloadable)).
6085 auto Result = Context.getExternCContextDecl()->lookup(Name);
6086 return Result.empty() ? nullptr : *Result.begin();
6087}
6088
6089/// Diagnose function specifiers on a declaration of an identifier that
6090/// does not identify a function.
6091void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6092 // FIXME: We should probably indicate the identifier in question to avoid
6093 // confusion for constructs like "virtual int a(), b;"
6094 if (DS.isVirtualSpecified())
6095 Diag(DS.getVirtualSpecLoc(),
6096 diag::err_virtual_non_function);
6097
6098 if (DS.hasExplicitSpecifier())
6099 Diag(DS.getExplicitSpecLoc(),
6100 diag::err_explicit_non_function);
6101
6102 if (DS.isNoreturnSpecified())
6103 Diag(DS.getNoreturnSpecLoc(),
6104 diag::err_noreturn_non_function);
6105}
6106
6107NamedDecl*
6108Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6109 TypeSourceInfo *TInfo, LookupResult &Previous) {
6110 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6111 if (D.getCXXScopeSpec().isSet()) {
6112 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6113 << D.getCXXScopeSpec().getRange();
6114 D.setInvalidType();
6115 // Pretend we didn't see the scope specifier.
6116 DC = CurContext;
6117 Previous.clear();
6118 }
6119
6120 DiagnoseFunctionSpecifiers(D.getDeclSpec());
6121
6122 if (D.getDeclSpec().isInlineSpecified())
6123 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6124 << getLangOpts().CPlusPlus17;
6125 if (D.getDeclSpec().hasConstexprSpecifier())
6126 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6127 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6128
6129 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
6130 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
6131 Diag(D.getName().StartLocation,
6132 diag::err_deduction_guide_invalid_specifier)
6133 << "typedef";
6134 else
6135 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6136 << D.getName().getSourceRange();
6137 return nullptr;
6138 }
6139
6140 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6141 if (!NewTD) return nullptr;
6142
6143 // Handle attributes prior to checking for duplicates in MergeVarDecl
6144 ProcessDeclAttributes(S, NewTD, D);
6145
6146 CheckTypedefForVariablyModifiedType(S, NewTD);
6147
6148 bool Redeclaration = D.isRedeclaration();
6149 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6150 D.setRedeclaration(Redeclaration);
6151 return ND;
6152}
6153
6154void
6155Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6156 // C99 6.7.7p2: If a typedef name specifies a variably modified type
6157 // then it shall have block scope.
6158 // Note that variably modified types must be fixed before merging the decl so
6159 // that redeclarations will match.
6160 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6161 QualType T = TInfo->getType();
6162 if (T->isVariablyModifiedType()) {
6163 setFunctionHasBranchProtectedScope();
6164
6165 if (S->getFnParent() == nullptr) {
6166 bool SizeIsNegative;
6167 llvm::APSInt Oversized;
6168 TypeSourceInfo *FixedTInfo =
6169 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6170 SizeIsNegative,
6171 Oversized);
6172 if (FixedTInfo) {
6173 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6174 NewTD->setTypeSourceInfo(FixedTInfo);
6175 } else {
6176 if (SizeIsNegative)
6177 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6178 else if (T->isVariableArrayType())
6179 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6180 else if (Oversized.getBoolValue())
6181 Diag(NewTD->getLocation(), diag::err_array_too_large)
6182 << Oversized.toString(10);
6183 else
6184 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6185 NewTD->setInvalidDecl();
6186 }
6187 }
6188 }
6189}
6190
6191/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6192/// declares a typedef-name, either using the 'typedef' type specifier or via
6193/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6194NamedDecl*
6195Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6196 LookupResult &Previous, bool &Redeclaration) {
6197
6198 // Find the shadowed declaration before filtering for scope.
6199 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6200
6201 // Merge the decl with the existing one if appropriate. If the decl is
6202 // in an outer scope, it isn't the same thing.
6203 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6204 /*AllowInlineNamespace*/false);
6205 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6206 if (!Previous.empty()) {
6207 Redeclaration = true;
6208 MergeTypedefNameDecl(S, NewTD, Previous);
6209 } else {
6210 inferGslPointerAttribute(NewTD);
6211 }
6212
6213 if (ShadowedDecl && !Redeclaration)
6214 CheckShadow(NewTD, ShadowedDecl, Previous);
6215
6216 // If this is the C FILE type, notify the AST context.
6217 if (IdentifierInfo *II = NewTD->getIdentifier())
6218 if (!NewTD->isInvalidDecl() &&
6219 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6220 if (II->isStr("FILE"))
6221 Context.setFILEDecl(NewTD);
6222 else if (II->isStr("jmp_buf"))
6223 Context.setjmp_bufDecl(NewTD);
6224 else if (II->isStr("sigjmp_buf"))
6225 Context.setsigjmp_bufDecl(NewTD);
6226 else if (II->isStr("ucontext_t"))
6227 Context.setucontext_tDecl(NewTD);
6228 }
6229
6230 return NewTD;
6231}
6232
6233/// Determines whether the given declaration is an out-of-scope
6234/// previous declaration.
6235///
6236/// This routine should be invoked when name lookup has found a
6237/// previous declaration (PrevDecl) that is not in the scope where a
6238/// new declaration by the same name is being introduced. If the new
6239/// declaration occurs in a local scope, previous declarations with
6240/// linkage may still be considered previous declarations (C99
6241/// 6.2.2p4-5, C++ [basic.link]p6).
6242///
6243/// \param PrevDecl the previous declaration found by name
6244/// lookup
6245///
6246/// \param DC the context in which the new declaration is being
6247/// declared.
6248///
6249/// \returns true if PrevDecl is an out-of-scope previous declaration
6250/// for a new delcaration with the same name.
6251static bool
6252isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6253 ASTContext &Context) {
6254 if (!PrevDecl)
6255 return false;
6256
6257 if (!PrevDecl->hasLinkage())
6258 return false;
6259
6260 if (Context.getLangOpts().CPlusPlus) {
6261 // C++ [basic.link]p6:
6262 // If there is a visible declaration of an entity with linkage
6263 // having the same name and type, ignoring entities declared
6264 // outside the innermost enclosing namespace scope, the block
6265 // scope declaration declares that same entity and receives the
6266 // linkage of the previous declaration.
6267 DeclContext *OuterContext = DC->getRedeclContext();
6268 if (!OuterContext->isFunctionOrMethod())
6269 // This rule only applies to block-scope declarations.
6270 return false;
6271
6272 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6273 if (PrevOuterContext->isRecord())
6274 // We found a member function: ignore it.
6275 return false;
6276
6277 // Find the innermost enclosing namespace for the new and
6278 // previous declarations.
6279 OuterContext = OuterContext->getEnclosingNamespaceContext();
6280 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6281
6282 // The previous declaration is in a different namespace, so it
6283 // isn't the same function.
6284 if (!OuterContext->Equals(PrevOuterContext))
6285 return false;
6286 }
6287
6288 return true;
6289}
6290
6291static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6292 CXXScopeSpec &SS = D.getCXXScopeSpec();
6293 if (!SS.isSet()) return;
6294 DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6295}
6296
6297bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6298 QualType type = decl->getType();
6299 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6300 if (lifetime == Qualifiers::OCL_Autoreleasing) {
6301 // Various kinds of declaration aren't allowed to be __autoreleasing.
6302 unsigned kind = -1U;
6303 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6304 if (var->hasAttr<BlocksAttr>())
6305 kind = 0; // __block
6306 else if (!var->hasLocalStorage())
6307 kind = 1; // global
6308 } else if (isa<ObjCIvarDecl>(decl)) {
6309 kind = 3; // ivar
6310 } else if (isa<FieldDecl>(decl)) {
6311 kind = 2; // field
6312 }
6313
6314 if (kind != -1U) {
6315 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6316 << kind;
6317 }
6318 } else if (lifetime == Qualifiers::OCL_None) {
6319 // Try to infer lifetime.
6320 if (!type->isObjCLifetimeType())
6321 return false;
6322
6323 lifetime = type->getObjCARCImplicitLifetime();
6324 type = Context.getLifetimeQualifiedType(type, lifetime);
6325 decl->setType(type);
6326 }
6327
6328 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6329 // Thread-local variables cannot have lifetime.
6330 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6331 var->getTLSKind()) {
6332 Diag(var->getLocation(), diag::err_arc_thread_ownership)
6333 << var->getType();
6334 return true;
6335 }
6336 }
6337
6338 return false;
6339}
6340
6341void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6342 if (Decl->getType().hasAddressSpace())
6343 return;
6344 if (Decl->getType()->isDependentType())
6345 return;
6346 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6347 QualType Type = Var->getType();
6348 if (Type->isSamplerT() || Type->isVoidType())
6349 return;
6350 LangAS ImplAS = LangAS::opencl_private;
6351 if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) &&
6352 Var->hasGlobalStorage())
6353 ImplAS = LangAS::opencl_global;
6354 // If the original type from a decayed type is an array type and that array
6355 // type has no address space yet, deduce it now.
6356 if (auto DT = dyn_cast<DecayedType>(Type)) {
6357 auto OrigTy = DT->getOriginalType();
6358 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6359 // Add the address space to the original array type and then propagate
6360 // that to the element type through `getAsArrayType`.
6361 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6362 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6363 // Re-generate the decayed type.
6364 Type = Context.getDecayedType(OrigTy);
6365 }
6366 }
6367 Type = Context.getAddrSpaceQualType(Type, ImplAS);
6368 // Apply any qualifiers (including address space) from the array type to
6369 // the element type. This implements C99 6.7.3p8: "If the specification of
6370 // an array type includes any type qualifiers, the element type is so
6371 // qualified, not the array type."
6372 if (Type->isArrayType())
6373 Type = QualType(Context.getAsArrayType(Type), 0);
6374 Decl->setType(Type);
6375 }
6376}
6377
6378static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6379 // Ensure that an auto decl is deduced otherwise the checks below might cache
6380 // the wrong linkage.
6381 assert(S.ParsingInitForAutoVars.count(&ND) == 0)((S.ParsingInitForAutoVars.count(&ND) == 0) ? static_cast
<void> (0) : __assert_fail ("S.ParsingInitForAutoVars.count(&ND) == 0"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 6381, __PRETTY_FUNCTION__))
;
6382
6383 // 'weak' only applies to declarations with external linkage.
6384 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6385 if (!ND.isExternallyVisible()) {
6386 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6387 ND.dropAttr<WeakAttr>();
6388 }
6389 }
6390 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6391 if (ND.isExternallyVisible()) {
6392 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6393 ND.dropAttr<WeakRefAttr>();
6394 ND.dropAttr<AliasAttr>();
6395 }
6396 }
6397
6398 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6399 if (VD->hasInit()) {
6400 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6401 assert(VD->isThisDeclarationADefinition() &&((VD->isThisDeclarationADefinition() && !VD->isExternallyVisible
() && "Broken AliasAttr handled late!") ? static_cast
<void> (0) : __assert_fail ("VD->isThisDeclarationADefinition() && !VD->isExternallyVisible() && \"Broken AliasAttr handled late!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 6402, __PRETTY_FUNCTION__))
6402 !VD->isExternallyVisible() && "Broken AliasAttr handled late!")((VD->isThisDeclarationADefinition() && !VD->isExternallyVisible
() && "Broken AliasAttr handled late!") ? static_cast
<void> (0) : __assert_fail ("VD->isThisDeclarationADefinition() && !VD->isExternallyVisible() && \"Broken AliasAttr handled late!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 6402, __PRETTY_FUNCTION__))
;
6403 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6404 VD->dropAttr<AliasAttr>();
6405 }
6406 }
6407 }
6408
6409 // 'selectany' only applies to externally visible variable declarations.
6410 // It does not apply to functions.
6411 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6412 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6413 S.Diag(Attr->getLocation(),
6414 diag::err_attribute_selectany_non_extern_data);
6415 ND.dropAttr<SelectAnyAttr>();
6416 }
6417 }
6418
6419 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6420 auto *VD = dyn_cast<VarDecl>(&ND);
6421 bool IsAnonymousNS = false;
6422 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6423 if (VD) {
6424 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6425 while (NS && !IsAnonymousNS) {
6426 IsAnonymousNS = NS->isAnonymousNamespace();
6427 NS = dyn_cast<NamespaceDecl>(NS->getParent());
6428 }
6429 }
6430 // dll attributes require external linkage. Static locals may have external
6431 // linkage but still cannot be explicitly imported or exported.
6432 // In Microsoft mode, a variable defined in anonymous namespace must have
6433 // external linkage in order to be exported.
6434 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6435 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6436 (!AnonNSInMicrosoftMode &&
6437 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6438 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6439 << &ND << Attr;
6440 ND.setInvalidDecl();
6441 }
6442 }
6443
6444 // Check the attributes on the function type, if any.
6445 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6446 // Don't declare this variable in the second operand of the for-statement;
6447 // GCC miscompiles that by ending its lifetime before evaluating the
6448 // third operand. See gcc.gnu.org/PR86769.
6449 AttributedTypeLoc ATL;
6450 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6451 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6452 TL = ATL.getModifiedLoc()) {
6453 // The [[lifetimebound]] attribute can be applied to the implicit object
6454 // parameter of a non-static member function (other than a ctor or dtor)
6455 // by applying it to the function type.
6456 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6457 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6458 if (!MD || MD->isStatic()) {
6459 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6460 << !MD << A->getRange();
6461 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6462 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6463 << isa<CXXDestructorDecl>(MD) << A->getRange();
6464 }
6465 }
6466 }
6467 }
6468}
6469
6470static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6471 NamedDecl *NewDecl,
6472 bool IsSpecialization,
6473 bool IsDefinition) {
6474 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6475 return;
6476
6477 bool IsTemplate = false;
6478 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6479 OldDecl = OldTD->getTemplatedDecl();
6480 IsTemplate = true;
6481 if (!IsSpecialization)
6482 IsDefinition = false;
6483 }
6484 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6485 NewDecl = NewTD->getTemplatedDecl();
6486 IsTemplate = true;
6487 }
6488
6489 if (!OldDecl || !NewDecl)
6490 return;
6491
6492 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6493 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6494 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6495 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6496
6497 // dllimport and dllexport are inheritable attributes so we have to exclude
6498 // inherited attribute instances.
6499 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6500 (NewExportAttr && !NewExportAttr->isInherited());
6501
6502 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6503 // the only exception being explicit specializations.
6504 // Implicitly generated declarations are also excluded for now because there
6505 // is no other way to switch these to use dllimport or dllexport.
6506 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6507
6508 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6509 // Allow with a warning for free functions and global variables.
6510 bool JustWarn = false;
6511 if (!OldDecl->isCXXClassMember()) {
6512 auto *VD = dyn_cast<VarDecl>(OldDecl);
6513 if (VD && !VD->getDescribedVarTemplate())
6514 JustWarn = true;
6515 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6516 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6517 JustWarn = true;
6518 }
6519
6520 // We cannot change a declaration that's been used because IR has already
6521 // been emitted. Dllimported functions will still work though (modulo
6522 // address equality) as they can use the thunk.
6523 if (OldDecl->isUsed())
6524 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6525 JustWarn = false;
6526
6527 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6528 : diag::err_attribute_dll_redeclaration;
6529 S.Diag(NewDecl->getLocation(), DiagID)
6530 << NewDecl
6531 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6532 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6533 if (!JustWarn) {
6534 NewDecl->setInvalidDecl();
6535 return;
6536 }
6537 }
6538
6539 // A redeclaration is not allowed to drop a dllimport attribute, the only
6540 // exceptions being inline function definitions (except for function
6541 // templates), local extern declarations, qualified friend declarations or
6542 // special MSVC extension: in the last case, the declaration is treated as if
6543 // it were marked dllexport.
6544 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6545 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
6546 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6547 // Ignore static data because out-of-line definitions are diagnosed
6548 // separately.
6549 IsStaticDataMember = VD->isStaticDataMember();
6550 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6551 VarDecl::DeclarationOnly;
6552 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6553 IsInline = FD->isInlined();
6554 IsQualifiedFriend = FD->getQualifier() &&
6555 FD->getFriendObjectKind() == Decl::FOK_Declared;
6556 }
6557
6558 if (OldImportAttr && !HasNewAttr &&
6559 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
6560 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6561 if (IsMicrosoftABI && IsDefinition) {
6562 S.Diag(NewDecl->getLocation(),
6563 diag::warn_redeclaration_without_import_attribute)
6564 << NewDecl;
6565 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6566 NewDecl->dropAttr<DLLImportAttr>();
6567 NewDecl->addAttr(
6568 DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6569 } else {
6570 S.Diag(NewDecl->getLocation(),
6571 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6572 << NewDecl << OldImportAttr;
6573 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6574 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6575 OldDecl->dropAttr<DLLImportAttr>();
6576 NewDecl->dropAttr<DLLImportAttr>();
6577 }
6578 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
6579 // In MinGW, seeing a function declared inline drops the dllimport
6580 // attribute.
6581 OldDecl->dropAttr<DLLImportAttr>();
6582 NewDecl->dropAttr<DLLImportAttr>();
6583 S.Diag(NewDecl->getLocation(),
6584 diag::warn_dllimport_dropped_from_inline_function)
6585 << NewDecl << OldImportAttr;
6586 }
6587
6588 // A specialization of a class template member function is processed here
6589 // since it's a redeclaration. If the parent class is dllexport, the
6590 // specialization inherits that attribute. This doesn't happen automatically
6591 // since the parent class isn't instantiated until later.
6592 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6593 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6594 !NewImportAttr && !NewExportAttr) {
6595 if (const DLLExportAttr *ParentExportAttr =
6596 MD->getParent()->getAttr<DLLExportAttr>()) {
6597 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6598 NewAttr->setInherited(true);
6599 NewDecl->addAttr(NewAttr);
6600 }
6601 }
6602 }
6603}
6604
6605/// Given that we are within the definition of the given function,
6606/// will that definition behave like C99's 'inline', where the
6607/// definition is discarded except for optimization purposes?
6608static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6609 // Try to avoid calling GetGVALinkageForFunction.
6610
6611 // All cases of this require the 'inline' keyword.
6612 if (!FD->isInlined()) return false;
6613
6614 // This is only possible in C++ with the gnu_inline attribute.
6615 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6616 return false;
6617
6618 // Okay, go ahead and call the relatively-more-expensive function.
6619 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6620}
6621
6622/// Determine whether a variable is extern "C" prior to attaching
6623/// an initializer. We can't just call isExternC() here, because that
6624/// will also compute and cache whether the declaration is externally
6625/// visible, which might change when we attach the initializer.
6626///
6627/// This can only be used if the declaration is known to not be a
6628/// redeclaration of an internal linkage declaration.
6629///
6630/// For instance:
6631///
6632/// auto x = []{};
6633///
6634/// Attaching the initializer here makes this declaration not externally
6635/// visible, because its type has internal linkage.
6636///
6637/// FIXME: This is a hack.
6638template<typename T>
6639static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6640 if (S.getLangOpts().CPlusPlus) {
6641 // In C++, the overloadable attribute negates the effects of extern "C".
6642 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6643 return false;
6644
6645 // So do CUDA's host/device attributes.
6646 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6647 D->template hasAttr<CUDAHostAttr>()))
6648 return false;
6649 }
6650 return D->isExternC();
6651}
6652
6653static bool shouldConsiderLinkage(const VarDecl *VD) {
6654 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6655 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6656 isa<OMPDeclareMapperDecl>(DC))
6657 return VD->hasExternalStorage();
6658 if (DC->isFileContext())
6659 return true;
6660 if (DC->isRecord())
6661 return false;
6662 if (isa<RequiresExprBodyDecl>(DC))
6663 return false;
6664 llvm_unreachable("Unexpected context")::llvm::llvm_unreachable_internal("Unexpected context", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 6664)
;
6665}
6666
6667static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6668 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6669 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6670 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6671 return true;
6672 if (DC->isRecord())
6673 return false;
6674 llvm_unreachable("Unexpected context")::llvm::llvm_unreachable_internal("Unexpected context", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 6674)
;
6675}
6676
6677static bool hasParsedAttr(Scope *S, const Declarator &PD,
6678 ParsedAttr::Kind Kind) {
6679 // Check decl attributes on the DeclSpec.
6680 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6681 return true;
6682
6683 // Walk the declarator structure, checking decl attributes that were in a type
6684 // position to the decl itself.
6685 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6686 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6687 return true;
6688 }
6689
6690 // Finally, check attributes on the decl itself.
6691 return PD.getAttributes().hasAttribute(Kind);
6692}
6693
6694/// Adjust the \c DeclContext for a function or variable that might be a
6695/// function-local external declaration.
6696bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6697 if (!DC->isFunctionOrMethod())
6698 return false;
6699
6700 // If this is a local extern function or variable declared within a function
6701 // template, don't add it into the enclosing namespace scope until it is
6702 // instantiated; it might have a dependent type right now.
6703 if (DC->isDependentContext())
6704 return true;
6705
6706 // C++11 [basic.link]p7:
6707 // When a block scope declaration of an entity with linkage is not found to
6708 // refer to some other declaration, then that entity is a member of the
6709 // innermost enclosing namespace.
6710 //
6711 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6712 // semantically-enclosing namespace, not a lexically-enclosing one.
6713 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6714 DC = DC->getParent();
6715 return true;
6716}
6717
6718/// Returns true if given declaration has external C language linkage.
6719static bool isDeclExternC(const Decl *D) {
6720 if (const auto *FD = dyn_cast<FunctionDecl>(D))
6721 return FD->isExternC();
6722 if (const auto *VD = dyn_cast<VarDecl>(D))
6723 return VD->isExternC();
6724
6725 llvm_unreachable("Unknown type of decl!")::llvm::llvm_unreachable_internal("Unknown type of decl!", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 6725)
;
6726}
6727/// Returns true if there hasn't been any invalid type diagnosed.
6728static bool diagnoseOpenCLTypes(Scope *S, Sema &Se, Declarator &D,
6729 DeclContext *DC, QualType R) {
6730 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6731 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6732 // argument.
6733 if (R->isImageType() || R->isPipeType()) {
6734 Se.Diag(D.getIdentifierLoc(),
6735 diag::err_opencl_type_can_only_be_used_as_function_parameter)
6736 << R;
6737 D.setInvalidType();
6738 return false;
6739 }
6740
6741 // OpenCL v1.2 s6.9.r:
6742 // The event type cannot be used to declare a program scope variable.
6743 // OpenCL v2.0 s6.9.q:
6744 // The clk_event_t and reserve_id_t types cannot be declared in program
6745 // scope.
6746 if (NULL__null == S->getParent()) {
6747 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6748 Se.Diag(D.getIdentifierLoc(),
6749 diag::err_invalid_type_for_program_scope_var)
6750 << R;
6751 D.setInvalidType();
6752 return false;
6753 }
6754 }
6755
6756 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6757 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
6758 Se.getLangOpts())) {
6759 QualType NR = R.getCanonicalType();
6760 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
6761 NR->isReferenceType()) {
6762 if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
6763 NR->isFunctionReferenceType()) {
6764 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer)
6765 << NR->isReferenceType();
6766 D.setInvalidType();
6767 return false;
6768 }
6769 NR = NR->getPointeeType();
6770 }
6771 }
6772
6773 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
6774 Se.getLangOpts())) {
6775 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6776 // half array type (unless the cl_khr_fp16 extension is enabled).
6777 if (Se.Context.getBaseElementType(R)->isHalfType()) {
6778 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6779 D.setInvalidType();
6780 return false;
6781 }
6782 }
6783
6784 // OpenCL v1.2 s6.9.r:
6785 // The event type cannot be used with the __local, __constant and __global
6786 // address space qualifiers.
6787 if (R->isEventT()) {
6788 if (R.getAddressSpace() != LangAS::opencl_private) {
6789 Se.Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
6790 D.setInvalidType();
6791 return false;
6792 }
6793 }
6794
6795 // C++ for OpenCL does not allow the thread_local storage qualifier.
6796 // OpenCL C does not support thread_local either, and
6797 // also reject all other thread storage class specifiers.
6798 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
6799 if (TSC != TSCS_unspecified) {
6800 bool IsCXX = Se.getLangOpts().OpenCLCPlusPlus;
6801 Se.Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6802 diag::err_opencl_unknown_type_specifier)
6803 << IsCXX << Se.getLangOpts().getOpenCLVersionTuple().getAsString()
6804 << DeclSpec::getSpecifierName(TSC) << 1;
6805 D.setInvalidType();
6806 return false;
6807 }
6808
6809 if (R->isSamplerT()) {
6810 // OpenCL v1.2 s6.9.b p4:
6811 // The sampler type cannot be used with the __local and __global address
6812 // space qualifiers.
6813 if (R.getAddressSpace() == LangAS::opencl_local ||
6814 R.getAddressSpace() == LangAS::opencl_global) {
6815 Se.Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6816 D.setInvalidType();
6817 }
6818
6819 // OpenCL v1.2 s6.12.14.1:
6820 // A global sampler must be declared with either the constant address
6821 // space qualifier or with the const qualifier.
6822 if (DC->isTranslationUnit() &&
6823 !(R.getAddressSpace() == LangAS::opencl_constant ||
6824 R.isConstQualified())) {
6825 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6826 D.setInvalidType();
6827 }
6828 if (D.isInvalidType())
6829 return false;
6830 }
6831 return true;
6832}
6833
6834template <typename AttrTy>
6835static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
6836 const TypedefNameDecl *TND = TT->getDecl();
6837 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
6838 AttrTy *Clone = Attribute->clone(S.Context);
6839 Clone->setInherited(true);
6840 D->addAttr(Clone);
6841 }
6842}
6843
6844NamedDecl *Sema::ActOnVariableDeclarator(
6845 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6846 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6847 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6848 QualType R = TInfo->getType();
6849 DeclarationName Name = GetNameForDeclarator(D).getName();
6850
6851 IdentifierInfo *II = Name.getAsIdentifierInfo();
6852
6853 if (D.isDecompositionDeclarator()) {
6854 // Take the name of the first declarator as our name for diagnostic
6855 // purposes.
6856 auto &Decomp = D.getDecompositionDeclarator();
6857 if (!Decomp.bindings().empty()) {
6858 II = Decomp.bindings()[0].Name;
6859 Name = II;
6860 }
6861 } else if (!II) {
6862 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6863 return nullptr;
6864 }
6865
6866
6867 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6868 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6869
6870 // dllimport globals without explicit storage class are treated as extern. We
6871 // have to change the storage class this early to get the right DeclContext.
6872 if (SC == SC_None && !DC->isRecord() &&
6873 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6874 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6875 SC = SC_Extern;
6876
6877 DeclContext *OriginalDC = DC;
6878 bool IsLocalExternDecl = SC == SC_Extern &&
6879 adjustContextForLocalExternDecl(DC);
6880
6881 if (SCSpec == DeclSpec::SCS_mutable) {
6882 // mutable can only appear on non-static class members, so it's always
6883 // an error here
6884 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6885 D.setInvalidType();
6886 SC = SC_None;
6887 }
6888
6889 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6890 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6891 D.getDeclSpec().getStorageClassSpecLoc())) {
6892 // In C++11, the 'register' storage class specifier is deprecated.
6893 // Suppress the warning in system macros, it's used in macros in some
6894 // popular C system headers, such as in glibc's htonl() macro.
6895 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6896 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6897 : diag::warn_deprecated_register)
6898 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6899 }
6900
6901 DiagnoseFunctionSpecifiers(D.getDeclSpec());
6902
6903 if (!DC->isRecord() && S->getFnParent() == nullptr) {
6904 // C99 6.9p2: The storage-class specifiers auto and register shall not
6905 // appear in the declaration specifiers in an external declaration.
6906 // Global Register+Asm is a GNU extension we support.
6907 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6908 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6909 D.setInvalidType();
6910 }
6911 }
6912
6913 // If this variable has a variable-modified type and an initializer, try to
6914 // fold to a constant-sized type. This is otherwise invalid.
6915 if (D.hasInitializer() && R->isVariablyModifiedType())
6916 tryToFixVariablyModifiedVarType(*this, TInfo, R, D.getIdentifierLoc(),
6917 /*DiagID=*/0);
6918
6919 bool IsMemberSpecialization = false;
6920 bool IsVariableTemplateSpecialization = false;
6921 bool IsPartialSpecialization = false;
6922 bool IsVariableTemplate = false;
6923 VarDecl *NewVD = nullptr;
6924 VarTemplateDecl *NewTemplate = nullptr;
6925 TemplateParameterList *TemplateParams = nullptr;
6926 if (!getLangOpts().CPlusPlus) {
6927 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6928 II, R, TInfo, SC);
6929
6930 if (R->getContainedDeducedType())
6931 ParsingInitForAutoVars.insert(NewVD);
6932
6933 if (D.isInvalidType())
6934 NewVD->setInvalidDecl();
6935
6936 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
6937 NewVD->hasLocalStorage())
6938 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
6939 NTCUC_AutoVar, NTCUK_Destruct);
6940 } else {
6941 bool Invalid = false;
6942
6943 if (DC->isRecord() && !CurContext->isRecord()) {
6944 // This is an out-of-line definition of a static data member.
6945 switch (SC) {
6946 case SC_None:
6947 break;
6948 case SC_Static:
6949 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6950 diag::err_static_out_of_line)
6951 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6952 break;
6953 case SC_Auto:
6954 case SC_Register:
6955 case SC_Extern:
6956 // [dcl.stc] p2: The auto or register specifiers shall be applied only
6957 // to names of variables declared in a block or to function parameters.
6958 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6959 // of class members
6960
6961 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6962 diag::err_storage_class_for_static_member)
6963 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6964 break;
6965 case SC_PrivateExtern:
6966 llvm_unreachable("C storage class in c++!")::llvm::llvm_unreachable_internal("C storage class in c++!", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 6966)
;
6967 }
6968 }
6969
6970 if (SC == SC_Static && CurContext->isRecord()) {
6971 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6972 // Walk up the enclosing DeclContexts to check for any that are
6973 // incompatible with static data members.
6974 const DeclContext *FunctionOrMethod = nullptr;
6975 const CXXRecordDecl *AnonStruct = nullptr;
6976 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
6977 if (Ctxt->isFunctionOrMethod()) {
6978 FunctionOrMethod = Ctxt;
6979 break;
6980 }
6981 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
6982 if (ParentDecl && !ParentDecl->getDeclName()) {
6983 AnonStruct = ParentDecl;
6984 break;
6985 }
6986 }
6987 if (FunctionOrMethod) {
6988 // C++ [class.static.data]p5: A local class shall not have static data
6989 // members.
6990 Diag(D.getIdentifierLoc(),
6991 diag::err_static_data_member_not_allowed_in_local_class)
6992 << Name << RD->getDeclName() << RD->getTagKind();
6993 } else if (AnonStruct) {
6994 // C++ [class.static.data]p4: Unnamed classes and classes contained
6995 // directly or indirectly within unnamed classes shall not contain
6996 // static data members.
6997 Diag(D.getIdentifierLoc(),
6998 diag::err_static_data_member_not_allowed_in_anon_struct)
6999 << Name << AnonStruct->getTagKind();
7000 Invalid = true;
7001 } else if (RD->isUnion()) {
7002 // C++98 [class.union]p1: If a union contains a static data member,
7003 // the program is ill-formed. C++11 drops this restriction.
7004 Diag(D.getIdentifierLoc(),
7005 getLangOpts().CPlusPlus11
7006 ? diag::warn_cxx98_compat_static_data_member_in_union
7007 : diag::ext_static_data_member_in_union) << Name;
7008 }
7009 }
7010 }
7011
7012 // Match up the template parameter lists with the scope specifier, then
7013 // determine whether we have a template or a template specialization.
7014 bool InvalidScope = false;
7015 TemplateParams = MatchTemplateParametersToScopeSpecifier(
7016 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7017 D.getCXXScopeSpec(),
7018 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7019 ? D.getName().TemplateId
7020 : nullptr,
7021 TemplateParamLists,
7022 /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
7023 Invalid |= InvalidScope;
7024
7025 if (TemplateParams) {
7026 if (!TemplateParams->size() &&
7027 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7028 // There is an extraneous 'template<>' for this variable. Complain
7029 // about it, but allow the declaration of the variable.
7030 Diag(TemplateParams->getTemplateLoc(),
7031 diag::err_template_variable_noparams)
7032 << II
7033 << SourceRange(TemplateParams->getTemplateLoc(),
7034 TemplateParams->getRAngleLoc());
7035 TemplateParams = nullptr;
7036 } else {
7037 // Check that we can declare a template here.
7038 if (CheckTemplateDeclScope(S, TemplateParams))
7039 return nullptr;
7040
7041 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7042 // This is an explicit specialization or a partial specialization.
7043 IsVariableTemplateSpecialization = true;
7044 IsPartialSpecialization = TemplateParams->size() > 0;
7045 } else { // if (TemplateParams->size() > 0)
7046 // This is a template declaration.
7047 IsVariableTemplate = true;
7048
7049 // Only C++1y supports variable templates (N3651).
7050 Diag(D.getIdentifierLoc(),
7051 getLangOpts().CPlusPlus14
7052 ? diag::warn_cxx11_compat_variable_template
7053 : diag::ext_variable_template);
7054 }
7055 }
7056 } else {
7057 // Check that we can declare a member specialization here.
7058 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7059 CheckTemplateDeclScope(S, TemplateParamLists.back()))
7060 return nullptr;
7061 assert((Invalid ||(((Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId
) && "should have a 'template<>' for this decl"
) ? static_cast<void> (0) : __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && \"should have a 'template<>' for this decl\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 7063, __PRETTY_FUNCTION__))
7062 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&(((Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId
) && "should have a 'template<>' for this decl"
) ? static_cast<void> (0) : __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && \"should have a 'template<>' for this decl\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 7063, __PRETTY_FUNCTION__))
7063 "should have a 'template<>' for this decl")(((Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId
) && "should have a 'template<>' for this decl"
) ? static_cast<void> (0) : __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && \"should have a 'template<>' for this decl\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 7063, __PRETTY_FUNCTION__))
;
7064 }
7065
7066 if (IsVariableTemplateSpecialization) {
7067 SourceLocation TemplateKWLoc =
7068 TemplateParamLists.size() > 0
7069 ? TemplateParamLists[0]->getTemplateLoc()
7070 : SourceLocation();
7071 DeclResult Res = ActOnVarTemplateSpecialization(
7072 S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7073 IsPartialSpecialization);
7074 if (Res.isInvalid())
7075 return nullptr;
7076 NewVD = cast<VarDecl>(Res.get());
7077 AddToScope = false;
7078 } else if (D.isDecompositionDeclarator()) {
7079 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7080 D.getIdentifierLoc(), R, TInfo, SC,
7081 Bindings);
7082 } else
7083 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7084 D.getIdentifierLoc(), II, R, TInfo, SC);
7085
7086 // If this is supposed to be a variable template, create it as such.
7087 if (IsVariableTemplate) {
7088 NewTemplate =
7089 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7090 TemplateParams, NewVD);
7091 NewVD->setDescribedVarTemplate(NewTemplate);
7092 }
7093
7094 // If this decl has an auto type in need of deduction, make a note of the
7095 // Decl so we can diagnose uses of it in its own initializer.
7096 if (R->getContainedDeducedType())
7097 ParsingInitForAutoVars.insert(NewVD);
7098
7099 if (D.isInvalidType() || Invalid) {
7100 NewVD->setInvalidDecl();
7101 if (NewTemplate)
7102 NewTemplate->setInvalidDecl();
7103 }
7104
7105 SetNestedNameSpecifier(*this, NewVD, D);
7106
7107 // If we have any template parameter lists that don't directly belong to
7108 // the variable (matching the scope specifier), store them.
7109 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7110 if (TemplateParamLists.size() > VDTemplateParamLists)
7111 NewVD->setTemplateParameterListsInfo(
7112 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7113 }
7114
7115 if (D.getDeclSpec().isInlineSpecified()) {
7116 if (!getLangOpts().CPlusPlus) {
7117 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7118 << 0;
7119 } else if (CurContext->isFunctionOrMethod()) {
7120 // 'inline' is not allowed on block scope variable declaration.
7121 Diag(D.getDeclSpec().getInlineSpecLoc(),
7122 diag::err_inline_declaration_block_scope) << Name
7123 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7124 } else {
7125 Diag(D.getDeclSpec().getInlineSpecLoc(),
7126 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7127 : diag::ext_inline_variable);
7128 NewVD->setInlineSpecified();
7129 }
7130 }
7131
7132 // Set the lexical context. If the declarator has a C++ scope specifier, the
7133 // lexical context will be different from the semantic context.
7134 NewVD->setLexicalDeclContext(CurContext);
7135 if (NewTemplate)
7136 NewTemplate->setLexicalDeclContext(CurContext);
7137
7138 if (IsLocalExternDecl) {
7139 if (D.isDecompositionDeclarator())
7140 for (auto *B : Bindings)
7141 B->setLocalExternDecl();
7142 else
7143 NewVD->setLocalExternDecl();
7144 }
7145
7146 bool EmitTLSUnsupportedError = false;
7147 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7148 // C++11 [dcl.stc]p4:
7149 // When thread_local is applied to a variable of block scope the
7150 // storage-class-specifier static is implied if it does not appear
7151 // explicitly.
7152 // Core issue: 'static' is not implied if the variable is declared
7153 // 'extern'.
7154 if (NewVD->hasLocalStorage() &&
7155 (SCSpec != DeclSpec::SCS_unspecified ||
7156 TSCS != DeclSpec::TSCS_thread_local ||
7157 !DC->isFunctionOrMethod()))
7158 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7159 diag::err_thread_non_global)
7160 << DeclSpec::getSpecifierName(TSCS);
7161 else if (!Context.getTargetInfo().isTLSSupported()) {
7162 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7163 getLangOpts().SYCLIsDevice) {
7164 // Postpone error emission until we've collected attributes required to
7165 // figure out whether it's a host or device variable and whether the
7166 // error should be ignored.
7167 EmitTLSUnsupportedError = true;
7168 // We still need to mark the variable as TLS so it shows up in AST with
7169 // proper storage class for other tools to use even if we're not going
7170 // to emit any code for it.
7171 NewVD->setTSCSpec(TSCS);
7172 } else
7173 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7174 diag::err_thread_unsupported);
7175 } else
7176 NewVD->setTSCSpec(TSCS);
7177 }
7178
7179 switch (D.getDeclSpec().getConstexprSpecifier()) {
7180 case ConstexprSpecKind::Unspecified:
7181 break;
7182
7183 case ConstexprSpecKind::Consteval:
7184 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7185 diag::err_constexpr_wrong_decl_kind)
7186 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7187 LLVM_FALLTHROUGH[[gnu::fallthrough]];
7188
7189 case ConstexprSpecKind::Constexpr:
7190 NewVD->setConstexpr(true);
7191 MaybeAddCUDAConstantAttr(NewVD);
7192 // C++1z [dcl.spec.constexpr]p1:
7193 // A static data member declared with the constexpr specifier is
7194 // implicitly an inline variable.
7195 if (NewVD->isStaticDataMember() &&
7196 (getLangOpts().CPlusPlus17 ||
7197 Context.getTargetInfo().getCXXABI().isMicrosoft()))
7198 NewVD->setImplicitlyInline();
7199 break;
7200
7201 case ConstexprSpecKind::Constinit:
7202 if (!NewVD->hasGlobalStorage())
7203 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7204 diag::err_constinit_local_variable);
7205 else
7206 NewVD->addAttr(ConstInitAttr::Create(
7207 Context, D.getDeclSpec().getConstexprSpecLoc(),
7208 AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7209 break;
7210 }
7211
7212 // C99 6.7.4p3
7213 // An inline definition of a function with external linkage shall
7214 // not contain a definition of a modifiable object with static or
7215 // thread storage duration...
7216 // We only apply this when the function is required to be defined
7217 // elsewhere, i.e. when the function is not 'extern inline'. Note
7218 // that a local variable with thread storage duration still has to
7219 // be marked 'static'. Also note that it's possible to get these
7220 // semantics in C++ using __attribute__((gnu_inline)).
7221 if (SC == SC_Static && S->getFnParent() != nullptr &&
7222 !NewVD->getType().isConstQualified()) {
7223 FunctionDecl *CurFD = getCurFunctionDecl();
7224 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7225 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7226 diag::warn_static_local_in_extern_inline);
7227 MaybeSuggestAddingStaticToDecl(CurFD);
7228 }
7229 }
7230
7231 if (D.getDeclSpec().isModulePrivateSpecified()) {
7232 if (IsVariableTemplateSpecialization)
7233 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7234 << (IsPartialSpecialization ? 1 : 0)
7235 << FixItHint::CreateRemoval(
7236 D.getDeclSpec().getModulePrivateSpecLoc());
7237 else if (IsMemberSpecialization)
7238 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7239 << 2
7240 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7241 else if (NewVD->hasLocalStorage())
7242 Diag(NewVD->getLocation(), diag::err_module_private_local)
7243 << 0 << NewVD
7244 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7245 << FixItHint::CreateRemoval(
7246 D.getDeclSpec().getModulePrivateSpecLoc());
7247 else {
7248 NewVD->setModulePrivate();
7249 if (NewTemplate)
7250 NewTemplate->setModulePrivate();
7251 for (auto *B : Bindings)
7252 B->setModulePrivate();
7253 }
7254 }
7255
7256 if (getLangOpts().OpenCL) {
7257
7258 deduceOpenCLAddressSpace(NewVD);
7259
7260 diagnoseOpenCLTypes(S, *this, D, DC, NewVD->getType());
7261 }
7262
7263 // Handle attributes prior to checking for duplicates in MergeVarDecl
7264 ProcessDeclAttributes(S, NewVD, D);
7265
7266 // FIXME: This is probably the wrong location to be doing this and we should
7267 // probably be doing this for more attributes (especially for function
7268 // pointer attributes such as format, warn_unused_result, etc.). Ideally
7269 // the code to copy attributes would be generated by TableGen.
7270 if (R->isFunctionPointerType())
7271 if (const auto *TT = R->getAs<TypedefType>())
7272 copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7273
7274 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7275 getLangOpts().SYCLIsDevice) {
7276 if (EmitTLSUnsupportedError &&
7277 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7278 (getLangOpts().OpenMPIsDevice &&
7279 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7280 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7281 diag::err_thread_unsupported);
7282
7283 if (EmitTLSUnsupportedError &&
7284 (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
7285 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7286 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7287 // storage [duration]."
7288 if (SC == SC_None && S->getFnParent() != nullptr &&
7289 (NewVD->hasAttr<CUDASharedAttr>() ||
7290 NewVD->hasAttr<CUDAConstantAttr>())) {
7291 NewVD->setStorageClass(SC_Static);
7292 }
7293 }
7294
7295 // Ensure that dllimport globals without explicit storage class are treated as
7296 // extern. The storage class is set above using parsed attributes. Now we can
7297 // check the VarDecl itself.
7298 assert(!NewVD->hasAttr<DLLImportAttr>() ||((!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr
<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember
() || NewVD->getStorageClass() != SC_None) ? static_cast<
void> (0) : __assert_fail ("!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 7300, __PRETTY_FUNCTION__))
7299 NewVD->getAttr<DLLImportAttr>()->isInherited() ||((!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr
<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember
() || NewVD->getStorageClass() != SC_None) ? static_cast<
void> (0) : __assert_fail ("!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 7300, __PRETTY_FUNCTION__))
7300 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None)((!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr
<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember
() || NewVD->getStorageClass() != SC_None) ? static_cast<
void> (0) : __assert_fail ("!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 7300, __PRETTY_FUNCTION__))
;
7301
7302 // In auto-retain/release, infer strong retension for variables of
7303 // retainable type.
7304 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7305 NewVD->setInvalidDecl();
7306
7307 // Handle GNU asm-label extension (encoded as an attribute).
7308 if (Expr *E = (Expr*)D.getAsmLabel()) {
7309 // The parser guarantees this is a string.
7310 StringLiteral *SE = cast<StringLiteral>(E);
7311 StringRef Label = SE->getString();
7312 if (S->getFnParent() != nullptr) {
7313 switch (SC) {
7314 case SC_None:
7315 case SC_Auto:
7316 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7317 break;
7318 case SC_Register:
7319 // Local Named register
7320 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7321 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7322 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7323 break;
7324 case SC_Static:
7325 case SC_Extern:
7326 case SC_PrivateExtern:
7327 break;
7328 }
7329 } else if (SC == SC_Register) {
7330 // Global Named register
7331 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7332 const auto &TI = Context.getTargetInfo();
7333 bool HasSizeMismatch;
7334
7335 if (!TI.isValidGCCRegisterName(Label))
7336 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7337 else if (!TI.validateGlobalRegisterVariable(Label,
7338 Context.getTypeSize(R),
7339 HasSizeMismatch))
7340 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7341 else if (HasSizeMismatch)
7342 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7343 }
7344
7345 if (!R->isIntegralType(Context) && !R->isPointerType()) {
7346 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7347 NewVD->setInvalidDecl(true);
7348 }
7349 }
7350
7351 NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7352 /*IsLiteralLabel=*/true,
7353 SE->getStrTokenLoc(0)));
7354 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7355 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7356 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7357 if (I != ExtnameUndeclaredIdentifiers.end()) {
7358 if (isDeclExternC(NewVD)) {
7359 NewVD->addAttr(I->second);
7360 ExtnameUndeclaredIdentifiers.erase(I);
7361 } else
7362 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7363 << /*Variable*/1 << NewVD;
7364 }
7365 }
7366
7367 // Find the shadowed declaration before filtering for scope.
7368 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7369 ? getShadowedDeclaration(NewVD, Previous)
7370 : nullptr;
7371
7372 // Don't consider existing declarations that are in a different
7373 // scope and are out-of-semantic-context declarations (if the new
7374 // declaration has linkage).
7375 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7376 D.getCXXScopeSpec().isNotEmpty() ||
7377 IsMemberSpecialization ||
7378 IsVariableTemplateSpecialization);
7379
7380 // Check whether the previous declaration is in the same block scope. This
7381 // affects whether we merge types with it, per C++11 [dcl.array]p3.
7382 if (getLangOpts().CPlusPlus &&
7383 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7384 NewVD->setPreviousDeclInSameBlockScope(
7385 Previous.isSingleResult() && !Previous.isShadowed() &&
7386 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7387
7388 if (!getLangOpts().CPlusPlus) {
7389 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7390 } else {
7391 // If this is an explicit specialization of a static data member, check it.
7392 if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7393 CheckMemberSpecialization(NewVD, Previous))
7394 NewVD->setInvalidDecl();
7395
7396 // Merge the decl with the existing one if appropriate.
7397 if (!Previous.empty()) {
7398 if (Previous.isSingleResult() &&
7399 isa<FieldDecl>(Previous.getFoundDecl()) &&
7400 D.getCXXScopeSpec().isSet()) {
7401 // The user tried to define a non-static data member
7402 // out-of-line (C++ [dcl.meaning]p1).
7403 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7404 << D.getCXXScopeSpec().getRange();
7405 Previous.clear();
7406 NewVD->setInvalidDecl();
7407 }
7408 } else if (D.getCXXScopeSpec().isSet()) {
7409 // No previous declaration in the qualifying scope.
7410 Diag(D.getIdentifierLoc(), diag::err_no_member)
7411 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7412 << D.getCXXScopeSpec().getRange();
7413 NewVD->setInvalidDecl();
7414 }
7415
7416 if (!IsVariableTemplateSpecialization)
7417 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7418
7419 if (NewTemplate) {
7420 VarTemplateDecl *PrevVarTemplate =
7421 NewVD->getPreviousDecl()
7422 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7423 : nullptr;
7424
7425 // Check the template parameter list of this declaration, possibly
7426 // merging in the template parameter list from the previous variable
7427 // template declaration.
7428 if (CheckTemplateParameterList(
7429 TemplateParams,
7430 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7431 : nullptr,
7432 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7433 DC->isDependentContext())
7434 ? TPC_ClassTemplateMember
7435 : TPC_VarTemplate))
7436 NewVD->setInvalidDecl();
7437
7438 // If we are providing an explicit specialization of a static variable
7439 // template, make a note of that.
7440 if (PrevVarTemplate &&
7441 PrevVarTemplate->getInstantiatedFromMemberTemplate())
7442 PrevVarTemplate->setMemberSpecialization();
7443 }
7444 }
7445
7446 // Diagnose shadowed variables iff this isn't a redeclaration.
7447 if (ShadowedDecl && !D.isRedeclaration())
7448 CheckShadow(NewVD, ShadowedDecl, Previous);
7449
7450 ProcessPragmaWeak(S, NewVD);
7451
7452 // If this is the first declaration of an extern C variable, update
7453 // the map of such variables.
7454 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7455 isIncompleteDeclExternC(*this, NewVD))
7456 RegisterLocallyScopedExternCDecl(NewVD, S);
7457
7458 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7459 MangleNumberingContext *MCtx;
7460 Decl *ManglingContextDecl;
7461 std::tie(MCtx, ManglingContextDecl) =
7462 getCurrentMangleNumberContext(NewVD->getDeclContext());
7463 if (MCtx) {
7464 Context.setManglingNumber(
7465 NewVD, MCtx->getManglingNumber(
7466 NewVD, getMSManglingNumber(getLangOpts(), S)));
7467 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7468 }
7469 }
7470
7471 // Special handling of variable named 'main'.
7472 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7473 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7474 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7475
7476 // C++ [basic.start.main]p3
7477 // A program that declares a variable main at global scope is ill-formed.
7478 if (getLangOpts().CPlusPlus)
7479 Diag(D.getBeginLoc(), diag::err_main_global_variable);
7480
7481 // In C, and external-linkage variable named main results in undefined
7482 // behavior.
7483 else if (NewVD->hasExternalFormalLinkage())
7484 Diag(D.getBeginLoc(), diag::warn_main_redefined);
7485 }
7486
7487 if (D.isRedeclaration() && !Previous.empty()) {
7488 NamedDecl *Prev = Previous.getRepresentativeDecl();
7489 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7490 D.isFunctionDefinition());
7491 }
7492
7493 if (NewTemplate) {
7494 if (NewVD->isInvalidDecl())
7495 NewTemplate->setInvalidDecl();
7496 ActOnDocumentableDecl(NewTemplate);
7497 return NewTemplate;
7498 }
7499
7500 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7501 CompleteMemberSpecialization(NewVD, Previous);
7502
7503 return NewVD;
7504}
7505
7506/// Enum describing the %select options in diag::warn_decl_shadow.
7507enum ShadowedDeclKind {
7508 SDK_Local,
7509 SDK_Global,
7510 SDK_StaticMember,
7511 SDK_Field,
7512 SDK_Typedef,
7513 SDK_Using,
7514 SDK_StructuredBinding
7515};
7516
7517/// Determine what kind of declaration we're shadowing.
7518static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7519 const DeclContext *OldDC) {
7520 if (isa<TypeAliasDecl>(ShadowedDecl))
7521 return SDK_Using;
7522 else if (isa<TypedefDecl>(ShadowedDecl))
7523 return SDK_Typedef;
7524 else if (isa<BindingDecl>(ShadowedDecl))
7525 return SDK_StructuredBinding;
7526 else if (isa<RecordDecl>(OldDC))
7527 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7528
7529 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7530}
7531
7532/// Return the location of the capture if the given lambda captures the given
7533/// variable \p VD, or an invalid source location otherwise.
7534static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7535 const VarDecl *VD) {
7536 for (const Capture &Capture : LSI->Captures) {
7537 if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7538 return Capture.getLocation();
7539 }
7540 return SourceLocation();
7541}
7542
7543static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7544 const LookupResult &R) {
7545 // Only diagnose if we're shadowing an unambiguous field or variable.
7546 if (R.getResultKind() != LookupResult::Found)
7547 return false;
7548
7549 // Return false if warning is ignored.
7550 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7551}
7552
7553/// Return the declaration shadowed by the given variable \p D, or null
7554/// if it doesn't shadow any declaration or shadowing warnings are disabled.
7555NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7556 const LookupResult &R) {
7557 if (!shouldWarnIfShadowedDecl(Diags, R))
7558 return nullptr;
7559
7560 // Don't diagnose declarations at file scope.
7561 if (D->hasGlobalStorage())
7562 return nullptr;
7563
7564 NamedDecl *ShadowedDecl = R.getFoundDecl();
7565 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7566 : nullptr;
7567}
7568
7569/// Return the declaration shadowed by the given typedef \p D, or null
7570/// if it doesn't shadow any declaration or shadowing warnings are disabled.
7571NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7572 const LookupResult &R) {
7573 // Don't warn if typedef declaration is part of a class
7574 if (D->getDeclContext()->isRecord())
7575 return nullptr;
7576
7577 if (!shouldWarnIfShadowedDecl(Diags, R))
7578 return nullptr;
7579
7580 NamedDecl *ShadowedDecl = R.getFoundDecl();
7581 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7582}
7583
7584/// Return the declaration shadowed by the given variable \p D, or null
7585/// if it doesn't shadow any declaration or shadowing warnings are disabled.
7586NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
7587 const LookupResult &R) {
7588 if (!shouldWarnIfShadowedDecl(Diags, R))
7589 return nullptr;
7590
7591 NamedDecl *ShadowedDecl = R.getFoundDecl();
7592 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7593 : nullptr;
7594}
7595
7596/// Diagnose variable or built-in function shadowing. Implements
7597/// -Wshadow.
7598///
7599/// This method is called whenever a VarDecl is added to a "useful"
7600/// scope.
7601///
7602/// \param ShadowedDecl the declaration that is shadowed by the given variable
7603/// \param R the lookup of the name
7604///
7605void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7606 const LookupResult &R) {
7607 DeclContext *NewDC = D->getDeclContext();
7608
7609 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7610 // Fields are not shadowed by variables in C++ static methods.
7611 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7612 if (MD->isStatic())
7613 return;
7614
7615 // Fields shadowed by constructor parameters are a special case. Usually
7616 // the constructor initializes the field with the parameter.
7617 if (isa<CXXConstructorDecl>(NewDC))
7618 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7619 // Remember that this was shadowed so we can either warn about its
7620 // modification or its existence depending on warning settings.
7621 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7622 return;
7623 }
7624 }
7625
7626 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7627 if (shadowedVar->isExternC()) {
7628 // For shadowing external vars, make sure that we point to the global
7629 // declaration, not a locally scoped extern declaration.
7630 for (auto I : shadowedVar->redecls())
7631 if (I->isFileVarDecl()) {
7632 ShadowedDecl = I;
7633 break;
7634 }
7635 }
7636
7637 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7638
7639 unsigned WarningDiag = diag::warn_decl_shadow;
7640 SourceLocation CaptureLoc;
7641 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7642 isa<CXXMethodDecl>(NewDC)) {
7643 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7644 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7645 if (RD->getLambdaCaptureDefault() == LCD_None) {
7646 // Try to avoid warnings for lambdas with an explicit capture list.
7647 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7648 // Warn only when the lambda captures the shadowed decl explicitly.
7649 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7650 if (CaptureLoc.isInvalid())
7651 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7652 } else {
7653 // Remember that this was shadowed so we can avoid the warning if the
7654 // shadowed decl isn't captured and the warning settings allow it.
7655 cast<LambdaScopeInfo>(getCurFunction())
7656 ->ShadowingDecls.push_back(
7657 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7658 return;
7659 }
7660 }
7661
7662 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7663 // A variable can't shadow a local variable in an enclosing scope, if
7664 // they are separated by a non-capturing declaration context.
7665 for (DeclContext *ParentDC = NewDC;
7666 ParentDC && !ParentDC->Equals(OldDC);
7667 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7668 // Only block literals, captured statements, and lambda expressions
7669 // can capture; other scopes don't.
7670 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7671 !isLambdaCallOperator(ParentDC)) {
7672 return;
7673 }
7674 }
7675 }
7676 }
7677 }
7678
7679 // Only warn about certain kinds of shadowing for class members.
7680 if (NewDC && NewDC->isRecord()) {
7681 // In particular, don't warn about shadowing non-class members.
7682 if (!OldDC->isRecord())
7683 return;
7684
7685 // TODO: should we warn about static data members shadowing
7686 // static data members from base classes?
7687
7688 // TODO: don't diagnose for inaccessible shadowed members.
7689 // This is hard to do perfectly because we might friend the
7690 // shadowing context, but that's just a false negative.
7691 }
7692
7693
7694 DeclarationName Name = R.getLookupName();
7695
7696 // Emit warning and note.
7697 if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7698 return;
7699 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7700 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7701 if (!CaptureLoc.isInvalid())
7702 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7703 << Name << /*explicitly*/ 1;
7704 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7705}
7706
7707/// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7708/// when these variables are captured by the lambda.
7709void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7710 for (const auto &Shadow : LSI->ShadowingDecls) {
7711 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7712 // Try to avoid the warning when the shadowed decl isn't captured.
7713 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7714 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7715 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7716 ? diag::warn_decl_shadow_uncaptured_local
7717 : diag::warn_decl_shadow)
7718 << Shadow.VD->getDeclName()
7719 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7720 if (!CaptureLoc.isInvalid())
7721 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7722 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7723 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7724 }
7725}
7726
7727/// Check -Wshadow without the advantage of a previous lookup.
7728void Sema::CheckShadow(Scope *S, VarDecl *D) {
7729 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7730 return;
7731
7732 LookupResult R(*this, D->getDeclName(), D->getLocation(),
7733 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7734 LookupName(R, S);
7735 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7736 CheckShadow(D, ShadowedDecl, R);
7737}
7738
7739/// Check if 'E', which is an expression that is about to be modified, refers
7740/// to a constructor parameter that shadows a field.
7741void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7742 // Quickly ignore expressions that can't be shadowing ctor parameters.
7743 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7744 return;
7745 E = E->IgnoreParenImpCasts();
7746 auto *DRE = dyn_cast<DeclRefExpr>(E);
7747 if (!DRE)
7748 return;
7749 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7750 auto I = ShadowingDecls.find(D);
7751 if (I == ShadowingDecls.end())
7752 return;
7753 const NamedDecl *ShadowedDecl = I->second;
7754 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7755 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7756 Diag(D->getLocation(), diag::note_var_declared_here) << D;
7757 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7758
7759 // Avoid issuing multiple warnings about the same decl.
7760 ShadowingDecls.erase(I);
7761}
7762
7763/// Check for conflict between this global or extern "C" declaration and
7764/// previous global or extern "C" declarations. This is only used in C++.
7765template<typename T>
7766static bool checkGlobalOrExternCConflict(
7767 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7768 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"")((S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""
) ? static_cast<void> (0) : __assert_fail ("S.getLangOpts().CPlusPlus && \"only C++ has extern \\\"C\\\"\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 7768, __PRETTY_FUNCTION__))
;
7769 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7770
7771 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7772 // The common case: this global doesn't conflict with any extern "C"
7773 // declaration.
7774 return false;
7775 }
7776
7777 if (Prev) {
7778 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7779 // Both the old and new declarations have C language linkage. This is a
7780 // redeclaration.
7781 Previous.clear();
7782 Previous.addDecl(Prev);
7783 return true;
7784 }
7785
7786 // This is a global, non-extern "C" declaration, and there is a previous
7787 // non-global extern "C" declaration. Diagnose if this is a variable
7788 // declaration.
7789 if (!isa<VarDecl>(ND))
7790 return false;
7791 } else {
7792 // The declaration is extern "C". Check for any declaration in the
7793 // translation unit which might conflict.
7794 if (IsGlobal) {
7795 // We have already performed the lookup into the translation unit.
7796 IsGlobal = false;
7797 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7798 I != E; ++I) {
7799 if (isa<VarDecl>(*I)) {
7800 Prev = *I;
7801 break;
7802 }
7803 }
7804 } else {
7805 DeclContext::lookup_result R =
7806 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7807 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7808 I != E; ++I) {
7809 if (isa<VarDecl>(*I)) {
7810 Prev = *I;
7811 break;
7812 }
7813 // FIXME: If we have any other entity with this name in global scope,
7814 // the declaration is ill-formed, but that is a defect: it breaks the
7815 // 'stat' hack, for instance. Only variables can have mangled name
7816 // clashes with extern "C" declarations, so only they deserve a
7817 // diagnostic.
7818 }
7819 }
7820
7821 if (!Prev)
7822 return false;
7823 }
7824
7825 // Use the first declaration's location to ensure we point at something which
7826 // is lexically inside an extern "C" linkage-spec.
7827 assert(Prev && "should have found a previous declaration to diagnose")((Prev && "should have found a previous declaration to diagnose"
) ? static_cast<void> (0) : __assert_fail ("Prev && \"should have found a previous declaration to diagnose\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 7827, __PRETTY_FUNCTION__))
;
7828 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7829 Prev = FD->getFirstDecl();
7830 else
7831 Prev = cast<VarDecl>(Prev)->getFirstDecl();
7832
7833 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7834 << IsGlobal << ND;
7835 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7836 << IsGlobal;
7837 return false;
7838}
7839
7840/// Apply special rules for handling extern "C" declarations. Returns \c true
7841/// if we have found that this is a redeclaration of some prior entity.
7842///
7843/// Per C++ [dcl.link]p6:
7844/// Two declarations [for a function or variable] with C language linkage
7845/// with the same name that appear in different scopes refer to the same
7846/// [entity]. An entity with C language linkage shall not be declared with
7847/// the same name as an entity in global scope.
7848template<typename T>
7849static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7850 LookupResult &Previous) {
7851 if (!S.getLangOpts().CPlusPlus) {
7852 // In C, when declaring a global variable, look for a corresponding 'extern'
7853 // variable declared in function scope. We don't need this in C++, because
7854 // we find local extern decls in the surrounding file-scope DeclContext.
7855 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7856 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7857 Previous.clear();
7858 Previous.addDecl(Prev);
7859 return true;
7860 }
7861 }
7862 return false;
7863 }
7864
7865 // A declaration in the translation unit can conflict with an extern "C"
7866 // declaration.
7867 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7868 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7869
7870 // An extern "C" declaration can conflict with a declaration in the
7871 // translation unit or can be a redeclaration of an extern "C" declaration
7872 // in another scope.
7873 if (isIncompleteDeclExternC(S,ND))
7874 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7875
7876 // Neither global nor extern "C": nothing to do.
7877 return false;
7878}
7879
7880void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7881 // If the decl is already known invalid, don't check it.
7882 if (NewVD->isInvalidDecl())
7883 return;
7884
7885 QualType T = NewVD->getType();
7886
7887 // Defer checking an 'auto' type until its initializer is attached.
7888 if (T->isUndeducedType())
7889 return;
7890
7891 if (NewVD->hasAttrs())
7892 CheckAlignasUnderalignment(NewVD);
7893
7894 if (T->isObjCObjectType()) {
7895 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7896 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7897 T = Context.getObjCObjectPointerType(T);
7898 NewVD->setType(T);
7899 }
7900
7901 // Emit an error if an address space was applied to decl with local storage.
7902 // This includes arrays of objects with address space qualifiers, but not
7903 // automatic variables that point to other address spaces.
7904 // ISO/IEC TR 18037 S5.1.2
7905 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7906 T.getAddressSpace() != LangAS::Default) {
7907 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7908 NewVD->setInvalidDecl();
7909 return;
7910 }
7911
7912 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7913 // scope.
7914 if (getLangOpts().OpenCLVersion == 120 &&
7915 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
7916 getLangOpts()) &&
7917 NewVD->isStaticLocal()) {
7918 Diag(NewVD->getLocation(), diag::err_static_function_scope);
7919 NewVD->setInvalidDecl();
7920 return;
7921 }
7922
7923 if (getLangOpts().OpenCL) {
7924 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7925 if (NewVD->hasAttr<BlocksAttr>()) {
7926 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7927 return;
7928 }
7929
7930 if (T->isBlockPointerType()) {
7931 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7932 // can't use 'extern' storage class.
7933 if (!T.isConstQualified()) {
7934 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7935 << 0 /*const*/;
7936 NewVD->setInvalidDecl();
7937 return;
7938 }
7939 if (NewVD->hasExternalStorage()) {
7940 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7941 NewVD->setInvalidDecl();
7942 return;
7943 }
7944 }
7945 // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
7946 // __constant address space.
7947 // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
7948 // variables inside a function can also be declared in the global
7949 // address space.
7950 // C++ for OpenCL inherits rule from OpenCL C v2.0.
7951 // FIXME: Adding local AS in C++ for OpenCL might make sense.
7952 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7953 NewVD->hasExternalStorage()) {
7954 if (!T->isSamplerT() &&
7955 !T->isDependentType() &&
7956 !(T.getAddressSpace() == LangAS::opencl_constant ||
7957 (T.getAddressSpace() == LangAS::opencl_global &&
7958 (getLangOpts().OpenCLVersion == 200 ||
7959 getLangOpts().OpenCLCPlusPlus)))) {
7960 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7961 if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
7962 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7963 << Scope << "global or constant";
7964 else
7965 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7966 << Scope << "constant";
7967 NewVD->setInvalidDecl();
7968 return;
7969 }
7970 } else {
7971 if (T.getAddressSpace() == LangAS::opencl_global) {
7972 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7973 << 1 /*is any function*/ << "global";
7974 NewVD->setInvalidDecl();
7975 return;
7976 }
7977 if (T.getAddressSpace() == LangAS::opencl_constant ||
7978 T.getAddressSpace() == LangAS::opencl_local) {
7979 FunctionDecl *FD = getCurFunctionDecl();
7980 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7981 // in functions.
7982 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7983 if (T.getAddressSpace() == LangAS::opencl_constant)
7984 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7985 << 0 /*non-kernel only*/ << "constant";
7986 else
7987 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7988 << 0 /*non-kernel only*/ << "local";
7989 NewVD->setInvalidDecl();
7990 return;
7991 }
7992 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7993 // in the outermost scope of a kernel function.
7994 if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7995 if (!getCurScope()->isFunctionScope()) {
7996 if (T.getAddressSpace() == LangAS::opencl_constant)
7997 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7998 << "constant";
7999 else
8000 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8001 << "local";
8002 NewVD->setInvalidDecl();
8003 return;
8004 }
8005 }
8006 } else if (T.getAddressSpace() != LangAS::opencl_private &&
8007 // If we are parsing a template we didn't deduce an addr
8008 // space yet.
8009 T.getAddressSpace() != LangAS::Default) {
8010 // Do not allow other address spaces on automatic variable.
8011 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8012 NewVD->setInvalidDecl();
8013 return;
8014 }
8015 }
8016 }
8017
8018 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8019 && !NewVD->hasAttr<BlocksAttr>()) {
8020 if (getLangOpts().getGC() != LangOptions::NonGC)
8021 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8022 else {
8023 assert(!getLangOpts().ObjCAutoRefCount)((!getLangOpts().ObjCAutoRefCount) ? static_cast<void> (
0) : __assert_fail ("!getLangOpts().ObjCAutoRefCount", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 8023, __PRETTY_FUNCTION__))
;
8024 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8025 }
8026 }
8027
8028 bool isVM = T->isVariablyModifiedType();
8029 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8030 NewVD->hasAttr<BlocksAttr>())
8031 setFunctionHasBranchProtectedScope();
8032
8033 if ((isVM && NewVD->hasLinkage()) ||
8034 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8035 bool SizeIsNegative;
8036 llvm::APSInt Oversized;
8037 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
8038 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8039 QualType FixedT;
8040 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
8041 FixedT = FixedTInfo->getType();
8042 else if (FixedTInfo) {
8043 // Type and type-as-written are canonically different. We need to fix up
8044 // both types separately.
8045 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8046 Oversized);
8047 }
8048 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8049 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8050 // FIXME: This won't give the correct result for
8051 // int a[10][n];
8052 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8053
8054 if (NewVD->isFileVarDecl())
8055 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8056 << SizeRange;
8057 else if (NewVD->isStaticLocal())
8058 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8059 << SizeRange;
8060 else
8061 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8062 << SizeRange;
8063 NewVD->setInvalidDecl();
8064 return;
8065 }
8066
8067 if (!FixedTInfo) {
8068 if (NewVD->isFileVarDecl())
8069 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8070 else
8071 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8072 NewVD->setInvalidDecl();
8073 return;
8074 }
8075
8076 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8077 NewVD->setType(FixedT);
8078 NewVD->setTypeSourceInfo(FixedTInfo);
8079 }
8080
8081 if (T->isVoidType()) {
8082 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8083 // of objects and functions.
8084 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8085 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8086 << T;
8087 NewVD->setInvalidDecl();
8088 return;
8089 }
8090 }
8091
8092 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8093 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8094 NewVD->setInvalidDecl();
8095 return;
8096 }
8097
8098 if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
8099 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8100 NewVD->setInvalidDecl();
8101 return;
8102 }
8103
8104 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8105 Diag(NewVD->getLocation(), diag::err_block_on_vm);
8106 NewVD->setInvalidDecl();
8107 return;
8108 }
8109
8110 if (NewVD->isConstexpr() && !T->isDependentType() &&
8111 RequireLiteralType(NewVD->getLocation(), T,
8112 diag::err_constexpr_var_non_literal)) {
8113 NewVD->setInvalidDecl();
8114 return;
8115 }
8116
8117 // PPC MMA non-pointer types are not allowed as non-local variable types.
8118 if (Context.getTargetInfo().getTriple().isPPC64() &&
8119 !NewVD->isLocalVarDecl() &&
8120 CheckPPCMMAType(T, NewVD->getLocation())) {
8121 NewVD->setInvalidDecl();
8122 return;
8123 }
8124}
8125
8126/// Perform semantic checking on a newly-created variable
8127/// declaration.
8128///
8129/// This routine performs all of the type-checking required for a
8130/// variable declaration once it has been built. It is used both to
8131/// check variables after they have been parsed and their declarators
8132/// have been translated into a declaration, and to check variables
8133/// that have been instantiated from a template.
8134///
8135/// Sets NewVD->isInvalidDecl() if an error was encountered.
8136///
8137/// Returns true if the variable declaration is a redeclaration.
8138bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8139 CheckVariableDeclarationType(NewVD);
8140
8141 // If the decl is already known invalid, don't check it.
8142 if (NewVD->isInvalidDecl())
8143 return false;
8144
8145 // If we did not find anything by this name, look for a non-visible
8146 // extern "C" declaration with the same name.
8147 if (Previous.empty() &&
8148 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8149 Previous.setShadowed();
8150
8151 if (!Previous.empty()) {
8152 MergeVarDecl(NewVD, Previous);
8153 return true;
8154 }
8155 return false;
8156}
8157
8158/// AddOverriddenMethods - See if a method overrides any in the base classes,
8159/// and if so, check that it's a valid override and remember it.
8160bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8161 llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
8162
8163 // Look for methods in base classes that this method might override.
8164 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8165 /*DetectVirtual=*/false);
8166 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8167 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8168 DeclarationName Name = MD->getDeclName();
8169
8170 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8171 // We really want to find the base class destructor here.
8172 QualType T = Context.getTypeDeclType(BaseRecord);
8173 CanQualType CT = Context.getCanonicalType(T);
8174 Name = Context.DeclarationNames.getCXXDestructorName(CT);
8175 }
8176
8177 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8178 CXXMethodDecl *BaseMD =
8179 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8180 if (!BaseMD || !BaseMD->isVirtual() ||
8181 IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8182 /*ConsiderCudaAttrs=*/true,
8183 // C++2a [class.virtual]p2 does not consider requires
8184 // clauses when overriding.
8185 /*ConsiderRequiresClauses=*/false))
8186 continue;
8187
8188 if (Overridden.insert(BaseMD).second) {
8189 MD->addOverriddenMethod(BaseMD);
8190 CheckOverridingFunctionReturnType(MD, BaseMD);
8191 CheckOverridingFunctionAttributes(MD, BaseMD);
8192 CheckOverridingFunctionExceptionSpec(MD, BaseMD);
8193 CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
8194 }
8195
8196 // A method can only override one function from each base class. We
8197 // don't track indirectly overridden methods from bases of bases.
8198 return true;
8199 }
8200
8201 return false;
8202 };
8203
8204 DC->lookupInBases(VisitBase, Paths);
8205 return !Overridden.empty();
8206}
8207
8208namespace {
8209 // Struct for holding all of the extra arguments needed by
8210 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8211 struct ActOnFDArgs {
8212 Scope *S;
8213 Declarator &D;
8214 MultiTemplateParamsArg TemplateParamLists;
8215 bool AddToScope;
8216 };
8217} // end anonymous namespace
8218
8219namespace {
8220
8221// Callback to only accept typo corrections that have a non-zero edit distance.
8222// Also only accept corrections that have the same parent decl.
8223class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8224 public:
8225 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8226 CXXRecordDecl *Parent)
8227 : Context(Context), OriginalFD(TypoFD),
8228 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8229
8230 bool ValidateCandidate(const TypoCorrection &candidate) override {
8231 if (candidate.getEditDistance() == 0)
8232 return false;
8233
8234 SmallVector<unsigned, 1> MismatchedParams;
8235 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8236 CDeclEnd = candidate.end();
8237 CDecl != CDeclEnd; ++CDecl) {
8238 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8239
8240 if (FD && !FD->hasBody() &&
8241 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8242 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8243 CXXRecordDecl *Parent = MD->getParent();
8244 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8245 return true;
8246 } else if (!ExpectedParent) {
8247 return true;
8248 }
8249 }
8250 }
8251
8252 return false;
8253 }
8254
8255 std::unique_ptr<CorrectionCandidateCallback> clone() override {
8256 return std::make_unique<DifferentNameValidatorCCC>(*this);
8257 }
8258
8259 private:
8260 ASTContext &Context;
8261 FunctionDecl *OriginalFD;
8262 CXXRecordDecl *ExpectedParent;
8263};
8264
8265} // end anonymous namespace
8266
8267void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8268 TypoCorrectedFunctionDefinitions.insert(F);
8269}
8270
8271/// Generate diagnostics for an invalid function redeclaration.
8272///
8273/// This routine handles generating the diagnostic messages for an invalid
8274/// function redeclaration, including finding possible similar declarations
8275/// or performing typo correction if there are no previous declarations with
8276/// the same name.
8277///
8278/// Returns a NamedDecl iff typo correction was performed and substituting in
8279/// the new declaration name does not cause new errors.
8280static NamedDecl *DiagnoseInvalidRedeclaration(
8281 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8282 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8283 DeclarationName Name = NewFD->getDeclName();
8284 DeclContext *NewDC = NewFD->getDeclContext();
8285 SmallVector<unsigned, 1> MismatchedParams;
8286 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8287 TypoCorrection Correction;
8288 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8289 unsigned DiagMsg =
8290 IsLocalFriend ? diag::err_no_matching_local_friend :
8291 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8292 diag::err_member_decl_does_not_match;
8293 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8294 IsLocalFriend ? Sema::LookupLocalFriendName
8295 : Sema::LookupOrdinaryName,
8296 Sema::ForVisibleRedeclaration);
8297
8298 NewFD->setInvalidDecl();
8299 if (IsLocalFriend)
8300 SemaRef.LookupName(Prev, S);
8301 else
8302 SemaRef.LookupQualifiedName(Prev, NewDC);
8303 assert(!Prev.isAmbiguous() &&((!Prev.isAmbiguous() && "Cannot have an ambiguity in previous-declaration lookup"
) ? static_cast<void> (0) : __assert_fail ("!Prev.isAmbiguous() && \"Cannot have an ambiguity in previous-declaration lookup\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 8304, __PRETTY_FUNCTION__))
8304 "Cannot have an ambiguity in previous-declaration lookup")((!Prev.isAmbiguous() && "Cannot have an ambiguity in previous-declaration lookup"
) ? static_cast<void> (0) : __assert_fail ("!Prev.isAmbiguous() && \"Cannot have an ambiguity in previous-declaration lookup\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 8304, __PRETTY_FUNCTION__))
;
8305 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8306 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8307 MD ? MD->getParent() : nullptr);
8308 if (!Prev.empty()) {
8309 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8310 Func != FuncEnd; ++Func) {
8311 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8312 if (FD &&
8313 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8314 // Add 1 to the index so that 0 can mean the mismatch didn't
8315 // involve a parameter
8316 unsigned ParamNum =
8317 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8318 NearMatches.push_back(std::make_pair(FD, ParamNum));
8319 }
8320 }
8321 // If the qualified name lookup yielded nothing, try typo correction
8322 } else if ((Correction = SemaRef.CorrectTypo(
8323 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8324 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8325 IsLocalFriend ? nullptr : NewDC))) {
8326 // Set up everything for the call to ActOnFunctionDeclarator
8327 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8328 ExtraArgs.D.getIdentifierLoc());
8329 Previous.clear();
8330 Previous.setLookupName(Correction.getCorrection());
8331 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8332 CDeclEnd = Correction.end();
8333 CDecl != CDeclEnd; ++CDecl) {
8334 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8335 if (FD && !FD->hasBody() &&
8336 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8337 Previous.addDecl(FD);
8338 }
8339 }
8340 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8341
8342 NamedDecl *Result;
8343 // Retry building the function declaration with the new previous
8344 // declarations, and with errors suppressed.
8345 {
8346 // Trap errors.
8347 Sema::SFINAETrap Trap(SemaRef);
8348
8349 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8350 // pieces need to verify the typo-corrected C++ declaration and hopefully
8351 // eliminate the need for the parameter pack ExtraArgs.
8352 Result = SemaRef.ActOnFunctionDeclarator(
8353 ExtraArgs.S, ExtraArgs.D,
8354 Correction.getCorrectionDecl()->getDeclContext(),
8355 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8356 ExtraArgs.AddToScope);
8357
8358 if (Trap.hasErrorOccurred())
8359 Result = nullptr;
8360 }
8361
8362 if (Result) {
8363 // Determine which correction we picked.
8364 Decl *Canonical = Result->getCanonicalDecl();
8365 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8366 I != E; ++I)
8367 if ((*I)->getCanonicalDecl() == Canonical)
8368 Correction.setCorrectionDecl(*I);
8369
8370 // Let Sema know about the correction.
8371 SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8372 SemaRef.diagnoseTypo(
8373 Correction,
8374 SemaRef.PDiag(IsLocalFriend
8375 ? diag::err_no_matching_local_friend_suggest
8376 : diag::err_member_decl_does_not_match_suggest)
8377 << Name << NewDC << IsDefinition);
8378 return Result;
8379 }
8380
8381 // Pretend the typo correction never occurred
8382 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8383 ExtraArgs.D.getIdentifierLoc());
8384 ExtraArgs.D.setRedeclaration(wasRedeclaration);
8385 Previous.clear();
8386 Previous.setLookupName(Name);
8387 }
8388
8389 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8390 << Name << NewDC << IsDefinition << NewFD->getLocation();
8391
8392 bool NewFDisConst = false;
8393 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8394 NewFDisConst = NewMD->isConst();
8395
8396 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8397 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8398 NearMatch != NearMatchEnd; ++NearMatch) {
8399 FunctionDecl *FD = NearMatch->first;
8400 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8401 bool FDisConst = MD && MD->isConst();
8402 bool IsMember = MD || !IsLocalFriend;
8403
8404 // FIXME: These notes are poorly worded for the local friend case.
8405 if (unsigned Idx = NearMatch->second) {
8406 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8407 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8408 if (Loc.isInvalid()) Loc = FD->getLocation();
8409 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8410 : diag::note_local_decl_close_param_match)
8411 << Idx << FDParam->getType()
8412 << NewFD->getParamDecl(Idx - 1)->getType();
8413 } else if (FDisConst != NewFDisConst) {
8414 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8415 << NewFDisConst << FD->getSourceRange().getEnd();
8416 } else
8417 SemaRef.Diag(FD->getLocation(),
8418 IsMember ? diag::note_member_def_close_match
8419 : diag::note_local_decl_close_match);
8420 }
8421 return nullptr;
8422}
8423
8424static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8425 switch (D.getDeclSpec().getStorageClassSpec()) {
8426 default: llvm_unreachable("Unknown storage class!")::llvm::llvm_unreachable_internal("Unknown storage class!", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 8426)
;
8427 case DeclSpec::SCS_auto:
8428 case DeclSpec::SCS_register:
8429 case DeclSpec::SCS_mutable:
8430 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8431 diag::err_typecheck_sclass_func);
8432 D.getMutableDeclSpec().ClearStorageClassSpecs();
8433 D.setInvalidType();
8434 break;
8435 case DeclSpec::SCS_unspecified: break;
8436 case DeclSpec::SCS_extern:
8437 if (D.getDeclSpec().isExternInLinkageSpec())
8438 return SC_None;
8439 return SC_Extern;
8440 case DeclSpec::SCS_static: {
8441 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8442 // C99 6.7.1p5:
8443 // The declaration of an identifier for a function that has
8444 // block scope shall have no explicit storage-class specifier
8445 // other than extern
8446 // See also (C++ [dcl.stc]p4).
8447 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8448 diag::err_static_block_func);
8449 break;
8450 } else
8451 return SC_Static;
8452 }
8453 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8454 }
8455
8456 // No explicit storage class has already been returned
8457 return SC_None;
8458}
8459
8460static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8461 DeclContext *DC, QualType &R,
8462 TypeSourceInfo *TInfo,
8463 StorageClass SC,
8464 bool &IsVirtualOkay) {
8465 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8466 DeclarationName Name = NameInfo.getName();
8467
8468 FunctionDecl *NewFD = nullptr;
8469 bool isInline = D.getDeclSpec().isInlineSpecified();
8470
8471 if (!SemaRef.getLangOpts().CPlusPlus) {
8472 // Determine whether the function was written with a
8473 // prototype. This true when:
8474 // - there is a prototype in the declarator, or
8475 // - the type R of the function is some kind of typedef or other non-
8476 // attributed reference to a type name (which eventually refers to a
8477 // function type).
8478 bool HasPrototype =
8479 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8480 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8481
8482 NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8483 R, TInfo, SC, isInline, HasPrototype,
8484 ConstexprSpecKind::Unspecified,
8485 /*TrailingRequiresClause=*/nullptr);
8486 if (D.isInvalidType())
8487 NewFD->setInvalidDecl();
8488
8489 return NewFD;
8490 }
8491
8492 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8493
8494 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8495 if (ConstexprKind == ConstexprSpecKind::Constinit) {
8496 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8497 diag::err_constexpr_wrong_decl_kind)
8498 << static_cast<int>(ConstexprKind);
8499 ConstexprKind = ConstexprSpecKind::Unspecified;
8500 D.getMutableDeclSpec().ClearConstexprSpec();
8501 }
8502 Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8503
8504 // Check that the return type is not an abstract class type.
8505 // For record types, this is done by the AbstractClassUsageDiagnoser once
8506 // the class has been completely parsed.
8507 if (!DC->isRecord() &&
8508 SemaRef.RequireNonAbstractType(
8509 D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8510 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8511 D.setInvalidType();
8512
8513 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8514 // This is a C++ constructor declaration.
8515 assert(DC->isRecord() &&((DC->isRecord() && "Constructors can only be declared in a member context"
) ? static_cast<void> (0) : __assert_fail ("DC->isRecord() && \"Constructors can only be declared in a member context\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 8516, __PRETTY_FUNCTION__))
8516 "Constructors can only be declared in a member context")((DC->isRecord() && "Constructors can only be declared in a member context"
) ? static_cast<void> (0) : __assert_fail ("DC->isRecord() && \"Constructors can only be declared in a member context\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 8516, __PRETTY_FUNCTION__))
;
8517
8518 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8519 return CXXConstructorDecl::Create(
8520 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8521 TInfo, ExplicitSpecifier, isInline,
8522 /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(),
8523 TrailingRequiresClause);
8524
8525 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8526 // This is a C++ destructor declaration.
8527 if (DC->isRecord()) {
8528 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8529 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8530 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8531 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8532 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8533 TrailingRequiresClause);
8534
8535 // If the destructor needs an implicit exception specification, set it
8536 // now. FIXME: It'd be nice to be able to create the right type to start
8537 // with, but the type needs to reference the destructor declaration.
8538 if (SemaRef.getLangOpts().CPlusPlus11)
8539 SemaRef.AdjustDestructorExceptionSpec(NewDD);
8540
8541 IsVirtualOkay = true;
8542 return NewDD;
8543
8544 } else {
8545 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8546 D.setInvalidType();
8547
8548 // Create a FunctionDecl to satisfy the function definition parsing
8549 // code path.
8550 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8551 D.getIdentifierLoc(), Name, R, TInfo, SC,
8552 isInline,
8553 /*hasPrototype=*/true, ConstexprKind,
8554 TrailingRequiresClause);
8555 }
8556
8557 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8558 if (!DC->isRecord()) {
8559 SemaRef.Diag(D.getIdentifierLoc(),
8560 diag::err_conv_function_not_member);
8561 return nullptr;
8562 }
8563
8564 SemaRef.CheckConversionDeclarator(D, R, SC);
8565 if (D.isInvalidType())
8566 return nullptr;
8567
8568 IsVirtualOkay = true;
8569 return CXXConversionDecl::Create(
8570 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8571 TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(),
8572 TrailingRequiresClause);
8573
8574 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8575 if (TrailingRequiresClause)
8576 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8577 diag::err_trailing_requires_clause_on_deduction_guide)
8578 << TrailingRequiresClause->getSourceRange();
8579 SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8580
8581 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8582 ExplicitSpecifier, NameInfo, R, TInfo,
8583 D.getEndLoc());
8584 } else if (DC->isRecord()) {
8585 // If the name of the function is the same as the name of the record,
8586 // then this must be an invalid constructor that has a return type.
8587 // (The parser checks for a return type and makes the declarator a
8588 // constructor if it has no return type).
8589 if (Name.getAsIdentifierInfo() &&
8590 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8591 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8592 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8593 << SourceRange(D.getIdentifierLoc());
8594 return nullptr;
8595 }
8596
8597 // This is a C++ method declaration.
8598 CXXMethodDecl *Ret = CXXMethodDecl::Create(
8599 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8600 TInfo, SC, isInline, ConstexprKind, SourceLocation(),
8601 TrailingRequiresClause);
8602 IsVirtualOkay = !Ret->isStatic();
8603 return Ret;
8604 } else {
8605 bool isFriend =
8606 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8607 if (!isFriend && SemaRef.CurContext->isRecord())
8608 return nullptr;
8609
8610 // Determine whether the function was written with a
8611 // prototype. This true when:
8612 // - we're in C++ (where every function has a prototype),
8613 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8614 R, TInfo, SC, isInline, true /*HasPrototype*/,
8615 ConstexprKind, TrailingRequiresClause);
8616 }
8617}
8618
8619enum OpenCLParamType {
8620 ValidKernelParam,
8621 PtrPtrKernelParam,
8622 PtrKernelParam,
8623 InvalidAddrSpacePtrKernelParam,
8624 InvalidKernelParam,
8625 RecordKernelParam
8626};
8627
8628static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8629 // Size dependent types are just typedefs to normal integer types
8630 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8631 // integers other than by their names.
8632 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8633
8634 // Remove typedefs one by one until we reach a typedef
8635 // for a size dependent type.
8636 QualType DesugaredTy = Ty;
8637 do {
8638 ArrayRef<StringRef> Names(SizeTypeNames);
8639 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8640 if (Names.end() != Match)
8641 return true;
8642
8643 Ty = DesugaredTy;
8644 DesugaredTy = Ty.getSingleStepDesugaredType(C);
8645 } while (DesugaredTy != Ty);
8646
8647 return false;
8648}
8649
8650static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8651 if (PT->isPointerType()) {
8652 QualType PointeeType = PT->getPointeeType();
8653 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8654 PointeeType.getAddressSpace() == LangAS::opencl_private ||
8655 PointeeType.getAddressSpace() == LangAS::Default)
8656 return InvalidAddrSpacePtrKernelParam;
8657
8658 if (PointeeType->isPointerType()) {
8659 // This is a pointer to pointer parameter.
8660 // Recursively check inner type.
8661 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
8662 if (ParamKind == InvalidAddrSpacePtrKernelParam ||
8663 ParamKind == InvalidKernelParam)
8664 return ParamKind;
8665
8666 return PtrPtrKernelParam;
8667 }
8668 return PtrKernelParam;
8669 }
8670
8671 // OpenCL v1.2 s6.9.k:
8672 // Arguments to kernel functions in a program cannot be declared with the
8673 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8674 // uintptr_t or a struct and/or union that contain fields declared to be one
8675 // of these built-in scalar types.
8676 if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8677 return InvalidKernelParam;
8678
8679 if (PT->isImageType())
8680 return PtrKernelParam;
8681
8682 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8683 return InvalidKernelParam;
8684
8685 // OpenCL extension spec v1.2 s9.5:
8686 // This extension adds support for half scalar and vector types as built-in
8687 // types that can be used for arithmetic operations, conversions etc.
8688 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
8689 PT->isHalfType())
8690 return InvalidKernelParam;
8691
8692 if (PT->isRecordType())
8693 return RecordKernelParam;
8694
8695 // Look into an array argument to check if it has a forbidden type.
8696 if (PT->isArrayType()) {
8697 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8698 // Call ourself to check an underlying type of an array. Since the
8699 // getPointeeOrArrayElementType returns an innermost type which is not an
8700 // array, this recursive call only happens once.
8701 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8702 }
8703
8704 return ValidKernelParam;
8705}
8706
8707static void checkIsValidOpenCLKernelParameter(
8708 Sema &S,
8709 Declarator &D,
8710 ParmVarDecl *Param,
8711 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8712 QualType PT = Param->getType();
8713
8714 // Cache the valid types we encounter to avoid rechecking structs that are
8715 // used again
8716 if (ValidTypes.count(PT.getTypePtr()))
8717 return;
8718
8719 switch (getOpenCLKernelParameterType(S, PT)) {
8720 case PtrPtrKernelParam:
8721 // OpenCL v3.0 s6.11.a:
8722 // A kernel function argument cannot be declared as a pointer to a pointer
8723 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
8724 if (S.getLangOpts().OpenCLVersion < 120 &&
8725 !S.getLangOpts().OpenCLCPlusPlus) {
8726 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8727 D.setInvalidType();
8728 return;
8729 }
8730
8731 ValidTypes.insert(PT.getTypePtr());
8732 return;
8733
8734 case InvalidAddrSpacePtrKernelParam:
8735 // OpenCL v1.0 s6.5:
8736 // __kernel function arguments declared to be a pointer of a type can point
8737 // to one of the following address spaces only : __global, __local or
8738 // __constant.
8739 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8740 D.setInvalidType();
8741 return;
8742
8743 // OpenCL v1.2 s6.9.k:
8744 // Arguments to kernel functions in a program cannot be declared with the
8745 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8746 // uintptr_t or a struct and/or union that contain fields declared to be
8747 // one of these built-in scalar types.
8748
8749 case InvalidKernelParam:
8750 // OpenCL v1.2 s6.8 n:
8751 // A kernel function argument cannot be declared
8752 // of event_t type.
8753 // Do not diagnose half type since it is diagnosed as invalid argument
8754 // type for any function elsewhere.
8755 if (!PT->isHalfType()) {
8756 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8757
8758 // Explain what typedefs are involved.
8759 const TypedefType *Typedef = nullptr;
8760 while ((Typedef = PT->getAs<TypedefType>())) {
8761 SourceLocation Loc = Typedef->getDecl()->getLocation();
8762 // SourceLocation may be invalid for a built-in type.
8763 if (Loc.isValid())
8764 S.Diag(Loc, diag::note_entity_declared_at) << PT;
8765 PT = Typedef->desugar();
8766 }
8767 }
8768
8769 D.setInvalidType();
8770 return;
8771
8772 case PtrKernelParam:
8773 case ValidKernelParam:
8774 ValidTypes.insert(PT.getTypePtr());
8775 return;
8776
8777 case RecordKernelParam:
8778 break;
8779 }
8780
8781 // Track nested structs we will inspect
8782 SmallVector<const Decl *, 4> VisitStack;
8783
8784 // Track where we are in the nested structs. Items will migrate from
8785 // VisitStack to HistoryStack as we do the DFS for bad field.
8786 SmallVector<const FieldDecl *, 4> HistoryStack;
8787 HistoryStack.push_back(nullptr);
8788
8789 // At this point we already handled everything except of a RecordType or
8790 // an ArrayType of a RecordType.
8791 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.")(((PT->isArrayType() || PT->isRecordType()) && "Unexpected type."
) ? static_cast<void> (0) : __assert_fail ("(PT->isArrayType() || PT->isRecordType()) && \"Unexpected type.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 8791, __PRETTY_FUNCTION__))
;
8792 const RecordType *RecTy =
8793 PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8794 const RecordDecl *OrigRecDecl = RecTy->getDecl();
8795
8796 VisitStack.push_back(RecTy->getDecl());
8797 assert(VisitStack.back() && "First decl null?")((VisitStack.back() && "First decl null?") ? static_cast
<void> (0) : __assert_fail ("VisitStack.back() && \"First decl null?\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 8797, __PRETTY_FUNCTION__))
;
8798
8799 do {
8800 const Decl *Next = VisitStack.pop_back_val();
8801 if (!Next) {
8802 assert(!HistoryStack.empty())((!HistoryStack.empty()) ? static_cast<void> (0) : __assert_fail
("!HistoryStack.empty()", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 8802, __PRETTY_FUNCTION__))
;
8803 // Found a marker, we have gone up a level
8804 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8805 ValidTypes.insert(Hist->getType().getTypePtr());
8806
8807 continue;
8808 }
8809
8810 // Adds everything except the original parameter declaration (which is not a
8811 // field itself) to the history stack.
8812 const RecordDecl *RD;
8813 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8814 HistoryStack.push_back(Field);
8815
8816 QualType FieldTy = Field->getType();
8817 // Other field types (known to be valid or invalid) are handled while we
8818 // walk around RecordDecl::fields().
8819 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&(((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
"Unexpected type.") ? static_cast<void> (0) : __assert_fail
("(FieldTy->isArrayType() || FieldTy->isRecordType()) && \"Unexpected type.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 8820, __PRETTY_FUNCTION__))
8820 "Unexpected type.")(((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
"Unexpected type.") ? static_cast<void> (0) : __assert_fail
("(FieldTy->isArrayType() || FieldTy->isRecordType()) && \"Unexpected type.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 8820, __PRETTY_FUNCTION__))
;
8821 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8822
8823 RD = FieldRecTy->castAs<RecordType>()->getDecl();
8824 } else {
8825 RD = cast<RecordDecl>(Next);
8826 }
8827
8828 // Add a null marker so we know when we've gone back up a level
8829 VisitStack.push_back(nullptr);
8830
8831 for (const auto *FD : RD->fields()) {
8832 QualType QT = FD->getType();
8833
8834 if (ValidTypes.count(QT.getTypePtr()))
8835 continue;
8836
8837 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8838 if (ParamType == ValidKernelParam)
8839 continue;
8840
8841 if (ParamType == RecordKernelParam) {
8842 VisitStack.push_back(FD);
8843 continue;
8844 }
8845
8846 // OpenCL v1.2 s6.9.p:
8847 // Arguments to kernel functions that are declared to be a struct or union
8848 // do not allow OpenCL objects to be passed as elements of the struct or
8849 // union.
8850 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8851 ParamType == InvalidAddrSpacePtrKernelParam) {
8852 S.Diag(Param->getLocation(),
8853 diag::err_record_with_pointers_kernel_param)
8854 << PT->isUnionType()
8855 << PT;
8856 } else {
8857 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8858 }
8859
8860 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8861 << OrigRecDecl->getDeclName();
8862
8863 // We have an error, now let's go back up through history and show where
8864 // the offending field came from
8865 for (ArrayRef<const FieldDecl *>::const_iterator
8866 I = HistoryStack.begin() + 1,
8867 E = HistoryStack.end();
8868 I != E; ++I) {
8869 const FieldDecl *OuterField = *I;
8870 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8871 << OuterField->getType();
8872 }
8873
8874 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8875 << QT->isPointerType()
8876 << QT;
8877 D.setInvalidType();
8878 return;
8879 }
8880 } while (!VisitStack.empty());
8881}
8882
8883/// Find the DeclContext in which a tag is implicitly declared if we see an
8884/// elaborated type specifier in the specified context, and lookup finds
8885/// nothing.
8886static DeclContext *getTagInjectionContext(DeclContext *DC) {
8887 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8888 DC = DC->getParent();
8889 return DC;
8890}
8891
8892/// Find the Scope in which a tag is implicitly declared if we see an
8893/// elaborated type specifier in the specified context, and lookup finds
8894/// nothing.
8895static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8896 while (S->isClassScope() ||
8897 (LangOpts.CPlusPlus &&
8898 S->isFunctionPrototypeScope()) ||
8899 ((S->getFlags() & Scope::DeclScope) == 0) ||
8900 (S->getEntity() && S->getEntity()->isTransparentContext()))
8901 S = S->getParent();
8902 return S;
8903}
8904
8905NamedDecl*
8906Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8907 TypeSourceInfo *TInfo, LookupResult &Previous,
8908 MultiTemplateParamsArg TemplateParamListsRef,
8909 bool &AddToScope) {
8910 QualType R = TInfo->getType();
8911
8912 assert(R->isFunctionType())((R->isFunctionType()) ? static_cast<void> (0) : __assert_fail
("R->isFunctionType()", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 8912, __PRETTY_FUNCTION__))
;
8913 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
8914 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
8915
8916 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
8917 for (TemplateParameterList *TPL : TemplateParamListsRef)
8918 TemplateParamLists.push_back(TPL);
8919 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
8920 if (!TemplateParamLists.empty() &&
8921 Invented->getDepth() == TemplateParamLists.back()->getDepth())
8922 TemplateParamLists.back() = Invented;
8923 else
8924 TemplateParamLists.push_back(Invented);
8925 }
8926
8927 // TODO: consider using NameInfo for diagnostic.
8928 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8929 DeclarationName Name = NameInfo.getName();
8930 StorageClass SC = getFunctionStorageClass(*this, D);
8931
8932 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8933 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8934 diag::err_invalid_thread)
8935 << DeclSpec::getSpecifierName(TSCS);
8936
8937 if (D.isFirstDeclarationOfMember())
8938 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8939 D.getIdentifierLoc());
8940
8941 bool isFriend = false;
8942 FunctionTemplateDecl *FunctionTemplate = nullptr;
8943 bool isMemberSpecialization = false;
8944 bool isFunctionTemplateSpecialization = false;
8945
8946 bool isDependentClassScopeExplicitSpecialization = false;
8947 bool HasExplicitTemplateArgs = false;
8948 TemplateArgumentListInfo TemplateArgs;
8949
8950 bool isVirtualOkay = false;
8951
8952 DeclContext *OriginalDC = DC;
8953 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8954
8955 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8956 isVirtualOkay);
8957 if (!NewFD) return nullptr;
8958
8959 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8960 NewFD->setTopLevelDeclInObjCContainer();
8961
8962 // Set the lexical context. If this is a function-scope declaration, or has a
8963 // C++ scope specifier, or is the object of a friend declaration, the lexical
8964 // context will be different from the semantic context.
8965 NewFD->setLexicalDeclContext(CurContext);
8966
8967 if (IsLocalExternDecl)
8968 NewFD->setLocalExternDecl();
8969
8970 if (getLangOpts().CPlusPlus) {
8971 bool isInline = D.getDeclSpec().isInlineSpecified();
8972 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8973 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
8974 isFriend = D.getDeclSpec().isFriendSpecified();
8975 if (isFriend && !isInline && D.isFunctionDefinition()) {
8976 // C++ [class.friend]p5
8977 // A function can be defined in a friend declaration of a
8978 // class . . . . Such a function is implicitly inline.
8979 NewFD->setImplicitlyInline();
8980 }
8981
8982 // If this is a method defined in an __interface, and is not a constructor
8983 // or an overloaded operator, then set the pure flag (isVirtual will already
8984 // return true).
8985 if (const CXXRecordDecl *Parent =
8986 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8987 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8988 NewFD->setPure(true);
8989
8990 // C++ [class.union]p2
8991 // A union can have member functions, but not virtual functions.
8992 if (isVirtual && Parent->isUnion())
8993 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8994 }
8995
8996 SetNestedNameSpecifier(*this, NewFD, D);
8997 isMemberSpecialization = false;
8998 isFunctionTemplateSpecialization = false;
8999 if (D.isInvalidType())
9000 NewFD->setInvalidDecl();
9001
9002 // Match up the template parameter lists with the scope specifier, then
9003 // determine whether we have a template or a template specialization.
9004 bool Invalid = false;
9005 TemplateParameterList *TemplateParams =
9006 MatchTemplateParametersToScopeSpecifier(
9007 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
9008 D.getCXXScopeSpec(),
9009 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
9010 ? D.getName().TemplateId
9011 : nullptr,
9012 TemplateParamLists, isFriend, isMemberSpecialization,
9013 Invalid);
9014 if (TemplateParams) {
9015 // Check that we can declare a template here.
9016 if (CheckTemplateDeclScope(S, TemplateParams))
9017 NewFD->setInvalidDecl();
9018
9019 if (TemplateParams->size() > 0) {
9020 // This is a function template
9021
9022 // A destructor cannot be a template.
9023 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9024 Diag(NewFD->getLocation(), diag::err_destructor_template);
9025 NewFD->setInvalidDecl();
9026 }
9027
9028 // If we're adding a template to a dependent context, we may need to
9029 // rebuilding some of the types used within the template parameter list,
9030 // now that we know what the current instantiation is.
9031 if (DC->isDependentContext()) {
9032 ContextRAII SavedContext(*this, DC);
9033 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
9034 Invalid = true;
9035 }
9036
9037 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
9038 NewFD->getLocation(),
9039 Name, TemplateParams,
9040 NewFD);
9041 FunctionTemplate->setLexicalDeclContext(CurContext);
9042 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
9043
9044 // For source fidelity, store the other template param lists.
9045 if (TemplateParamLists.size() > 1) {
9046 NewFD->setTemplateParameterListsInfo(Context,
9047 ArrayRef<TemplateParameterList *>(TemplateParamLists)
9048 .drop_back(1));
9049 }
9050 } else {
9051 // This is a function template specialization.
9052 isFunctionTemplateSpecialization = true;
9053 // For source fidelity, store all the template param lists.
9054 if (TemplateParamLists.size() > 0)
9055 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9056
9057 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9058 if (isFriend) {
9059 // We want to remove the "template<>", found here.
9060 SourceRange RemoveRange = TemplateParams->getSourceRange();
9061
9062 // If we remove the template<> and the name is not a
9063 // template-id, we're actually silently creating a problem:
9064 // the friend declaration will refer to an untemplated decl,
9065 // and clearly the user wants a template specialization. So
9066 // we need to insert '<>' after the name.
9067 SourceLocation InsertLoc;
9068 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9069 InsertLoc = D.getName().getSourceRange().getEnd();
9070 InsertLoc = getLocForEndOfToken(InsertLoc);
9071 }
9072
9073 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9074 << Name << RemoveRange
9075 << FixItHint::CreateRemoval(RemoveRange)
9076 << FixItHint::CreateInsertion(InsertLoc, "<>");
9077 }
9078 }
9079 } else {
9080 // Check that we can declare a template here.
9081 if (!TemplateParamLists.empty() && isMemberSpecialization &&
9082 CheckTemplateDeclScope(S, TemplateParamLists.back()))
9083 NewFD->setInvalidDecl();
9084
9085 // All template param lists were matched against the scope specifier:
9086 // this is NOT (an explicit specialization of) a template.
9087 if (TemplateParamLists.size() > 0)
9088 // For source fidelity, store all the template param lists.
9089 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9090 }
9091
9092 if (Invalid) {
9093 NewFD->setInvalidDecl();
9094 if (FunctionTemplate)
9095 FunctionTemplate->setInvalidDecl();
9096 }
9097
9098 // C++ [dcl.fct.spec]p5:
9099 // The virtual specifier shall only be used in declarations of
9100 // nonstatic class member functions that appear within a
9101 // member-specification of a class declaration; see 10.3.
9102 //
9103 if (isVirtual && !NewFD->isInvalidDecl()) {
9104 if (!isVirtualOkay) {
9105 Diag(D.getDeclSpec().getVirtualSpecLoc(),
9106 diag::err_virtual_non_function);
9107 } else if (!CurContext->isRecord()) {
9108 // 'virtual' was specified outside of the class.
9109 Diag(D.getDeclSpec().getVirtualSpecLoc(),
9110 diag::err_virtual_out_of_class)
9111 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9112 } else if (NewFD->getDescribedFunctionTemplate()) {
9113 // C++ [temp.mem]p3:
9114 // A member function template shall not be virtual.
9115 Diag(D.getDeclSpec().getVirtualSpecLoc(),
9116 diag::err_virtual_member_function_template)
9117 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9118 } else {
9119 // Okay: Add virtual to the method.
9120 NewFD->setVirtualAsWritten(true);
9121 }
9122
9123 if (getLangOpts().CPlusPlus14 &&
9124 NewFD->getReturnType()->isUndeducedType())
9125 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9126 }
9127
9128 if (getLangOpts().CPlusPlus14 &&
9129 (NewFD->isDependentContext() ||
9130 (isFriend && CurContext->isDependentContext())) &&
9131 NewFD->getReturnType()->isUndeducedType()) {
9132 // If the function template is referenced directly (for instance, as a
9133 // member of the current instantiation), pretend it has a dependent type.
9134 // This is not really justified by the standard, but is the only sane
9135 // thing to do.
9136 // FIXME: For a friend function, we have not marked the function as being
9137 // a friend yet, so 'isDependentContext' on the FD doesn't work.
9138 const FunctionProtoType *FPT =
9139 NewFD->getType()->castAs<FunctionProtoType>();
9140 QualType Result =
9141 SubstAutoType(FPT->getReturnType(), Context.DependentTy);
9142 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9143 FPT->getExtProtoInfo()));
9144 }
9145
9146 // C++ [dcl.fct.spec]p3:
9147 // The inline specifier shall not appear on a block scope function
9148 // declaration.
9149 if (isInline && !NewFD->isInvalidDecl()) {
9150 if (CurContext->isFunctionOrMethod()) {
9151 // 'inline' is not allowed on block scope function declaration.
9152 Diag(D.getDeclSpec().getInlineSpecLoc(),
9153 diag::err_inline_declaration_block_scope) << Name
9154 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9155 }
9156 }
9157
9158 // C++ [dcl.fct.spec]p6:
9159 // The explicit specifier shall be used only in the declaration of a
9160 // constructor or conversion function within its class definition;
9161 // see 12.3.1 and 12.3.2.
9162 if (hasExplicit && !NewFD->isInvalidDecl() &&
9163 !isa<CXXDeductionGuideDecl>(NewFD)) {
9164 if (!CurContext->isRecord()) {
9165 // 'explicit' was specified outside of the class.
9166 Diag(D.getDeclSpec().getExplicitSpecLoc(),
9167 diag::err_explicit_out_of_class)
9168 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9169 } else if (!isa<CXXConstructorDecl>(NewFD) &&
9170 !isa<CXXConversionDecl>(NewFD)) {
9171 // 'explicit' was specified on a function that wasn't a constructor
9172 // or conversion function.
9173 Diag(D.getDeclSpec().getExplicitSpecLoc(),
9174 diag::err_explicit_non_ctor_or_conv_function)
9175 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9176 }
9177 }
9178
9179 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9180 if (ConstexprKind != ConstexprSpecKind::Unspecified) {
9181 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9182 // are implicitly inline.
9183 NewFD->setImplicitlyInline();
9184
9185 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9186 // be either constructors or to return a literal type. Therefore,
9187 // destructors cannot be declared constexpr.
9188 if (isa<CXXDestructorDecl>(NewFD) &&
9189 (!getLangOpts().CPlusPlus20 ||
9190 ConstexprKind == ConstexprSpecKind::Consteval)) {
9191 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9192 << static_cast<int>(ConstexprKind);
9193 NewFD->setConstexprKind(getLangOpts().CPlusPlus20
9194 ? ConstexprSpecKind::Unspecified
9195 : ConstexprSpecKind::Constexpr);
9196 }
9197 // C++20 [dcl.constexpr]p2: An allocation function, or a
9198 // deallocation function shall not be declared with the consteval
9199 // specifier.
9200 if (ConstexprKind == ConstexprSpecKind::Consteval &&
9201 (NewFD->getOverloadedOperator() == OO_New ||
9202 NewFD->getOverloadedOperator() == OO_Array_New ||
9203 NewFD->getOverloadedOperator() == OO_Delete ||
9204 NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9205 Diag(D.getDeclSpec().getConstexprSpecLoc(),
9206 diag::err_invalid_consteval_decl_kind)
9207 << NewFD;
9208 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
9209 }
9210 }
9211
9212 // If __module_private__ was specified, mark the function accordingly.
9213 if (D.getDeclSpec().isModulePrivateSpecified()) {
9214 if (isFunctionTemplateSpecialization) {
9215 SourceLocation ModulePrivateLoc
9216 = D.getDeclSpec().getModulePrivateSpecLoc();
9217 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9218 << 0
9219 << FixItHint::CreateRemoval(ModulePrivateLoc);
9220 } else {
9221 NewFD->setModulePrivate();
9222 if (FunctionTemplate)
9223 FunctionTemplate->setModulePrivate();
9224 }
9225 }
9226
9227 if (isFriend) {
9228 if (FunctionTemplate) {
9229 FunctionTemplate->setObjectOfFriendDecl();
9230 FunctionTemplate->setAccess(AS_public);
9231 }
9232 NewFD->setObjectOfFriendDecl();
9233 NewFD->setAccess(AS_public);
9234 }
9235
9236 // If a function is defined as defaulted or deleted, mark it as such now.
9237 // We'll do the relevant checks on defaulted / deleted functions later.
9238 switch (D.getFunctionDefinitionKind()) {
9239 case FunctionDefinitionKind::Declaration:
9240 case FunctionDefinitionKind::Definition:
9241 break;
9242
9243 case FunctionDefinitionKind::Defaulted:
9244 NewFD->setDefaulted();
9245 break;
9246
9247 case FunctionDefinitionKind::Deleted:
9248 NewFD->setDeletedAsWritten();
9249 break;
9250 }
9251
9252 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9253 D.isFunctionDefinition()) {
9254 // C++ [class.mfct]p2:
9255 // A member function may be defined (8.4) in its class definition, in
9256 // which case it is an inline member function (7.1.2)
9257 NewFD->setImplicitlyInline();
9258 }
9259
9260 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9261 !CurContext->isRecord()) {
9262 // C++ [class.static]p1:
9263 // A data or function member of a class may be declared static
9264 // in a class definition, in which case it is a static member of
9265 // the class.
9266
9267 // Complain about the 'static' specifier if it's on an out-of-line
9268 // member function definition.
9269
9270 // MSVC permits the use of a 'static' storage specifier on an out-of-line
9271 // member function template declaration and class member template
9272 // declaration (MSVC versions before 2015), warn about this.
9273 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9274 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9275 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9276 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9277 ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9278 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9279 }
9280
9281 // C++11 [except.spec]p15:
9282 // A deallocation function with no exception-specification is treated
9283 // as if it were specified with noexcept(true).
9284 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9285 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9286 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9287 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9288 NewFD->setType(Context.getFunctionType(
9289 FPT->getReturnType(), FPT->getParamTypes(),
9290 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9291 }
9292
9293 // Filter out previous declarations that don't match the scope.
9294 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9295 D.getCXXScopeSpec().isNotEmpty() ||
9296 isMemberSpecialization ||
9297 isFunctionTemplateSpecialization);
9298
9299 // Handle GNU asm-label extension (encoded as an attribute).
9300 if (Expr *E = (Expr*) D.getAsmLabel()) {
9301 // The parser guarantees this is a string.
9302 StringLiteral *SE = cast<StringLiteral>(E);
9303 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9304 /*IsLiteralLabel=*/true,
9305 SE->getStrTokenLoc(0)));
9306 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9307 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9308 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9309 if (I != ExtnameUndeclaredIdentifiers.end()) {
9310 if (isDeclExternC(NewFD)) {
9311 NewFD->addAttr(I->second);
9312 ExtnameUndeclaredIdentifiers.erase(I);
9313 } else
9314 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9315 << /*Variable*/0 << NewFD;
9316 }
9317 }
9318
9319 // Copy the parameter declarations from the declarator D to the function
9320 // declaration NewFD, if they are available. First scavenge them into Params.
9321 SmallVector<ParmVarDecl*, 16> Params;
9322 unsigned FTIIdx;
9323 if (D.isFunctionDeclarator(FTIIdx)) {
9324 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9325
9326 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9327 // function that takes no arguments, not a function that takes a
9328 // single void argument.
9329 // We let through "const void" here because Sema::GetTypeForDeclarator
9330 // already checks for that case.
9331 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9332 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9333 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9334 assert(Param->getDeclContext() != NewFD && "Was set before ?")((Param->getDeclContext() != NewFD && "Was set before ?"
) ? static_cast<void> (0) : __assert_fail ("Param->getDeclContext() != NewFD && \"Was set before ?\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 9334, __PRETTY_FUNCTION__))
;
9335 Param->setDeclContext(NewFD);
9336 Params.push_back(Param);
9337
9338 if (Param->isInvalidDecl())
9339 NewFD->setInvalidDecl();
9340 }
9341 }
9342
9343 if (!getLangOpts().CPlusPlus) {
9344 // In C, find all the tag declarations from the prototype and move them
9345 // into the function DeclContext. Remove them from the surrounding tag
9346 // injection context of the function, which is typically but not always
9347 // the TU.
9348 DeclContext *PrototypeTagContext =
9349 getTagInjectionContext(NewFD->getLexicalDeclContext());
9350 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9351 auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9352
9353 // We don't want to reparent enumerators. Look at their parent enum
9354 // instead.
9355 if (!TD) {
9356 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9357 TD = cast<EnumDecl>(ECD->getDeclContext());
9358 }
9359 if (!TD)
9360 continue;
9361 DeclContext *TagDC = TD->getLexicalDeclContext();
9362 if (!TagDC->containsDecl(TD))
9363 continue;
9364 TagDC->removeDecl(TD);
9365 TD->setDeclContext(NewFD);
9366 NewFD->addDecl(TD);
9367
9368 // Preserve the lexical DeclContext if it is not the surrounding tag
9369 // injection context of the FD. In this example, the semantic context of
9370 // E will be f and the lexical context will be S, while both the
9371 // semantic and lexical contexts of S will be f:
9372 // void f(struct S { enum E { a } f; } s);
9373 if (TagDC != PrototypeTagContext)
9374 TD->setLexicalDeclContext(TagDC);
9375 }
9376 }
9377 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9378 // When we're declaring a function with a typedef, typeof, etc as in the
9379 // following example, we'll need to synthesize (unnamed)
9380 // parameters for use in the declaration.
9381 //
9382 // @code
9383 // typedef void fn(int);
9384 // fn f;
9385 // @endcode
9386
9387 // Synthesize a parameter for each argument type.
9388 for (const auto &AI : FT->param_types()) {
9389 ParmVarDecl *Param =
9390 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9391 Param->setScopeInfo(0, Params.size());
9392 Params.push_back(Param);
9393 }
9394 } else {
9395 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&((R->isFunctionNoProtoType() && NewFD->getNumParams
() == 0 && "Should not need args for typedef of non-prototype fn"
) ? static_cast<void> (0) : __assert_fail ("R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && \"Should not need args for typedef of non-prototype fn\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 9396, __PRETTY_FUNCTION__))
9396 "Should not need args for typedef of non-prototype fn")((R->isFunctionNoProtoType() && NewFD->getNumParams
() == 0 && "Should not need args for typedef of non-prototype fn"
) ? static_cast<void> (0) : __assert_fail ("R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && \"Should not need args for typedef of non-prototype fn\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 9396, __PRETTY_FUNCTION__))
;
9397 }
9398
9399 // Finally, we know we have the right number of parameters, install them.
9400 NewFD->setParams(Params);
9401
9402 if (D.getDeclSpec().isNoreturnSpecified())
9403 NewFD->addAttr(C11NoReturnAttr::Create(Context,
9404 D.getDeclSpec().getNoreturnSpecLoc(),
9405 AttributeCommonInfo::AS_Keyword));
9406
9407 // Functions returning a variably modified type violate C99 6.7.5.2p2
9408 // because all functions have linkage.
9409 if (!NewFD->isInvalidDecl() &&
9410 NewFD->getReturnType()->isVariablyModifiedType()) {
9411 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9412 NewFD->setInvalidDecl();
9413 }
9414
9415 // Apply an implicit SectionAttr if '#pragma clang section text' is active
9416 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9417 !NewFD->hasAttr<SectionAttr>())
9418 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9419 Context, PragmaClangTextSection.SectionName,
9420 PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9421
9422 // Apply an implicit SectionAttr if #pragma code_seg is active.
9423 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9424 !NewFD->hasAttr<SectionAttr>()) {
9425 NewFD->addAttr(SectionAttr::CreateImplicit(
9426 Context, CodeSegStack.CurrentValue->getString(),
9427 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9428 SectionAttr::Declspec_allocate));
9429 if (UnifySection(CodeSegStack.CurrentValue->getString(),
9430 ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9431 ASTContext::PSF_Read,
9432 NewFD))
9433 NewFD->dropAttr<SectionAttr>();
9434 }
9435
9436 // Apply an implicit CodeSegAttr from class declspec or
9437 // apply an implicit SectionAttr from #pragma code_seg if active.
9438 if (!NewFD->hasAttr<CodeSegAttr>()) {
9439 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9440 D.isFunctionDefinition())) {
9441 NewFD->addAttr(SAttr);
9442 }
9443 }
9444
9445 // Handle attributes.
9446 ProcessDeclAttributes(S, NewFD, D);
9447
9448 if (getLangOpts().OpenCL) {
9449 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9450 // type declaration will generate a compilation error.
9451 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9452 if (AddressSpace != LangAS::Default) {
9453 Diag(NewFD->getLocation(),
9454 diag::err_opencl_return_value_with_address_space);
9455 NewFD->setInvalidDecl();
9456 }
9457 }
9458
9459 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice))
9460 checkDeviceDecl(NewFD, D.getBeginLoc());
9461
9462 if (!getLangOpts().CPlusPlus) {
9463 // Perform semantic checking on the function declaration.
9464 if (!NewFD->isInvalidDecl() && NewFD->isMain())
9465 CheckMain(NewFD, D.getDeclSpec());
9466
9467 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9468 CheckMSVCRTEntryPoint(NewFD);
9469
9470 if (!NewFD->isInvalidDecl())
9471 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9472 isMemberSpecialization));
9473 else if (!Previous.empty())
9474 // Recover gracefully from an invalid redeclaration.
9475 D.setRedeclaration(true);
9476 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous
.getResultKind() != LookupResult::FoundOverloaded) &&
"previous declaration set still overloaded") ? static_cast<
void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 9478, __PRETTY_FUNCTION__))
9477 Previous.getResultKind() != LookupResult::FoundOverloaded) &&(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous
.getResultKind() != LookupResult::FoundOverloaded) &&
"previous declaration set still overloaded") ? static_cast<
void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 9478, __PRETTY_FUNCTION__))
9478 "previous declaration set still overloaded")(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous
.getResultKind() != LookupResult::FoundOverloaded) &&
"previous declaration set still overloaded") ? static_cast<
void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 9478, __PRETTY_FUNCTION__))
;
9479
9480 // Diagnose no-prototype function declarations with calling conventions that
9481 // don't support variadic calls. Only do this in C and do it after merging
9482 // possibly prototyped redeclarations.
9483 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9484 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9485 CallingConv CC = FT->getExtInfo().getCC();
9486 if (!supportsVariadicCall(CC)) {
9487 // Windows system headers sometimes accidentally use stdcall without
9488 // (void) parameters, so we relax this to a warning.
9489 int DiagID =
9490 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9491 Diag(NewFD->getLocation(), DiagID)
9492 << FunctionType::getNameForCallConv(CC);
9493 }
9494 }
9495
9496 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9497 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9498 checkNonTrivialCUnion(NewFD->getReturnType(),
9499 NewFD->getReturnTypeSourceRange().getBegin(),
9500 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9501 } else {
9502 // C++11 [replacement.functions]p3:
9503 // The program's definitions shall not be specified as inline.
9504 //
9505 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9506 //
9507 // Suppress the diagnostic if the function is __attribute__((used)), since
9508 // that forces an external definition to be emitted.
9509 if (D.getDeclSpec().isInlineSpecified() &&
9510 NewFD->isReplaceableGlobalAllocationFunction() &&
9511 !NewFD->hasAttr<UsedAttr>())
9512 Diag(D.getDeclSpec().getInlineSpecLoc(),
9513 diag::ext_operator_new_delete_declared_inline)
9514 << NewFD->getDeclName();
9515
9516 // If the declarator is a template-id, translate the parser's template
9517 // argument list into our AST format.
9518 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9519 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9520 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9521 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9522 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9523 TemplateId->NumArgs);
9524 translateTemplateArguments(TemplateArgsPtr,
9525 TemplateArgs);
9526
9527 HasExplicitTemplateArgs = true;
9528
9529 if (NewFD->isInvalidDecl()) {
9530 HasExplicitTemplateArgs = false;
9531 } else if (FunctionTemplate) {
9532 // Function template with explicit template arguments.
9533 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9534 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9535
9536 HasExplicitTemplateArgs = false;
9537 } else {
9538 assert((isFunctionTemplateSpecialization ||(((isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified
()) && "should have a 'template<>' for this decl"
) ? static_cast<void> (0) : __assert_fail ("(isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && \"should have a 'template<>' for this decl\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 9540, __PRETTY_FUNCTION__))
9539 D.getDeclSpec().isFriendSpecified()) &&(((isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified
()) && "should have a 'template<>' for this decl"
) ? static_cast<void> (0) : __assert_fail ("(isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && \"should have a 'template<>' for this decl\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 9540, __PRETTY_FUNCTION__))
9540 "should have a 'template<>' for this decl")(((isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified
()) && "should have a 'template<>' for this decl"
) ? static_cast<void> (0) : __assert_fail ("(isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && \"should have a 'template<>' for this decl\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 9540, __PRETTY_FUNCTION__))
;
9541 // "friend void foo<>(int);" is an implicit specialization decl.
9542 isFunctionTemplateSpecialization = true;
9543 }
9544 } else if (isFriend && isFunctionTemplateSpecialization) {
9545 // This combination is only possible in a recovery case; the user
9546 // wrote something like:
9547 // template <> friend void foo(int);
9548 // which we're recovering from as if the user had written:
9549 // friend void foo<>(int);
9550 // Go ahead and fake up a template id.
9551 HasExplicitTemplateArgs = true;
9552 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9553 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9554 }
9555
9556 // We do not add HD attributes to specializations here because
9557 // they may have different constexpr-ness compared to their
9558 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9559 // may end up with different effective targets. Instead, a
9560 // specialization inherits its target attributes from its template
9561 // in the CheckFunctionTemplateSpecialization() call below.
9562 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9563 maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9564
9565 // If it's a friend (and only if it's a friend), it's possible
9566 // that either the specialized function type or the specialized
9567 // template is dependent, and therefore matching will fail. In
9568 // this case, don't check the specialization yet.
9569 if (isFunctionTemplateSpecialization && isFriend &&
9570 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9571 TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
9572 TemplateArgs.arguments()))) {
9573 assert(HasExplicitTemplateArgs &&((HasExplicitTemplateArgs && "friend function specialization without template args"
) ? static_cast<void> (0) : __assert_fail ("HasExplicitTemplateArgs && \"friend function specialization without template args\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 9574, __PRETTY_FUNCTION__))
9574 "friend function specialization without template args")((HasExplicitTemplateArgs && "friend function specialization without template args"
) ? static_cast<void> (0) : __assert_fail ("HasExplicitTemplateArgs && \"friend function specialization without template args\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 9574, __PRETTY_FUNCTION__))
;
9575 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9576 Previous))
9577 NewFD->setInvalidDecl();
9578 } else if (isFunctionTemplateSpecialization) {
9579 if (CurContext->isDependentContext() && CurContext->isRecord()
9580 && !isFriend) {
9581 isDependentClassScopeExplicitSpecialization = true;
9582 } else if (!NewFD->isInvalidDecl() &&
9583 CheckFunctionTemplateSpecialization(
9584 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9585 Previous))
9586 NewFD->setInvalidDecl();
9587
9588 // C++ [dcl.stc]p1:
9589 // A storage-class-specifier shall not be specified in an explicit
9590 // specialization (14.7.3)
9591 FunctionTemplateSpecializationInfo *Info =
9592 NewFD->getTemplateSpecializationInfo();
9593 if (Info && SC != SC_None) {
9594 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9595 Diag(NewFD->getLocation(),
9596 diag::err_explicit_specialization_inconsistent_storage_class)
9597 << SC
9598 << FixItHint::CreateRemoval(
9599 D.getDeclSpec().getStorageClassSpecLoc());
9600
9601 else
9602 Diag(NewFD->getLocation(),
9603 diag::ext_explicit_specialization_storage_class)
9604 << FixItHint::CreateRemoval(
9605 D.getDeclSpec().getStorageClassSpecLoc());
9606 }
9607 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9608 if (CheckMemberSpecialization(NewFD, Previous))
9609 NewFD->setInvalidDecl();
9610 }
9611
9612 // Perform semantic checking on the function declaration.
9613 if (!isDependentClassScopeExplicitSpecialization) {
9614 if (!NewFD->isInvalidDecl() && NewFD->isMain())
9615 CheckMain(NewFD, D.getDeclSpec());
9616
9617 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9618 CheckMSVCRTEntryPoint(NewFD);
9619
9620 if (!NewFD->isInvalidDecl())
9621 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9622 isMemberSpecialization));
9623 else if (!Previous.empty())
9624 // Recover gracefully from an invalid redeclaration.
9625 D.setRedeclaration(true);
9626 }
9627
9628 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous
.getResultKind() != LookupResult::FoundOverloaded) &&
"previous declaration set still overloaded") ? static_cast<
void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 9630, __PRETTY_FUNCTION__))
9629 Previous.getResultKind() != LookupResult::FoundOverloaded) &&(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous
.getResultKind() != LookupResult::FoundOverloaded) &&
"previous declaration set still overloaded") ? static_cast<
void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 9630, __PRETTY_FUNCTION__))
9630 "previous declaration set still overloaded")(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous
.getResultKind() != LookupResult::FoundOverloaded) &&
"previous declaration set still overloaded") ? static_cast<
void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 9630, __PRETTY_FUNCTION__))
;
9631
9632 NamedDecl *PrincipalDecl = (FunctionTemplate
9633 ? cast<NamedDecl>(FunctionTemplate)
9634 : NewFD);
9635
9636 if (isFriend && NewFD->getPreviousDecl()) {
9637 AccessSpecifier Access = AS_public;
9638 if (!NewFD->isInvalidDecl())
9639 Access = NewFD->getPreviousDecl()->getAccess();
9640
9641 NewFD->setAccess(Access);
9642 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9643 }
9644
9645 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9646 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9647 PrincipalDecl->setNonMemberOperator();
9648
9649 // If we have a function template, check the template parameter
9650 // list. This will check and merge default template arguments.
9651 if (FunctionTemplate) {
9652 FunctionTemplateDecl *PrevTemplate =
9653 FunctionTemplate->getPreviousDecl();
9654 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9655 PrevTemplate ? PrevTemplate->getTemplateParameters()
9656 : nullptr,
9657 D.getDeclSpec().isFriendSpecified()
9658 ? (D.isFunctionDefinition()
9659 ? TPC_FriendFunctionTemplateDefinition
9660 : TPC_FriendFunctionTemplate)
9661 : (D.getCXXScopeSpec().isSet() &&
9662 DC && DC->isRecord() &&
9663 DC->isDependentContext())
9664 ? TPC_ClassTemplateMember
9665 : TPC_FunctionTemplate);
9666 }
9667
9668 if (NewFD->isInvalidDecl()) {
9669 // Ignore all the rest of this.
9670 } else if (!D.isRedeclaration()) {
9671 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9672 AddToScope };
9673 // Fake up an access specifier if it's supposed to be a class member.
9674 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9675 NewFD->setAccess(AS_public);
9676
9677 // Qualified decls generally require a previous declaration.
9678 if (D.getCXXScopeSpec().isSet()) {
9679 // ...with the major exception of templated-scope or
9680 // dependent-scope friend declarations.
9681
9682 // TODO: we currently also suppress this check in dependent
9683 // contexts because (1) the parameter depth will be off when
9684 // matching friend templates and (2) we might actually be
9685 // selecting a friend based on a dependent factor. But there
9686 // are situations where these conditions don't apply and we
9687 // can actually do this check immediately.
9688 //
9689 // Unless the scope is dependent, it's always an error if qualified
9690 // redeclaration lookup found nothing at all. Diagnose that now;
9691 // nothing will diagnose that error later.
9692 if (isFriend &&
9693 (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9694 (!Previous.empty() && CurContext->isDependentContext()))) {
9695 // ignore these
9696 } else {
9697 // The user tried to provide an out-of-line definition for a
9698 // function that is a member of a class or namespace, but there
9699 // was no such member function declared (C++ [class.mfct]p2,
9700 // C++ [namespace.memdef]p2). For example:
9701 //
9702 // class X {
9703 // void f() const;
9704 // };
9705 //
9706 // void X::f() { } // ill-formed
9707 //
9708 // Complain about this problem, and attempt to suggest close
9709 // matches (e.g., those that differ only in cv-qualifiers and
9710 // whether the parameter types are references).
9711
9712 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9713 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9714 AddToScope = ExtraArgs.AddToScope;
9715 return Result;
9716 }
9717 }
9718
9719 // Unqualified local friend declarations are required to resolve
9720 // to something.
9721 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9722 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9723 *this, Previous, NewFD, ExtraArgs, true, S)) {
9724 AddToScope = ExtraArgs.AddToScope;
9725 return Result;
9726 }
9727 }
9728 } else if (!D.isFunctionDefinition() &&
9729 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9730 !isFriend && !isFunctionTemplateSpecialization &&
9731 !isMemberSpecialization) {
9732 // An out-of-line member function declaration must also be a
9733 // definition (C++ [class.mfct]p2).
9734 // Note that this is not the case for explicit specializations of
9735 // function templates or member functions of class templates, per
9736 // C++ [temp.expl.spec]p2. We also allow these declarations as an
9737 // extension for compatibility with old SWIG code which likes to
9738 // generate them.
9739 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9740 << D.getCXXScopeSpec().getRange();
9741 }
9742 }
9743
9744 // If this is the first declaration of a library builtin function, add
9745 // attributes as appropriate.
9746 if (!D.isRedeclaration() &&
9747 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
9748 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
9749 if (unsigned BuiltinID = II->getBuiltinID()) {
9750 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
9751 // Validate the type matches unless this builtin is specified as
9752 // matching regardless of its declared type.
9753 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
9754 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9755 } else {
9756 ASTContext::GetBuiltinTypeError Error;
9757 LookupNecessaryTypesForBuiltin(S, BuiltinID);
9758 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
9759
9760 if (!Error && !BuiltinType.isNull() &&
9761 Context.hasSameFunctionTypeIgnoringExceptionSpec(
9762 NewFD->getType(), BuiltinType))
9763 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9764 }
9765 } else if (BuiltinID == Builtin::BI__GetExceptionInfo &&
9766 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9767 // FIXME: We should consider this a builtin only in the std namespace.
9768 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9769 }
9770 }
9771 }
9772 }
9773
9774 ProcessPragmaWeak(S, NewFD);
9775 checkAttributesAfterMerging(*this, *NewFD);
9776
9777 AddKnownFunctionAttributes(NewFD);
9778
9779 if (NewFD->hasAttr<OverloadableAttr>() &&
9780 !NewFD->getType()->getAs<FunctionProtoType>()) {
9781 Diag(NewFD->getLocation(),
9782 diag::err_attribute_overloadable_no_prototype)
9783 << NewFD;
9784
9785 // Turn this into a variadic function with no parameters.
9786 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9787 FunctionProtoType::ExtProtoInfo EPI(
9788 Context.getDefaultCallingConvention(true, false));
9789 EPI.Variadic = true;
9790 EPI.ExtInfo = FT->getExtInfo();
9791
9792 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9793 NewFD->setType(R);
9794 }
9795
9796 // If there's a #pragma GCC visibility in scope, and this isn't a class
9797 // member, set the visibility of this function.
9798 if (!DC->isRecord() && NewFD->isExternallyVisible())
9799 AddPushedVisibilityAttribute(NewFD);
9800
9801 // If there's a #pragma clang arc_cf_code_audited in scope, consider
9802 // marking the function.
9803 AddCFAuditedAttribute(NewFD);
9804
9805 // If this is a function definition, check if we have to apply optnone due to
9806 // a pragma.
9807 if(D.isFunctionDefinition())
9808 AddRangeBasedOptnone(NewFD);
9809
9810 // If this is the first declaration of an extern C variable, update
9811 // the map of such variables.
9812 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9813 isIncompleteDeclExternC(*this, NewFD))
9814 RegisterLocallyScopedExternCDecl(NewFD, S);
9815
9816 // Set this FunctionDecl's range up to the right paren.
9817 NewFD->setRangeEnd(D.getSourceRange().getEnd());
9818
9819 if (D.isRedeclaration() && !Previous.empty()) {
9820 NamedDecl *Prev = Previous.getRepresentativeDecl();
9821 checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9822 isMemberSpecialization ||
9823 isFunctionTemplateSpecialization,
9824 D.isFunctionDefinition());
9825 }
9826
9827 if (getLangOpts().CUDA) {
9828 IdentifierInfo *II = NewFD->getIdentifier();
9829 if (II && II->isStr(getCudaConfigureFuncName()) &&
9830 !NewFD->isInvalidDecl() &&
9831 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9832 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
9833 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9834 << getCudaConfigureFuncName();
9835 Context.setcudaConfigureCallDecl(NewFD);
9836 }
9837
9838 // Variadic functions, other than a *declaration* of printf, are not allowed
9839 // in device-side CUDA code, unless someone passed
9840 // -fcuda-allow-variadic-functions.
9841 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9842 (NewFD->hasAttr<CUDADeviceAttr>() ||
9843 NewFD->hasAttr<CUDAGlobalAttr>()) &&
9844 !(II && II->isStr("printf") && NewFD->isExternC() &&
9845 !D.isFunctionDefinition())) {
9846 Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9847 }
9848 }
9849
9850 MarkUnusedFileScopedDecl(NewFD);
9851
9852
9853
9854 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
9855 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9856 if ((getLangOpts().OpenCLVersion >= 120)
9857 && (SC == SC_Static)) {
9858 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9859 D.setInvalidType();
9860 }
9861
9862 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9863 if (!NewFD->getReturnType()->isVoidType()) {
9864 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9865 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9866 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9867 : FixItHint());
9868 D.setInvalidType();
9869 }
9870
9871 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9872 for (auto Param : NewFD->parameters())
9873 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9874
9875 if (getLangOpts().OpenCLCPlusPlus) {
9876 if (DC->isRecord()) {
9877 Diag(D.getIdentifierLoc(), diag::err_method_kernel);
9878 D.setInvalidType();
9879 }
9880 if (FunctionTemplate) {
9881 Diag(D.getIdentifierLoc(), diag::err_template_kernel);
9882 D.setInvalidType();
9883 }
9884 }
9885 }
9886
9887 if (getLangOpts().CPlusPlus) {
9888 if (FunctionTemplate) {
9889 if (NewFD->isInvalidDecl())
9890 FunctionTemplate->setInvalidDecl();
9891 return FunctionTemplate;
9892 }
9893
9894 if (isMemberSpecialization && !NewFD->isInvalidDecl())
9895 CompleteMemberSpecialization(NewFD, Previous);
9896 }
9897
9898 for (const ParmVarDecl *Param : NewFD->parameters()) {
9899 QualType PT = Param->getType();
9900
9901 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9902 // types.
9903 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
9904 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9905 QualType ElemTy = PipeTy->getElementType();
9906 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9907 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9908 D.setInvalidType();
9909 }
9910 }
9911 }
9912 }
9913
9914 // Here we have an function template explicit specialization at class scope.
9915 // The actual specialization will be postponed to template instatiation
9916 // time via the ClassScopeFunctionSpecializationDecl node.
9917 if (isDependentClassScopeExplicitSpecialization) {
9918 ClassScopeFunctionSpecializationDecl *NewSpec =
9919 ClassScopeFunctionSpecializationDecl::Create(
9920 Context, CurContext, NewFD->getLocation(),
9921 cast<CXXMethodDecl>(NewFD),
9922 HasExplicitTemplateArgs, TemplateArgs);
9923 CurContext->addDecl(NewSpec);
9924 AddToScope = false;
9925 }
9926
9927 // Diagnose availability attributes. Availability cannot be used on functions
9928 // that are run during load/unload.
9929 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9930 if (NewFD->hasAttr<ConstructorAttr>()) {
9931 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9932 << 1;
9933 NewFD->dropAttr<AvailabilityAttr>();
9934 }
9935 if (NewFD->hasAttr<DestructorAttr>()) {
9936 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9937 << 2;
9938 NewFD->dropAttr<AvailabilityAttr>();
9939 }
9940 }
9941
9942 // Diagnose no_builtin attribute on function declaration that are not a
9943 // definition.
9944 // FIXME: We should really be doing this in
9945 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
9946 // the FunctionDecl and at this point of the code
9947 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
9948 // because Sema::ActOnStartOfFunctionDef has not been called yet.
9949 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
9950 switch (D.getFunctionDefinitionKind()) {
9951 case FunctionDefinitionKind::Defaulted:
9952 case FunctionDefinitionKind::Deleted:
9953 Diag(NBA->getLocation(),
9954 diag::err_attribute_no_builtin_on_defaulted_deleted_function)
9955 << NBA->getSpelling();
9956 break;
9957 case FunctionDefinitionKind::Declaration:
9958 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
9959 << NBA->getSpelling();
9960 break;
9961 case FunctionDefinitionKind::Definition:
9962 break;
9963 }
9964
9965 return NewFD;
9966}
9967
9968/// Return a CodeSegAttr from a containing class. The Microsoft docs say
9969/// when __declspec(code_seg) "is applied to a class, all member functions of
9970/// the class and nested classes -- this includes compiler-generated special
9971/// member functions -- are put in the specified segment."
9972/// The actual behavior is a little more complicated. The Microsoft compiler
9973/// won't check outer classes if there is an active value from #pragma code_seg.
9974/// The CodeSeg is always applied from the direct parent but only from outer
9975/// classes when the #pragma code_seg stack is empty. See:
9976/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
9977/// available since MS has removed the page.
9978static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
9979 const auto *Method = dyn_cast<CXXMethodDecl>(FD);
9980 if (!Method)
9981 return nullptr;
9982 const CXXRecordDecl *Parent = Method->getParent();
9983 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9984 Attr *NewAttr = SAttr->clone(S.getASTContext());
9985 NewAttr->setImplicit(true);
9986 return NewAttr;
9987 }
9988
9989 // The Microsoft compiler won't check outer classes for the CodeSeg
9990 // when the #pragma code_seg stack is active.
9991 if (S.CodeSegStack.CurrentValue)
9992 return nullptr;
9993
9994 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
9995 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9996 Attr *NewAttr = SAttr->clone(S.getASTContext());
9997 NewAttr->setImplicit(true);
9998 return NewAttr;
9999 }
10000 }
10001 return nullptr;
10002}
10003
10004/// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
10005/// containing class. Otherwise it will return implicit SectionAttr if the
10006/// function is a definition and there is an active value on CodeSegStack
10007/// (from the current #pragma code-seg value).
10008///
10009/// \param FD Function being declared.
10010/// \param IsDefinition Whether it is a definition or just a declarartion.
10011/// \returns A CodeSegAttr or SectionAttr to apply to the function or
10012/// nullptr if no attribute should be added.
10013Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
10014 bool IsDefinition) {
10015 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
10016 return A;
10017 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
10018 CodeSegStack.CurrentValue)
10019 return SectionAttr::CreateImplicit(
10020 getASTContext(), CodeSegStack.CurrentValue->getString(),
10021 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
10022 SectionAttr::Declspec_allocate);
10023 return nullptr;
10024}
10025
10026/// Determines if we can perform a correct type check for \p D as a
10027/// redeclaration of \p PrevDecl. If not, we can generally still perform a
10028/// best-effort check.
10029///
10030/// \param NewD The new declaration.
10031/// \param OldD The old declaration.
10032/// \param NewT The portion of the type of the new declaration to check.
10033/// \param OldT The portion of the type of the old declaration to check.
10034bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
10035 QualType NewT, QualType OldT) {
10036 if (!NewD->getLexicalDeclContext()->isDependentContext())
10037 return true;
10038
10039 // For dependently-typed local extern declarations and friends, we can't
10040 // perform a correct type check in general until instantiation:
10041 //
10042 // int f();
10043 // template<typename T> void g() { T f(); }
10044 //
10045 // (valid if g() is only instantiated with T = int).
10046 if (NewT->isDependentType() &&
10047 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
10048 return false;
10049
10050 // Similarly, if the previous declaration was a dependent local extern
10051 // declaration, we don't really know its type yet.
10052 if (OldT->isDependentType() && OldD->isLocalExternDecl())
10053 return false;
10054
10055 return true;
10056}
10057
10058/// Checks if the new declaration declared in dependent context must be
10059/// put in the same redeclaration chain as the specified declaration.
10060///
10061/// \param D Declaration that is checked.
10062/// \param PrevDecl Previous declaration found with proper lookup method for the
10063/// same declaration name.
10064/// \returns True if D must be added to the redeclaration chain which PrevDecl
10065/// belongs to.
10066///
10067bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
10068 if (!D->getLexicalDeclContext()->isDependentContext())
10069 return true;
10070
10071 // Don't chain dependent friend function definitions until instantiation, to
10072 // permit cases like
10073 //
10074 // void func();
10075 // template<typename T> class C1 { friend void func() {} };
10076 // template<typename T> class C2 { friend void func() {} };
10077 //
10078 // ... which is valid if only one of C1 and C2 is ever instantiated.
10079 //
10080 // FIXME: This need only apply to function definitions. For now, we proxy
10081 // this by checking for a file-scope function. We do not want this to apply
10082 // to friend declarations nominating member functions, because that gets in
10083 // the way of access checks.
10084 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
10085 return false;
10086
10087 auto *VD = dyn_cast<ValueDecl>(D);
10088 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
10089 return !VD || !PrevVD ||
10090 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
10091 PrevVD->getType());
10092}
10093
10094/// Check the target attribute of the function for MultiVersion
10095/// validity.
10096///
10097/// Returns true if there was an error, false otherwise.
10098static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
10099 const auto *TA = FD->getAttr<TargetAttr>();
10100 assert(TA && "MultiVersion Candidate requires a target attribute")((TA && "MultiVersion Candidate requires a target attribute"
) ? static_cast<void> (0) : __assert_fail ("TA && \"MultiVersion Candidate requires a target attribute\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 10100, __PRETTY_FUNCTION__))
;
10101 ParsedTargetAttr ParseInfo = TA->parse();
10102 const TargetInfo &TargetInfo = S.Context.getTargetInfo();
10103 enum ErrType { Feature = 0, Architecture = 1 };
10104
10105 if (!ParseInfo.Architecture.empty() &&
10106 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
10107 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10108 << Architecture << ParseInfo.Architecture;
10109 return true;
10110 }
10111
10112 for (const auto &Feat : ParseInfo.Features) {
10113 auto BareFeat = StringRef{Feat}.substr(1);
10114 if (Feat[0] == '-') {
10115 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10116 << Feature << ("no-" + BareFeat).str();
10117 return true;
10118 }
10119
10120 if (!TargetInfo.validateCpuSupports(BareFeat) ||
10121 !TargetInfo.isValidFeatureName(BareFeat)) {
10122 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10123 << Feature << BareFeat;
10124 return true;
10125 }
10126 }
10127 return false;
10128}
10129
10130// Provide a white-list of attributes that are allowed to be combined with
10131// multiversion functions.
10132static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
10133 MultiVersionKind MVType) {
10134 // Note: this list/diagnosis must match the list in
10135 // checkMultiversionAttributesAllSame.
10136 switch (Kind) {
10137 default:
10138 return false;
10139 case attr::Used:
10140 return MVType == MultiVersionKind::Target;
10141 case attr::NonNull:
10142 case attr::NoThrow:
10143 return true;
10144 }
10145}
10146
10147static bool checkNonMultiVersionCompatAttributes(Sema &S,
10148 const FunctionDecl *FD,
10149 const FunctionDecl *CausedFD,
10150 MultiVersionKind MVType) {
10151 bool IsCPUSpecificCPUDispatchMVType =
10152 MVType == MultiVersionKind::CPUDispatch ||
10153 MVType == MultiVersionKind::CPUSpecific;
10154 const auto Diagnose = [FD, CausedFD, IsCPUSpecificCPUDispatchMVType](
10155 Sema &S, const Attr *A) {
10156 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
10157 << IsCPUSpecificCPUDispatchMVType << A;
10158 if (CausedFD)
10159 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
10160 return true;
10161 };
10162
10163 for (const Attr *A : FD->attrs()) {
10164 switch (A->getKind()) {
10165 case attr::CPUDispatch:
10166 case attr::CPUSpecific:
10167 if (MVType != MultiVersionKind::CPUDispatch &&
10168 MVType != MultiVersionKind::CPUSpecific)
10169 return Diagnose(S, A);
10170 break;
10171 case attr::Target:
10172 if (MVType != MultiVersionKind::Target)
10173 return Diagnose(S, A);
10174 break;
10175 default:
10176 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType))
10177 return Diagnose(S, A);
10178 break;
10179 }
10180 }
10181 return false;
10182}
10183
10184bool Sema::areMultiversionVariantFunctionsCompatible(
10185 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10186 const PartialDiagnostic &NoProtoDiagID,
10187 const PartialDiagnosticAt &NoteCausedDiagIDAt,
10188 const PartialDiagnosticAt &NoSupportDiagIDAt,
10189 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10190 bool ConstexprSupported, bool CLinkageMayDiffer) {
10191 enum DoesntSupport {
10192 FuncTemplates = 0,
10193 VirtFuncs = 1,
10194 DeducedReturn = 2,
10195 Constructors = 3,
10196 Destructors = 4,
10197 DeletedFuncs = 5,
10198 DefaultedFuncs = 6,
10199 ConstexprFuncs = 7,
10200 ConstevalFuncs = 8,
10201 };
10202 enum Different {
10203 CallingConv = 0,
10204 ReturnType = 1,
10205 ConstexprSpec = 2,
10206 InlineSpec = 3,
10207 StorageClass = 4,
10208 Linkage = 5,
10209 };
10210
10211 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
10212 !OldFD->getType()->getAs<FunctionProtoType>()) {
10213 Diag(OldFD->getLocation(), NoProtoDiagID);
10214 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10215 return true;
10216 }
10217
10218 if (NoProtoDiagID.getDiagID() != 0 &&
10219 !NewFD->getType()->getAs<FunctionProtoType>())
10220 return Diag(NewFD->getLocation(), NoProtoDiagID);
10221
10222 if (!TemplatesSupported &&
10223 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10224 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10225 << FuncTemplates;
10226
10227 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
10228 if (NewCXXFD->isVirtual())
10229 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10230 << VirtFuncs;
10231
10232 if (isa<CXXConstructorDecl>(NewCXXFD))
10233 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10234 << Constructors;
10235
10236 if (isa<CXXDestructorDecl>(NewCXXFD))
10237 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10238 << Destructors;
10239 }
10240
10241 if (NewFD->isDeleted())
10242 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10243 << DeletedFuncs;
10244
10245 if (NewFD->isDefaulted())
10246 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10247 << DefaultedFuncs;
10248
10249 if (!ConstexprSupported && NewFD->isConstexpr())
10250 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10251 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
10252
10253 QualType NewQType = Context.getCanonicalType(NewFD->getType());
10254 const auto *NewType = cast<FunctionType>(NewQType);
10255 QualType NewReturnType = NewType->getReturnType();
10256
10257 if (NewReturnType->isUndeducedType())
10258 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10259 << DeducedReturn;
10260
10261 // Ensure the return type is identical.
10262 if (OldFD) {
10263 QualType OldQType = Context.getCanonicalType(OldFD->getType());
10264 const auto *OldType = cast<FunctionType>(OldQType);
10265 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
10266 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
10267
10268 if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
10269 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
10270
10271 QualType OldReturnType = OldType->getReturnType();
10272
10273 if (OldReturnType != NewReturnType)
10274 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
10275
10276 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
10277 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
10278
10279 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
10280 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
10281
10282 if (OldFD->getStorageClass() != NewFD->getStorageClass())
10283 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass;
10284
10285 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
10286 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
10287
10288 if (CheckEquivalentExceptionSpec(
10289 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
10290 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
10291 return true;
10292 }
10293 return false;
10294}
10295
10296static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
10297 const FunctionDecl *NewFD,
10298 bool CausesMV,
10299 MultiVersionKind MVType) {
10300 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10301 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10302 if (OldFD)
10303 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10304 return true;
10305 }
10306
10307 bool IsCPUSpecificCPUDispatchMVType =
10308 MVType == MultiVersionKind::CPUDispatch ||
10309 MVType == MultiVersionKind::CPUSpecific;
10310
10311 if (CausesMV && OldFD &&
10312 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVType))
10313 return true;
10314
10315 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVType))
10316 return true;
10317
10318 // Only allow transition to MultiVersion if it hasn't been used.
10319 if (OldFD && CausesMV && OldFD->isUsed(false))
10320 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10321
10322 return S.areMultiversionVariantFunctionsCompatible(
10323 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
10324 PartialDiagnosticAt(NewFD->getLocation(),
10325 S.PDiag(diag::note_multiversioning_caused_here)),
10326 PartialDiagnosticAt(NewFD->getLocation(),
10327 S.PDiag(diag::err_multiversion_doesnt_support)
10328 << IsCPUSpecificCPUDispatchMVType),
10329 PartialDiagnosticAt(NewFD->getLocation(),
10330 S.PDiag(diag::err_multiversion_diff)),
10331 /*TemplatesSupported=*/false,
10332 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType,
10333 /*CLinkageMayDiffer=*/false);
10334}
10335
10336/// Check the validity of a multiversion function declaration that is the
10337/// first of its kind. Also sets the multiversion'ness' of the function itself.
10338///
10339/// This sets NewFD->isInvalidDecl() to true if there was an error.
10340///
10341/// Returns true if there was an error, false otherwise.
10342static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10343 MultiVersionKind MVType,
10344 const TargetAttr *TA) {
10345 assert(MVType != MultiVersionKind::None &&((MVType != MultiVersionKind::None && "Function lacks multiversion attribute"
) ? static_cast<void> (0) : __assert_fail ("MVType != MultiVersionKind::None && \"Function lacks multiversion attribute\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 10346, __PRETTY_FUNCTION__))
10346 "Function lacks multiversion attribute")((MVType != MultiVersionKind::None && "Function lacks multiversion attribute"
) ? static_cast<void> (0) : __assert_fail ("MVType != MultiVersionKind::None && \"Function lacks multiversion attribute\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 10346, __PRETTY_FUNCTION__))
;
10347
10348 // Target only causes MV if it is default, otherwise this is a normal
10349 // function.
10350 if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
10351 return false;
10352
10353 if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10354 FD->setInvalidDecl();
10355 return true;
10356 }
10357
10358 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
10359 FD->setInvalidDecl();
10360 return true;
10361 }
10362
10363 FD->setIsMultiVersion();
10364 return false;
10365}
10366
10367static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10368 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10369 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10370 return true;
10371 }
10372
10373 return false;
10374}
10375
10376static bool CheckTargetCausesMultiVersioning(
10377 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10378 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10379 LookupResult &Previous) {
10380 const auto *OldTA = OldFD->getAttr<TargetAttr>();
10381 ParsedTargetAttr NewParsed = NewTA->parse();
10382 // Sort order doesn't matter, it just needs to be consistent.
10383 llvm::sort(NewParsed.Features);
10384
10385 // If the old decl is NOT MultiVersioned yet, and we don't cause that
10386 // to change, this is a simple redeclaration.
10387 if (!NewTA->isDefaultVersion() &&
10388 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10389 return false;
10390
10391 // Otherwise, this decl causes MultiVersioning.
10392 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10393 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10394 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10395 NewFD->setInvalidDecl();
10396 return true;
10397 }
10398
10399 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10400 MultiVersionKind::Target)) {
10401 NewFD->setInvalidDecl();
10402 return true;
10403 }
10404
10405 if (CheckMultiVersionValue(S, NewFD)) {
10406 NewFD->setInvalidDecl();
10407 return true;
10408 }
10409
10410 // If this is 'default', permit the forward declaration.
10411 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10412 Redeclaration = true;
10413 OldDecl = OldFD;
10414 OldFD->setIsMultiVersion();
10415 NewFD->setIsMultiVersion();
10416 return false;
10417 }
10418
10419 if (CheckMultiVersionValue(S, OldFD)) {
10420 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10421 NewFD->setInvalidDecl();
10422 return true;
10423 }
10424
10425 ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10426
10427 if (OldParsed == NewParsed) {
10428 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10429 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10430 NewFD->setInvalidDecl();
10431 return true;
10432 }
10433
10434 for (const auto *FD : OldFD->redecls()) {
10435 const auto *CurTA = FD->getAttr<TargetAttr>();
10436 // We allow forward declarations before ANY multiversioning attributes, but
10437 // nothing after the fact.
10438 if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10439 (!CurTA || CurTA->isInherited())) {
10440 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10441 << 0;
10442 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10443 NewFD->setInvalidDecl();
10444 return true;
10445 }
10446 }
10447
10448 OldFD->setIsMultiVersion();
10449 NewFD->setIsMultiVersion();
10450 Redeclaration = false;
10451 MergeTypeWithPrevious = false;
10452 OldDecl = nullptr;
10453 Previous.clear();
10454 return false;
10455}
10456
10457/// Check the validity of a new function declaration being added to an existing
10458/// multiversioned declaration collection.
10459static bool CheckMultiVersionAdditionalDecl(
10460 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10461 MultiVersionKind NewMVType, const TargetAttr *NewTA,
10462 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10463 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10464 LookupResult &Previous) {
10465
10466 MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
10467 // Disallow mixing of multiversioning types.
10468 if ((OldMVType == MultiVersionKind::Target &&
10469 NewMVType != MultiVersionKind::Target) ||
10470 (NewMVType == MultiVersionKind::Target &&
10471 OldMVType != MultiVersionKind::Target)) {
10472 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10473 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10474 NewFD->setInvalidDecl();
10475 return true;
10476 }
10477
10478 ParsedTargetAttr NewParsed;
10479 if (NewTA) {
10480 NewParsed = NewTA->parse();
10481 llvm::sort(NewParsed.Features);
10482 }
10483
10484 bool UseMemberUsingDeclRules =
10485 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10486
10487 // Next, check ALL non-overloads to see if this is a redeclaration of a
10488 // previous member of the MultiVersion set.
10489 for (NamedDecl *ND : Previous) {
10490 FunctionDecl *CurFD = ND->getAsFunction();
10491 if (!CurFD)
10492 continue;
10493 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10494 continue;
10495
10496 if (NewMVType == MultiVersionKind::Target) {
10497 const auto *CurTA = CurFD->getAttr<TargetAttr>();
10498 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10499 NewFD->setIsMultiVersion();
10500 Redeclaration = true;
10501 OldDecl = ND;
10502 return false;
10503 }
10504
10505 ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10506 if (CurParsed == NewParsed) {
10507 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10508 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10509 NewFD->setInvalidDecl();
10510 return true;
10511 }
10512 } else {
10513 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10514 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10515 // Handle CPUDispatch/CPUSpecific versions.
10516 // Only 1 CPUDispatch function is allowed, this will make it go through
10517 // the redeclaration errors.
10518 if (NewMVType == MultiVersionKind::CPUDispatch &&
10519 CurFD->hasAttr<CPUDispatchAttr>()) {
10520 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10521 std::equal(
10522 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10523 NewCPUDisp->cpus_begin(),
10524 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10525 return Cur->getName() == New->getName();
10526 })) {
10527 NewFD->setIsMultiVersion();
10528 Redeclaration = true;
10529 OldDecl = ND;
10530 return false;
10531 }
10532
10533 // If the declarations don't match, this is an error condition.
10534 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10535 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10536 NewFD->setInvalidDecl();
10537 return true;
10538 }
10539 if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10540
10541 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10542 std::equal(
10543 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10544 NewCPUSpec->cpus_begin(),
10545 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10546 return Cur->getName() == New->getName();
10547 })) {
10548 NewFD->setIsMultiVersion();
10549 Redeclaration = true;
10550 OldDecl = ND;
10551 return false;
10552 }
10553
10554 // Only 1 version of CPUSpecific is allowed for each CPU.
10555 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10556 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10557 if (CurII == NewII) {
10558 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10559 << NewII;
10560 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10561 NewFD->setInvalidDecl();
10562 return true;
10563 }
10564 }
10565 }
10566 }
10567 // If the two decls aren't the same MVType, there is no possible error
10568 // condition.
10569 }
10570 }
10571
10572 // Else, this is simply a non-redecl case. Checking the 'value' is only
10573 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10574 // handled in the attribute adding step.
10575 if (NewMVType == MultiVersionKind::Target &&
10576 CheckMultiVersionValue(S, NewFD)) {
10577 NewFD->setInvalidDecl();
10578 return true;
10579 }
10580
10581 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10582 !OldFD->isMultiVersion(), NewMVType)) {
10583 NewFD->setInvalidDecl();
10584 return true;
10585 }
10586
10587 // Permit forward declarations in the case where these two are compatible.
10588 if (!OldFD->isMultiVersion()) {
10589 OldFD->setIsMultiVersion();
10590 NewFD->setIsMultiVersion();
10591 Redeclaration = true;
10592 OldDecl = OldFD;
10593 return false;
10594 }
10595
10596 NewFD->setIsMultiVersion();
10597 Redeclaration = false;
10598 MergeTypeWithPrevious = false;
10599 OldDecl = nullptr;
10600 Previous.clear();
10601 return false;
10602}
10603
10604
10605/// Check the validity of a mulitversion function declaration.
10606/// Also sets the multiversion'ness' of the function itself.
10607///
10608/// This sets NewFD->isInvalidDecl() to true if there was an error.
10609///
10610/// Returns true if there was an error, false otherwise.
10611static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10612 bool &Redeclaration, NamedDecl *&OldDecl,
10613 bool &MergeTypeWithPrevious,
10614 LookupResult &Previous) {
10615 const auto *NewTA = NewFD->getAttr<TargetAttr>();
10616 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10617 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10618
10619 // Mixing Multiversioning types is prohibited.
10620 if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
10621 (NewCPUDisp && NewCPUSpec)) {
10622 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10623 NewFD->setInvalidDecl();
10624 return true;
10625 }
10626
10627 MultiVersionKind MVType = NewFD->getMultiVersionKind();
10628
10629 // Main isn't allowed to become a multiversion function, however it IS
10630 // permitted to have 'main' be marked with the 'target' optimization hint.
10631 if (NewFD->isMain()) {
10632 if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
10633 MVType == MultiVersionKind::CPUDispatch ||
10634 MVType == MultiVersionKind::CPUSpecific) {
10635 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10636 NewFD->setInvalidDecl();
10637 return true;
10638 }
10639 return false;
10640 }
10641
10642 if (!OldDecl || !OldDecl->getAsFunction() ||
10643 OldDecl->getDeclContext()->getRedeclContext() !=
10644 NewFD->getDeclContext()->getRedeclContext()) {
10645 // If there's no previous declaration, AND this isn't attempting to cause
10646 // multiversioning, this isn't an error condition.
10647 if (MVType == MultiVersionKind::None)
10648 return false;
10649 return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
10650 }
10651
10652 FunctionDecl *OldFD = OldDecl->getAsFunction();
10653
10654 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
10655 return false;
10656
10657 if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
10658 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10659 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10660 NewFD->setInvalidDecl();
10661 return true;
10662 }
10663
10664 // Handle the target potentially causes multiversioning case.
10665 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10666 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10667 Redeclaration, OldDecl,
10668 MergeTypeWithPrevious, Previous);
10669
10670 // At this point, we have a multiversion function decl (in OldFD) AND an
10671 // appropriate attribute in the current function decl. Resolve that these are
10672 // still compatible with previous declarations.
10673 return CheckMultiVersionAdditionalDecl(
10674 S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
10675 OldDecl, MergeTypeWithPrevious, Previous);
10676}
10677
10678/// Perform semantic checking of a new function declaration.
10679///
10680/// Performs semantic analysis of the new function declaration
10681/// NewFD. This routine performs all semantic checking that does not
10682/// require the actual declarator involved in the declaration, and is
10683/// used both for the declaration of functions as they are parsed
10684/// (called via ActOnDeclarator) and for the declaration of functions
10685/// that have been instantiated via C++ template instantiation (called
10686/// via InstantiateDecl).
10687///
10688/// \param IsMemberSpecialization whether this new function declaration is
10689/// a member specialization (that replaces any definition provided by the
10690/// previous declaration).
10691///
10692/// This sets NewFD->isInvalidDecl() to true if there was an error.
10693///
10694/// \returns true if the function declaration is a redeclaration.
10695bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10696 LookupResult &Previous,
10697 bool IsMemberSpecialization) {
10698 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&((!NewFD->getReturnType()->isVariablyModifiedType() &&
"Variably modified return types are not handled here") ? static_cast
<void> (0) : __assert_fail ("!NewFD->getReturnType()->isVariablyModifiedType() && \"Variably modified return types are not handled here\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 10699, __PRETTY_FUNCTION__))
10699 "Variably modified return types are not handled here")((!NewFD->getReturnType()->isVariablyModifiedType() &&
"Variably modified return types are not handled here") ? static_cast
<void> (0) : __assert_fail ("!NewFD->getReturnType()->isVariablyModifiedType() && \"Variably modified return types are not handled here\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 10699, __PRETTY_FUNCTION__))
;
10700
10701 // Determine whether the type of this function should be merged with
10702 // a previous visible declaration. This never happens for functions in C++,
10703 // and always happens in C if the previous declaration was visible.
10704 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10705 !Previous.isShadowed();
10706
10707 bool Redeclaration = false;
10708 NamedDecl *OldDecl = nullptr;
10709 bool MayNeedOverloadableChecks = false;
10710
10711 // Merge or overload the declaration with an existing declaration of
10712 // the same name, if appropriate.
10713 if (!Previous.empty()) {
10714 // Determine whether NewFD is an overload of PrevDecl or
10715 // a declaration that requires merging. If it's an overload,
10716 // there's no more work to do here; we'll just add the new
10717 // function to the scope.
10718 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10719 NamedDecl *Candidate = Previous.getRepresentativeDecl();
10720 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10721 Redeclaration = true;
10722 OldDecl = Candidate;
10723 }
10724 } else {
10725 MayNeedOverloadableChecks = true;
10726 switch (CheckOverload(S, NewFD, Previous, OldDecl,
10727 /*NewIsUsingDecl*/ false)) {
10728 case Ovl_Match:
10729 Redeclaration = true;
10730 break;
10731
10732 case Ovl_NonFunction:
10733 Redeclaration = true;
10734 break;
10735
10736 case Ovl_Overload:
10737 Redeclaration = false;
10738 break;
10739 }
10740 }
10741 }
10742
10743 // Check for a previous extern "C" declaration with this name.
10744 if (!Redeclaration &&
10745 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10746 if (!Previous.empty()) {
10747 // This is an extern "C" declaration with the same name as a previous
10748 // declaration, and thus redeclares that entity...
10749 Redeclaration = true;
10750 OldDecl = Previous.getFoundDecl();
10751 MergeTypeWithPrevious = false;
10752
10753 // ... except in the presence of __attribute__((overloadable)).
10754 if (OldDecl->hasAttr<OverloadableAttr>() ||
10755 NewFD->hasAttr<OverloadableAttr>()) {
10756 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10757 MayNeedOverloadableChecks = true;
10758 Redeclaration = false;
10759 OldDecl = nullptr;
10760 }
10761 }
10762 }
10763 }
10764
10765 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10766 MergeTypeWithPrevious, Previous))
10767 return Redeclaration;
10768
10769 // PPC MMA non-pointer types are not allowed as function return types.
10770 if (Context.getTargetInfo().getTriple().isPPC64() &&
10771 CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
10772 NewFD->setInvalidDecl();
10773 }
10774
10775 // C++11 [dcl.constexpr]p8:
10776 // A constexpr specifier for a non-static member function that is not
10777 // a constructor declares that member function to be const.
10778 //
10779 // This needs to be delayed until we know whether this is an out-of-line
10780 // definition of a static member function.
10781 //
10782 // This rule is not present in C++1y, so we produce a backwards
10783 // compatibility warning whenever it happens in C++11.
10784 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10785 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10786 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10787 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
10788 CXXMethodDecl *OldMD = nullptr;
10789 if (OldDecl)
10790 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10791 if (!OldMD || !OldMD->isStatic()) {
10792 const FunctionProtoType *FPT =
10793 MD->getType()->castAs<FunctionProtoType>();
10794 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10795 EPI.TypeQuals.addConst();
10796 MD->setType(Context.getFunctionType(FPT->getReturnType(),
10797 FPT->getParamTypes(), EPI));
10798
10799 // Warn that we did this, if we're not performing template instantiation.
10800 // In that case, we'll have warned already when the template was defined.
10801 if (!inTemplateInstantiation()) {
10802 SourceLocation AddConstLoc;
10803 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10804 .IgnoreParens().getAs<FunctionTypeLoc>())
10805 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10806
10807 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10808 << FixItHint::CreateInsertion(AddConstLoc, " const");
10809 }
10810 }
10811 }
10812
10813 if (Redeclaration) {
10814 // NewFD and OldDecl represent declarations that need to be
10815 // merged.
10816 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10817 NewFD->setInvalidDecl();
10818 return Redeclaration;
10819 }
10820
10821 Previous.clear();
10822 Previous.addDecl(OldDecl);
10823
10824 if (FunctionTemplateDecl *OldTemplateDecl =
10825 dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10826 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10827 FunctionTemplateDecl *NewTemplateDecl
10828 = NewFD->getDescribedFunctionTemplate();
10829 assert(NewTemplateDecl && "Template/non-template mismatch")((NewTemplateDecl && "Template/non-template mismatch"
) ? static_cast<void> (0) : __assert_fail ("NewTemplateDecl && \"Template/non-template mismatch\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 10829, __PRETTY_FUNCTION__))
;
10830
10831 // The call to MergeFunctionDecl above may have created some state in
10832 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10833 // can add it as a redeclaration.
10834 NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10835
10836 NewFD->setPreviousDeclaration(OldFD);
10837 if (NewFD->isCXXClassMember()) {
10838 NewFD->setAccess(OldTemplateDecl->getAccess());
10839 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10840 }
10841
10842 // If this is an explicit specialization of a member that is a function
10843 // template, mark it as a member specialization.
10844 if (IsMemberSpecialization &&
10845 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10846 NewTemplateDecl->setMemberSpecialization();
10847 assert(OldTemplateDecl->isMemberSpecialization())((OldTemplateDecl->isMemberSpecialization()) ? static_cast
<void> (0) : __assert_fail ("OldTemplateDecl->isMemberSpecialization()"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 10847, __PRETTY_FUNCTION__))
;
10848 // Explicit specializations of a member template do not inherit deleted
10849 // status from the parent member template that they are specializing.
10850 if (OldFD->isDeleted()) {
10851 // FIXME: This assert will not hold in the presence of modules.
10852 assert(OldFD->getCanonicalDecl() == OldFD)((OldFD->getCanonicalDecl() == OldFD) ? static_cast<void
> (0) : __assert_fail ("OldFD->getCanonicalDecl() == OldFD"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 10852, __PRETTY_FUNCTION__))
;
10853 // FIXME: We need an update record for this AST mutation.
10854 OldFD->setDeletedAsWritten(false);
10855 }
10856 }
10857
10858 } else {
10859 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10860 auto *OldFD = cast<FunctionDecl>(OldDecl);
10861 // This needs to happen first so that 'inline' propagates.
10862 NewFD->setPreviousDeclaration(OldFD);
10863 if (NewFD->isCXXClassMember())
10864 NewFD->setAccess(OldFD->getAccess());
10865 }
10866 }
10867 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10868 !NewFD->getAttr<OverloadableAttr>()) {
10869 assert((Previous.empty() ||(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl
*ND) { return ND->hasAttr<OverloadableAttr>(); })) &&
"Non-redecls shouldn't happen without overloadable present")
? static_cast<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-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 10874, __PRETTY_FUNCTION__))
10870 llvm::any_of(Previous,(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl
*ND) { return ND->hasAttr<OverloadableAttr>(); })) &&
"Non-redecls shouldn't happen without overloadable present")
? static_cast<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-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 10874, __PRETTY_FUNCTION__))
10871 [](const NamedDecl *ND) {(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl
*ND) { return ND->hasAttr<OverloadableAttr>(); })) &&
"Non-redecls shouldn't happen without overloadable present")
? static_cast<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-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 10874, __PRETTY_FUNCTION__))
10872 return ND->hasAttr<OverloadableAttr>();(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl
*ND) { return ND->hasAttr<OverloadableAttr>(); })) &&
"Non-redecls shouldn't happen without overloadable present")
? static_cast<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-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 10874, __PRETTY_FUNCTION__))
10873 })) &&(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl
*ND) { return ND->hasAttr<OverloadableAttr>(); })) &&
"Non-redecls shouldn't happen without overloadable present")
? static_cast<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-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 10874, __PRETTY_FUNCTION__))
10874 "Non-redecls shouldn't happen without overloadable present")(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl
*ND) { return ND->hasAttr<OverloadableAttr>(); })) &&
"Non-redecls shouldn't happen without overloadable present")
? static_cast<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-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 10874, __PRETTY_FUNCTION__))
;
10875
10876 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10877 const auto *FD = dyn_cast<FunctionDecl>(ND);
10878 return FD && !FD->hasAttr<OverloadableAttr>();
10879 });
10880
10881 if (OtherUnmarkedIter != Previous.end()) {
10882 Diag(NewFD->getLocation(),
10883 diag::err_attribute_overloadable_multiple_unmarked_overloads);
10884 Diag((*OtherUnmarkedIter)->getLocation(),
10885 diag::note_attribute_overloadable_prev_overload)
10886 << false;
10887
10888 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10889 }
10890 }
10891
10892 if (LangOpts.OpenMP)
10893 ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
10894
10895 // Semantic checking for this function declaration (in isolation).
10896
10897 if (getLangOpts().CPlusPlus) {
10898 // C++-specific checks.
10899 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10900 CheckConstructor(Constructor);
10901 } else if (CXXDestructorDecl *Destructor =
10902 dyn_cast<CXXDestructorDecl>(NewFD)) {
10903 CXXRecordDecl *Record = Destructor->getParent();
10904 QualType ClassType = Context.getTypeDeclType(Record);
10905
10906 // FIXME: Shouldn't we be able to perform this check even when the class
10907 // type is dependent? Both gcc and edg can handle that.
10908 if (!ClassType->isDependentType()) {
10909 DeclarationName Name
10910 = Context.DeclarationNames.getCXXDestructorName(
10911 Context.getCanonicalType(ClassType));
10912 if (NewFD->getDeclName() != Name) {
10913 Diag(NewFD->getLocation(), diag::err_destructor_name);
10914 NewFD->setInvalidDecl();
10915 return Redeclaration;
10916 }
10917 }
10918 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10919 if (auto *TD = Guide->getDescribedFunctionTemplate())
10920 CheckDeductionGuideTemplate(TD);
10921
10922 // A deduction guide is not on the list of entities that can be
10923 // explicitly specialized.
10924 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10925 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
10926 << /*explicit specialization*/ 1;
10927 }
10928
10929 // Find any virtual functions that this function overrides.
10930 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10931 if (!Method->isFunctionTemplateSpecialization() &&
10932 !Method->getDescribedFunctionTemplate() &&
10933 Method->isCanonicalDecl()) {
10934 AddOverriddenMethods(Method->getParent(), Method);
10935 }
10936 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
10937 // C++2a [class.virtual]p6
10938 // A virtual method shall not have a requires-clause.
10939 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
10940 diag::err_constrained_virtual_method);
10941
10942 if (Method->isStatic())
10943 checkThisInStaticMemberFunctionType(Method);
10944 }
10945
10946 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
10947 ActOnConversionDeclarator(Conversion);
10948
10949 // Extra checking for C++ overloaded operators (C++ [over.oper]).
10950 if (NewFD->isOverloadedOperator() &&
10951 CheckOverloadedOperatorDeclaration(NewFD)) {
10952 NewFD->setInvalidDecl();
10953 return Redeclaration;
10954 }
10955
10956 // Extra checking for C++0x literal operators (C++0x [over.literal]).
10957 if (NewFD->getLiteralIdentifier() &&
10958 CheckLiteralOperatorDeclaration(NewFD)) {
10959 NewFD->setInvalidDecl();
10960 return Redeclaration;
10961 }
10962
10963 // In C++, check default arguments now that we have merged decls. Unless
10964 // the lexical context is the class, because in this case this is done
10965 // during delayed parsing anyway.
10966 if (!CurContext->isRecord())
10967 CheckCXXDefaultArguments(NewFD);
10968
10969 // If this function is declared as being extern "C", then check to see if
10970 // the function returns a UDT (class, struct, or union type) that is not C
10971 // compatible, and if it does, warn the user.
10972 // But, issue any diagnostic on the first declaration only.
10973 if (Previous.empty() && NewFD->isExternC()) {
10974 QualType R = NewFD->getReturnType();
10975 if (R->isIncompleteType() && !R->isVoidType())
10976 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
10977 << NewFD << R;
10978 else if (!R.isPODType(Context) && !R->isVoidType() &&
10979 !R->isObjCObjectPointerType())
10980 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
10981 }
10982
10983 // C++1z [dcl.fct]p6:
10984 // [...] whether the function has a non-throwing exception-specification
10985 // [is] part of the function type
10986 //
10987 // This results in an ABI break between C++14 and C++17 for functions whose
10988 // declared type includes an exception-specification in a parameter or
10989 // return type. (Exception specifications on the function itself are OK in
10990 // most cases, and exception specifications are not permitted in most other
10991 // contexts where they could make it into a mangling.)
10992 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
10993 auto HasNoexcept = [&](QualType T) -> bool {
10994 // Strip off declarator chunks that could be between us and a function
10995 // type. We don't need to look far, exception specifications are very
10996 // restricted prior to C++17.
10997 if (auto *RT = T->getAs<ReferenceType>())
10998 T = RT->getPointeeType();
10999 else if (T->isAnyPointerType())
11000 T = T->getPointeeType();
11001 else if (auto *MPT = T->getAs<MemberPointerType>())
11002 T = MPT->getPointeeType();
11003 if (auto *FPT = T->getAs<FunctionProtoType>())
11004 if (FPT->isNothrow())
11005 return true;
11006 return false;
11007 };
11008
11009 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
11010 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
11011 for (QualType T : FPT->param_types())
11012 AnyNoexcept |= HasNoexcept(T);
11013 if (AnyNoexcept)
11014 Diag(NewFD->getLocation(),
11015 diag::warn_cxx17_compat_exception_spec_in_signature)
11016 << NewFD;
11017 }
11018
11019 if (!Redeclaration && LangOpts.CUDA)
11020 checkCUDATargetOverload(NewFD, Previous);
11021 }
11022 return Redeclaration;
11023}
11024
11025void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
11026 // C++11 [basic.start.main]p3:
11027 // A program that [...] declares main to be inline, static or
11028 // constexpr is ill-formed.
11029 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
11030 // appear in a declaration of main.
11031 // static main is not an error under C99, but we should warn about it.
11032 // We accept _Noreturn main as an extension.
11033 if (FD->getStorageClass() == SC_Static)
11034 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
11035 ? diag::err_static_main : diag::warn_static_main)
11036 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
11037 if (FD->isInlineSpecified())
11038 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
11039 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
11040 if (DS.isNoreturnSpecified()) {
11041 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
11042 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
11043 Diag(NoreturnLoc, diag::ext_noreturn_main);
11044 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
11045 << FixItHint::CreateRemoval(NoreturnRange);
11046 }
11047 if (FD->isConstexpr()) {
11048 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
11049 << FD->isConsteval()
11050 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
11051 FD->setConstexprKind(ConstexprSpecKind::Unspecified);
11052 }
11053
11054 if (getLangOpts().OpenCL) {
11055 Diag(FD->getLocation(), diag::err_opencl_no_main)
11056 << FD->hasAttr<OpenCLKernelAttr>();
11057 FD->setInvalidDecl();
11058 return;
11059 }
11060
11061 QualType T = FD->getType();
11062 assert(T->isFunctionType() && "function decl is not of function type")((T->isFunctionType() && "function decl is not of function type"
) ? static_cast<void> (0) : __assert_fail ("T->isFunctionType() && \"function decl is not of function type\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 11062, __PRETTY_FUNCTION__))
;
11063 const FunctionType* FT = T->castAs<FunctionType>();
11064
11065 // Set default calling convention for main()
11066 if (FT->getCallConv() != CC_C) {
11067 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
11068 FD->setType(QualType(FT, 0));
11069 T = Context.getCanonicalType(FD->getType());
11070 }
11071
11072 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
11073 // In C with GNU extensions we allow main() to have non-integer return
11074 // type, but we should warn about the extension, and we disable the
11075 // implicit-return-zero rule.
11076
11077 // GCC in C mode accepts qualified 'int'.
11078 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
11079 FD->setHasImplicitReturnZero(true);
11080 else {
11081 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
11082 SourceRange RTRange = FD->getReturnTypeSourceRange();
11083 if (RTRange.isValid())
11084 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
11085 << FixItHint::CreateReplacement(RTRange, "int");
11086 }
11087 } else {
11088 // In C and C++, main magically returns 0 if you fall off the end;
11089 // set the flag which tells us that.
11090 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
11091
11092 // All the standards say that main() should return 'int'.
11093 if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
11094 FD->setHasImplicitReturnZero(true);
11095 else {
11096 // Otherwise, this is just a flat-out error.
11097 SourceRange RTRange = FD->getReturnTypeSourceRange();
11098 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
11099 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
11100 : FixItHint());
11101 FD->setInvalidDecl(true);
11102 }
11103 }
11104
11105 // Treat protoless main() as nullary.
11106 if (isa<FunctionNoProtoType>(FT)) return;
11107
11108 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
11109 unsigned nparams = FTP->getNumParams();
11110 assert(FD->getNumParams() == nparams)((FD->getNumParams() == nparams) ? static_cast<void>
(0) : __assert_fail ("FD->getNumParams() == nparams", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 11110, __PRETTY_FUNCTION__))
;
11111
11112 bool HasExtraParameters = (nparams > 3);
11113
11114 if (FTP->isVariadic()) {
11115 Diag(FD->getLocation(), diag::ext_variadic_main);
11116 // FIXME: if we had information about the location of the ellipsis, we
11117 // could add a FixIt hint to remove it as a parameter.
11118 }
11119
11120 // Darwin passes an undocumented fourth argument of type char**. If
11121 // other platforms start sprouting these, the logic below will start
11122 // getting shifty.
11123 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
11124 HasExtraParameters = false;
11125
11126 if (HasExtraParameters) {
11127 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
11128 FD->setInvalidDecl(true);
11129 nparams = 3;
11130 }
11131
11132 // FIXME: a lot of the following diagnostics would be improved
11133 // if we had some location information about types.
11134
11135 QualType CharPP =
11136 Context.getPointerType(Context.getPointerType(Context.CharTy));
11137 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
11138
11139 for (unsigned i = 0; i < nparams; ++i) {
11140 QualType AT = FTP->getParamType(i);
11141
11142 bool mismatch = true;
11143
11144 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
11145 mismatch = false;
11146 else if (Expected[i] == CharPP) {
11147 // As an extension, the following forms are okay:
11148 // char const **
11149 // char const * const *
11150 // char * const *
11151
11152 QualifierCollector qs;
11153 const PointerType* PT;
11154 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
11155 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
11156 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
11157 Context.CharTy)) {
11158 qs.removeConst();
11159 mismatch = !qs.empty();
11160 }
11161 }
11162
11163 if (mismatch) {
11164 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
11165 // TODO: suggest replacing given type with expected type
11166 FD->setInvalidDecl(true);
11167 }
11168 }
11169
11170 if (nparams == 1 && !FD->isInvalidDecl()) {
11171 Diag(FD->getLocation(), diag::warn_main_one_arg);
11172 }
11173
11174 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11175 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11176 FD->setInvalidDecl();
11177 }
11178}
11179
11180static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
11181
11182 // Default calling convention for main and wmain is __cdecl
11183 if (FD->getName() == "main" || FD->getName() == "wmain")
11184 return false;
11185
11186 // Default calling convention for MinGW is __cdecl
11187 const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
11188 if (T.isWindowsGNUEnvironment())
11189 return false;
11190
11191 // Default calling convention for WinMain, wWinMain and DllMain
11192 // is __stdcall on 32 bit Windows
11193 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
11194 return true;
11195
11196 return false;
11197}
11198
11199void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
11200 QualType T = FD->getType();
11201 assert(T->isFunctionType() && "function decl is not of function type")((T->isFunctionType() && "function decl is not of function type"
) ? static_cast<void> (0) : __assert_fail ("T->isFunctionType() && \"function decl is not of function type\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 11201, __PRETTY_FUNCTION__))
;
11202 const FunctionType *FT = T->castAs<FunctionType>();
11203
11204 // Set an implicit return of 'zero' if the function can return some integral,
11205 // enumeration, pointer or nullptr type.
11206 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
11207 FT->getReturnType()->isAnyPointerType() ||
11208 FT->getReturnType()->isNullPtrType())
11209 // DllMain is exempt because a return value of zero means it failed.
11210 if (FD->getName() != "DllMain")
11211 FD->setHasImplicitReturnZero(true);
11212
11213 // Explicity specified calling conventions are applied to MSVC entry points
11214 if (!hasExplicitCallingConv(T)) {
11215 if (isDefaultStdCall(FD, *this)) {
11216 if (FT->getCallConv() != CC_X86StdCall) {
11217 FT = Context.adjustFunctionType(
11218 FT, FT->getExtInfo().withCallingConv(CC_X86StdCall));
11219 FD->setType(QualType(FT, 0));
11220 }
11221 } else if (FT->getCallConv() != CC_C) {
11222 FT = Context.adjustFunctionType(FT,
11223 FT->getExtInfo().withCallingConv(CC_C));
11224 FD->setType(QualType(FT, 0));
11225 }
11226 }
11227
11228 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11229 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11230 FD->setInvalidDecl();
11231 }
11232}
11233
11234bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
11235 // FIXME: Need strict checking. In C89, we need to check for
11236 // any assignment, increment, decrement, function-calls, or
11237 // commas outside of a sizeof. In C99, it's the same list,
11238 // except that the aforementioned are allowed in unevaluated
11239 // expressions. Everything else falls under the
11240 // "may accept other forms of constant expressions" exception.
11241 //
11242 // Regular C++ code will not end up here (exceptions: language extensions,
11243 // OpenCL C++ etc), so the constant expression rules there don't matter.
11244 if (Init->isValueDependent()) {
11245 assert(Init->containsErrors() &&((Init->containsErrors() && "Dependent code should only occur in error-recovery path."
) ? static_cast<void> (0) : __assert_fail ("Init->containsErrors() && \"Dependent code should only occur in error-recovery path.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 11246, __PRETTY_FUNCTION__))
11246 "Dependent code should only occur in error-recovery path.")((Init->containsErrors() && "Dependent code should only occur in error-recovery path."
) ? static_cast<void> (0) : __assert_fail ("Init->containsErrors() && \"Dependent code should only occur in error-recovery path.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 11246, __PRETTY_FUNCTION__))
;
11247 return true;
11248 }
11249 const Expr *Culprit;
11250 if (Init->isConstantInitializer(Context, false, &Culprit))
11251 return false;
11252 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
11253 << Culprit->getSourceRange();
11254 return true;
11255}
11256
11257namespace {
11258 // Visits an initialization expression to see if OrigDecl is evaluated in
11259 // its own initialization and throws a warning if it does.
11260 class SelfReferenceChecker
11261 : public EvaluatedExprVisitor<SelfReferenceChecker> {
11262 Sema &S;
11263 Decl *OrigDecl;
11264 bool isRecordType;
11265 bool isPODType;
11266 bool isReferenceType;
11267
11268 bool isInitList;
11269 llvm::SmallVector<unsigned, 4> InitFieldIndex;
11270
11271 public:
11272 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
11273
11274 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
11275 S(S), OrigDecl(OrigDecl) {
11276 isPODType = false;
11277 isRecordType = false;
11278 isReferenceType = false;
11279 isInitList = false;
11280 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
11281 isPODType = VD->getType().isPODType(S.Context);
11282 isRecordType = VD->getType()->isRecordType();
11283 isReferenceType = VD->getType()->isReferenceType();
11284 }
11285 }
11286
11287 // For most expressions, just call the visitor. For initializer lists,
11288 // track the index of the field being initialized since fields are
11289 // initialized in order allowing use of previously initialized fields.
11290 void CheckExpr(Expr *E) {
11291 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
11292 if (!InitList) {
11293 Visit(E);
11294 return;
11295 }
11296
11297 // Track and increment the index here.
11298 isInitList = true;
11299 InitFieldIndex.push_back(0);
11300 for (auto Child : InitList->children()) {
11301 CheckExpr(cast<Expr>(Child));
11302 ++InitFieldIndex.back();
11303 }
11304 InitFieldIndex.pop_back();
11305 }
11306
11307 // Returns true if MemberExpr is checked and no further checking is needed.
11308 // Returns false if additional checking is required.
11309 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
11310 llvm::SmallVector<FieldDecl*, 4> Fields;
11311 Expr *Base = E;
11312 bool ReferenceField = false;
11313
11314 // Get the field members used.
11315 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11316 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
11317 if (!FD)
11318 return false;
11319 Fields.push_back(FD);
11320 if (FD->getType()->isReferenceType())
11321 ReferenceField = true;
11322 Base = ME->getBase()->IgnoreParenImpCasts();
11323 }
11324
11325 // Keep checking only if the base Decl is the same.
11326 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
11327 if (!DRE || DRE->getDecl() != OrigDecl)
11328 return false;
11329
11330 // A reference field can be bound to an unininitialized field.
11331 if (CheckReference && !ReferenceField)
11332 return true;
11333
11334 // Convert FieldDecls to their index number.
11335 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
11336 for (const FieldDecl *I : llvm::reverse(Fields))
11337 UsedFieldIndex.push_back(I->getFieldIndex());
11338
11339 // See if a warning is needed by checking the first difference in index
11340 // numbers. If field being used has index less than the field being
11341 // initialized, then the use is safe.
11342 for (auto UsedIter = UsedFieldIndex.begin(),
11343 UsedEnd = UsedFieldIndex.end(),
11344 OrigIter = InitFieldIndex.begin(),
11345 OrigEnd = InitFieldIndex.end();
11346 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
11347 if (*UsedIter < *OrigIter)
11348 return true;
11349 if (*UsedIter > *OrigIter)
11350 break;
11351 }
11352
11353 // TODO: Add a different warning which will print the field names.
11354 HandleDeclRefExpr(DRE);
11355 return true;
11356 }
11357
11358 // For most expressions, the cast is directly above the DeclRefExpr.
11359 // For conditional operators, the cast can be outside the conditional
11360 // operator if both expressions are DeclRefExpr's.
11361 void HandleValue(Expr *E) {
11362 E = E->IgnoreParens();
11363 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11364 HandleDeclRefExpr(DRE);
11365 return;
11366 }
11367
11368 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11369 Visit(CO->getCond());
11370 HandleValue(CO->getTrueExpr());
11371 HandleValue(CO->getFalseExpr());
11372 return;
11373 }
11374
11375 if (BinaryConditionalOperator *BCO =
11376 dyn_cast<BinaryConditionalOperator>(E)) {
11377 Visit(BCO->getCond());
11378 HandleValue(BCO->getFalseExpr());
11379 return;
11380 }
11381
11382 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11383 HandleValue(OVE->getSourceExpr());
11384 return;
11385 }
11386
11387 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11388 if (BO->getOpcode() == BO_Comma) {
11389 Visit(BO->getLHS());
11390 HandleValue(BO->getRHS());
11391 return;
11392 }
11393 }
11394
11395 if (isa<MemberExpr>(E)) {
11396 if (isInitList) {
11397 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11398 false /*CheckReference*/))
11399 return;
11400 }
11401
11402 Expr *Base = E->IgnoreParenImpCasts();
11403 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11404 // Check for static member variables and don't warn on them.
11405 if (!isa<FieldDecl>(ME->getMemberDecl()))
11406 return;
11407 Base = ME->getBase()->IgnoreParenImpCasts();
11408 }
11409 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11410 HandleDeclRefExpr(DRE);
11411 return;
11412 }
11413
11414 Visit(E);
11415 }
11416
11417 // Reference types not handled in HandleValue are handled here since all
11418 // uses of references are bad, not just r-value uses.
11419 void VisitDeclRefExpr(DeclRefExpr *E) {
11420 if (isReferenceType)
11421 HandleDeclRefExpr(E);
11422 }
11423
11424 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11425 if (E->getCastKind() == CK_LValueToRValue) {
11426 HandleValue(E->getSubExpr());
11427 return;
11428 }
11429
11430 Inherited::VisitImplicitCastExpr(E);
11431 }
11432
11433 void VisitMemberExpr(MemberExpr *E) {
11434 if (isInitList) {
11435 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11436 return;
11437 }
11438
11439 // Don't warn on arrays since they can be treated as pointers.
11440 if (E->getType()->canDecayToPointerType()) return;
11441
11442 // Warn when a non-static method call is followed by non-static member
11443 // field accesses, which is followed by a DeclRefExpr.
11444 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11445 bool Warn = (MD && !MD->isStatic());
11446 Expr *Base = E->getBase()->IgnoreParenImpCasts();
11447 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11448 if (!isa<FieldDecl>(ME->getMemberDecl()))
11449 Warn = false;
11450 Base = ME->getBase()->IgnoreParenImpCasts();
11451 }
11452
11453 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11454 if (Warn)
11455 HandleDeclRefExpr(DRE);
11456 return;
11457 }
11458
11459 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11460 // Visit that expression.
11461 Visit(Base);
11462 }
11463
11464 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11465 Expr *Callee = E->getCallee();
11466
11467 if (isa<UnresolvedLookupExpr>(Callee))
11468 return Inherited::VisitCXXOperatorCallExpr(E);
11469
11470 Visit(Callee);
11471 for (auto Arg: E->arguments())
11472 HandleValue(Arg->IgnoreParenImpCasts());
11473 }
11474
11475 void VisitUnaryOperator(UnaryOperator *E) {
11476 // For POD record types, addresses of its own members are well-defined.
11477 if (E->getOpcode() == UO_AddrOf && isRecordType &&
11478 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11479 if (!isPODType)
11480 HandleValue(E->getSubExpr());
11481 return;
11482 }
11483
11484 if (E->isIncrementDecrementOp()) {
11485 HandleValue(E->getSubExpr());
11486 return;
11487 }
11488
11489 Inherited::VisitUnaryOperator(E);
11490 }
11491
11492 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11493
11494 void VisitCXXConstructExpr(CXXConstructExpr *E) {
11495 if (E->getConstructor()->isCopyConstructor()) {
11496 Expr *ArgExpr = E->getArg(0);
11497 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11498 if (ILE->getNumInits() == 1)
11499 ArgExpr = ILE->getInit(0);
11500 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11501 if (ICE->getCastKind() == CK_NoOp)
11502 ArgExpr = ICE->getSubExpr();
11503 HandleValue(ArgExpr);
11504 return;
11505 }
11506 Inherited::VisitCXXConstructExpr(E);
11507 }
11508
11509 void VisitCallExpr(CallExpr *E) {
11510 // Treat std::move as a use.
11511 if (E->isCallToStdMove()) {
11512 HandleValue(E->getArg(0));
11513 return;
11514 }
11515
11516 Inherited::VisitCallExpr(E);
11517 }
11518
11519 void VisitBinaryOperator(BinaryOperator *E) {
11520 if (E->isCompoundAssignmentOp()) {
11521 HandleValue(E->getLHS());
11522 Visit(E->getRHS());
11523 return;
11524 }
11525
11526 Inherited::VisitBinaryOperator(E);
11527 }
11528
11529 // A custom visitor for BinaryConditionalOperator is needed because the
11530 // regular visitor would check the condition and true expression separately
11531 // but both point to the same place giving duplicate diagnostics.
11532 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11533 Visit(E->getCond());
11534 Visit(E->getFalseExpr());
11535 }
11536
11537 void HandleDeclRefExpr(DeclRefExpr *DRE) {
11538 Decl* ReferenceDecl = DRE->getDecl();
11539 if (OrigDecl != ReferenceDecl) return;
11540 unsigned diag;
11541 if (isReferenceType) {
11542 diag = diag::warn_uninit_self_reference_in_reference_init;
11543 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11544 diag = diag::warn_static_self_reference_in_init;
11545 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11546 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11547 DRE->getDecl()->getType()->isRecordType()) {
11548 diag = diag::warn_uninit_self_reference_in_init;
11549 } else {
11550 // Local variables will be handled by the CFG analysis.
11551 return;
11552 }
11553
11554 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11555 S.PDiag(diag)
11556 << DRE->getDecl() << OrigDecl->getLocation()
11557 << DRE->getSourceRange());
11558 }
11559 };
11560
11561 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
11562 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11563 bool DirectInit) {
11564 // Parameters arguments are occassionially constructed with itself,
11565 // for instance, in recursive functions. Skip them.
11566 if (isa<ParmVarDecl>(OrigDecl))
11567 return;
11568
11569 E = E->IgnoreParens();
11570
11571 // Skip checking T a = a where T is not a record or reference type.
11572 // Doing so is a way to silence uninitialized warnings.
11573 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11574 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11575 if (ICE->getCastKind() == CK_LValueToRValue)
11576 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11577 if (DRE->getDecl() == OrigDecl)
11578 return;
11579
11580 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11581 }
11582} // end anonymous namespace
11583
11584namespace {
11585 // Simple wrapper to add the name of a variable or (if no variable is
11586 // available) a DeclarationName into a diagnostic.
11587 struct VarDeclOrName {
11588 VarDecl *VDecl;
11589 DeclarationName Name;
11590
11591 friend const Sema::SemaDiagnosticBuilder &
11592 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11593 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11594 }
11595 };
11596} // end anonymous namespace
11597
11598QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11599 DeclarationName Name, QualType Type,
11600 TypeSourceInfo *TSI,
11601 SourceRange Range, bool DirectInit,
11602 Expr *Init) {
11603 bool IsInitCapture = !VDecl;
11604 assert((!VDecl || !VDecl->isInitCapture()) &&(((!VDecl || !VDecl->isInitCapture()) && "init captures are expected to be deduced prior to initialization"
) ? static_cast<void> (0) : __assert_fail ("(!VDecl || !VDecl->isInitCapture()) && \"init captures are expected to be deduced prior to initialization\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 11605, __PRETTY_FUNCTION__))
11605 "init captures are expected to be deduced prior to initialization")(((!VDecl || !VDecl->isInitCapture()) && "init captures are expected to be deduced prior to initialization"
) ? static_cast<void> (0) : __assert_fail ("(!VDecl || !VDecl->isInitCapture()) && \"init captures are expected to be deduced prior to initialization\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 11605, __PRETTY_FUNCTION__))
;
11606
11607 VarDeclOrName VN{VDecl, Name};
11608
11609 DeducedType *Deduced = Type->getContainedDeducedType();
11610 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type")((Deduced && "deduceVarTypeFromInitializer for non-deduced type"
) ? static_cast<void> (0) : __assert_fail ("Deduced && \"deduceVarTypeFromInitializer for non-deduced type\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 11610, __PRETTY_FUNCTION__))
;
11611
11612 // C++11 [dcl.spec.auto]p3
11613 if (!Init) {
11614 assert(VDecl && "no init for init capture deduction?")((VDecl && "no init for init capture deduction?") ? static_cast
<void> (0) : __assert_fail ("VDecl && \"no init for init capture deduction?\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 11614, __PRETTY_FUNCTION__))
;
11615
11616 // Except for class argument deduction, and then for an initializing
11617 // declaration only, i.e. no static at class scope or extern.
11618 if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11619 VDecl->hasExternalStorage() ||
11620 VDecl->isStaticDataMember()) {
11621 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11622 << VDecl->getDeclName() << Type;
11623 return QualType();
11624 }
11625 }
11626
11627 ArrayRef<Expr*> DeduceInits;
11628 if (Init)
11629 DeduceInits = Init;
11630
11631 if (DirectInit) {
11632 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
11633 DeduceInits = PL->exprs();
11634 }
11635
11636 if (isa<DeducedTemplateSpecializationType>(Deduced)) {
11637 assert(VDecl && "non-auto type for init capture deduction?")((VDecl && "non-auto type for init capture deduction?"
) ? static_cast<void> (0) : __assert_fail ("VDecl && \"non-auto type for init capture deduction?\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 11637, __PRETTY_FUNCTION__))
;
11638 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11639 InitializationKind Kind = InitializationKind::CreateForInit(
11640 VDecl->getLocation(), DirectInit, Init);
11641 // FIXME: Initialization should not be taking a mutable list of inits.
11642 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
11643 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
11644 InitsCopy);
11645 }
11646
11647 if (DirectInit) {
11648 if (auto *IL = dyn_cast<InitListExpr>(Init))
11649 DeduceInits = IL->inits();
11650 }
11651
11652 // Deduction only works if we have exactly one source expression.
11653 if (DeduceInits.empty()) {
11654 // It isn't possible to write this directly, but it is possible to
11655 // end up in this situation with "auto x(some_pack...);"
11656 Diag(Init->getBeginLoc(), IsInitCapture
11657 ? diag::err_init_capture_no_expression
11658 : diag::err_auto_var_init_no_expression)
11659 << VN << Type << Range;
11660 return QualType();
11661 }
11662
11663 if (DeduceInits.size() > 1) {
11664 Diag(DeduceInits[1]->getBeginLoc(),
11665 IsInitCapture ? diag::err_init_capture_multiple_expressions
11666 : diag::err_auto_var_init_multiple_expressions)
11667 << VN << Type << Range;
11668 return QualType();
11669 }
11670
11671 Expr *DeduceInit = DeduceInits[0];
11672 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11673 Diag(Init->getBeginLoc(), IsInitCapture
11674 ? diag::err_init_capture_paren_braces
11675 : diag::err_auto_var_init_paren_braces)
11676 << isa<InitListExpr>(Init) << VN << Type << Range;
11677 return QualType();
11678 }
11679
11680 // Expressions default to 'id' when we're in a debugger.
11681 bool DefaultedAnyToId = false;
11682 if (getLangOpts().DebuggerCastResultToId &&
11683 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11684 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11685 if (Result.isInvalid()) {
11686 return QualType();
11687 }
11688 Init = Result.get();
11689 DefaultedAnyToId = true;
11690 }
11691
11692 // C++ [dcl.decomp]p1:
11693 // If the assignment-expression [...] has array type A and no ref-qualifier
11694 // is present, e has type cv A
11695 if (VDecl && isa<DecompositionDecl>(VDecl) &&
11696 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11697 DeduceInit->getType()->isConstantArrayType())
11698 return Context.getQualifiedType(DeduceInit->getType(),
11699 Type.getQualifiers());
11700
11701 QualType DeducedType;
11702 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11703 if (!IsInitCapture)
11704 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11705 else if (isa<InitListExpr>(Init))
11706 Diag(Range.getBegin(),
11707 diag::err_init_capture_deduction_failure_from_init_list)
11708 << VN
11709 << (DeduceInit->getType().isNull() ? TSI->getType()
11710 : DeduceInit->getType())
11711 << DeduceInit->getSourceRange();
11712 else
11713 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11714 << VN << TSI->getType()
11715 << (DeduceInit->getType().isNull() ? TSI->getType()
11716 : DeduceInit->getType())
11717 << DeduceInit->getSourceRange();
11718 }
11719
11720 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11721 // 'id' instead of a specific object type prevents most of our usual
11722 // checks.
11723 // We only want to warn outside of template instantiations, though:
11724 // inside a template, the 'id' could have come from a parameter.
11725 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11726 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11727 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11728 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11729 }
11730
11731 return DeducedType;
11732}
11733
11734bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11735 Expr *Init) {
11736 assert(!Init || !Init->containsErrors())((!Init || !Init->containsErrors()) ? static_cast<void>
(0) : __assert_fail ("!Init || !Init->containsErrors()", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 11736, __PRETTY_FUNCTION__))
;
11737 QualType DeducedType = deduceVarTypeFromInitializer(
11738 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11739 VDecl->getSourceRange(), DirectInit, Init);
11740 if (DeducedType.isNull()) {
11741 VDecl->setInvalidDecl();
11742 return true;
11743 }
11744
11745 VDecl->setType(DeducedType);
11746 assert(VDecl->isLinkageValid())((VDecl->isLinkageValid()) ? static_cast<void> (0) :
__assert_fail ("VDecl->isLinkageValid()", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 11746, __PRETTY_FUNCTION__))
;
11747
11748 // In ARC, infer lifetime.
11749 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11750 VDecl->setInvalidDecl();
11751
11752 if (getLangOpts().OpenCL)
11753 deduceOpenCLAddressSpace(VDecl);
11754
11755 // If this is a redeclaration, check that the type we just deduced matches
11756 // the previously declared type.
11757 if (VarDecl *Old = VDecl->getPreviousDecl()) {
11758 // We never need to merge the type, because we cannot form an incomplete
11759 // array of auto, nor deduce such a type.
11760 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11761 }
11762
11763 // Check the deduced type is valid for a variable declaration.
11764 CheckVariableDeclarationType(VDecl);
11765 return VDecl->isInvalidDecl();
11766}
11767
11768void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
11769 SourceLocation Loc) {
11770 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
11771 Init = EWC->getSubExpr();
11772
11773 if (auto *CE = dyn_cast<ConstantExpr>(Init))
11774 Init = CE->getSubExpr();
11775
11776 QualType InitType = Init->getType();
11777 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||(((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()
|| InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
"shouldn't be called if type doesn't have a non-trivial C struct"
) ? static_cast<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-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 11779, __PRETTY_FUNCTION__))
11778 InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&(((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()
|| InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
"shouldn't be called if type doesn't have a non-trivial C struct"
) ? static_cast<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-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 11779, __PRETTY_FUNCTION__))
11779 "shouldn't be called if type doesn't have a non-trivial C struct")(((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()
|| InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
"shouldn't be called if type doesn't have a non-trivial C struct"
) ? static_cast<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-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 11779, __PRETTY_FUNCTION__))
;
11780 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
11781 for (auto I : ILE->inits()) {
11782 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
11783 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
11784 continue;
11785 SourceLocation SL = I->getExprLoc();
11786 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
11787 }
11788 return;
11789 }
11790
11791 if (isa<ImplicitValueInitExpr>(Init)) {
11792 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11793 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
11794 NTCUK_Init);
11795 } else {
11796 // Assume all other explicit initializers involving copying some existing
11797 // object.
11798 // TODO: ignore any explicit initializers where we can guarantee
11799 // copy-elision.
11800 if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
11801 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
11802 }
11803}
11804
11805namespace {
11806
11807bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
11808 // Ignore unavailable fields. A field can be marked as unavailable explicitly
11809 // in the source code or implicitly by the compiler if it is in a union
11810 // defined in a system header and has non-trivial ObjC ownership
11811 // qualifications. We don't want those fields to participate in determining
11812 // whether the containing union is non-trivial.
11813 return FD->hasAttr<UnavailableAttr>();
11814}
11815
11816struct DiagNonTrivalCUnionDefaultInitializeVisitor
11817 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11818 void> {
11819 using Super =
11820 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11821 void>;
11822
11823 DiagNonTrivalCUnionDefaultInitializeVisitor(
11824 QualType OrigTy, SourceLocation OrigLoc,
11825 Sema::NonTrivialCUnionContext UseContext, Sema &S)
11826 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11827
11828 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
11829 const FieldDecl *FD, bool InNonTrivialUnion) {
11830 if (const auto *AT = S.Context.getAsArrayType(QT))
11831 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11832 InNonTrivialUnion);
11833 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
11834 }
11835
11836 void visitARCStrong(QualType QT, const FieldDecl *FD,
11837 bool InNonTrivialUnion) {
11838 if (InNonTrivialUnion)
11839 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11840 << 1 << 0 << QT << FD->getName();
11841 }
11842
11843 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11844 if (InNonTrivialUnion)
11845 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11846 << 1 << 0 << QT << FD->getName();
11847 }
11848
11849 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11850 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11851 if (RD->isUnion()) {
11852 if (OrigLoc.isValid()) {
11853 bool IsUnion = false;
11854 if (auto *OrigRD = OrigTy->getAsRecordDecl())
11855 IsUnion = OrigRD->isUnion();
11856 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11857 << 0 << OrigTy << IsUnion << UseContext;
11858 // Reset OrigLoc so that this diagnostic is emitted only once.
11859 OrigLoc = SourceLocation();
11860 }
11861 InNonTrivialUnion = true;
11862 }
11863
11864 if (InNonTrivialUnion)
11865 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11866 << 0 << 0 << QT.getUnqualifiedType() << "";
11867
11868 for (const FieldDecl *FD : RD->fields())
11869 if (!shouldIgnoreForRecordTriviality(FD))
11870 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11871 }
11872
11873 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11874
11875 // The non-trivial C union type or the struct/union type that contains a
11876 // non-trivial C union.
11877 QualType OrigTy;
11878 SourceLocation OrigLoc;
11879 Sema::NonTrivialCUnionContext UseContext;
11880 Sema &S;
11881};
11882
11883struct DiagNonTrivalCUnionDestructedTypeVisitor
11884 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
11885 using Super =
11886 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
11887
11888 DiagNonTrivalCUnionDestructedTypeVisitor(
11889 QualType OrigTy, SourceLocation OrigLoc,
11890 Sema::NonTrivialCUnionContext UseContext, Sema &S)
11891 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11892
11893 void visitWithKind(QualType::DestructionKind DK, QualType QT,
11894 const FieldDecl *FD, bool InNonTrivialUnion) {
11895 if (const auto *AT = S.Context.getAsArrayType(QT))
11896 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11897 InNonTrivialUnion);
11898 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
11899 }
11900
11901 void visitARCStrong(QualType QT, const FieldDecl *FD,
11902 bool InNonTrivialUnion) {
11903 if (InNonTrivialUnion)
11904 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11905 << 1 << 1 << QT << FD->getName();
11906 }
11907
11908 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11909 if (InNonTrivialUnion)
11910 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11911 << 1 << 1 << QT << FD->getName();
11912 }
11913
11914 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11915 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11916 if (RD->isUnion()) {
11917 if (OrigLoc.isValid()) {
11918 bool IsUnion = false;
11919 if (auto *OrigRD = OrigTy->getAsRecordDecl())
11920 IsUnion = OrigRD->isUnion();
11921 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11922 << 1 << OrigTy << IsUnion << UseContext;
11923 // Reset OrigLoc so that this diagnostic is emitted only once.
11924 OrigLoc = SourceLocation();
11925 }
11926 InNonTrivialUnion = true;
11927 }
11928
11929 if (InNonTrivialUnion)
11930 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11931 << 0 << 1 << QT.getUnqualifiedType() << "";
11932
11933 for (const FieldDecl *FD : RD->fields())
11934 if (!shouldIgnoreForRecordTriviality(FD))
11935 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11936 }
11937
11938 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11939 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
11940 bool InNonTrivialUnion) {}
11941
11942 // The non-trivial C union type or the struct/union type that contains a
11943 // non-trivial C union.
11944 QualType OrigTy;
11945 SourceLocation OrigLoc;
11946 Sema::NonTrivialCUnionContext UseContext;
11947 Sema &S;
11948};
11949
11950struct DiagNonTrivalCUnionCopyVisitor
11951 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
11952 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
11953
11954 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
11955 Sema::NonTrivialCUnionContext UseContext,
11956 Sema &S)
11957 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11958
11959 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
11960 const FieldDecl *FD, bool InNonTrivialUnion) {
11961 if (const auto *AT = S.Context.getAsArrayType(QT))
11962 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11963 InNonTrivialUnion);
11964 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
11965 }
11966
11967 void visitARCStrong(QualType QT, const FieldDecl *FD,
11968 bool InNonTrivialUnion) {
11969 if (InNonTrivialUnion)
11970 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11971 << 1 << 2 << QT << FD->getName();
11972 }
11973
11974 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11975 if (InNonTrivialUnion)
11976 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11977 << 1 << 2 << QT << FD->getName();
11978 }
11979
11980 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11981 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11982 if (RD->isUnion()) {
11983 if (OrigLoc.isValid()) {
11984 bool IsUnion = false;
11985 if (auto *OrigRD = OrigTy->getAsRecordDecl())
11986 IsUnion = OrigRD->isUnion();
11987 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11988 << 2 << OrigTy << IsUnion << UseContext;
11989 // Reset OrigLoc so that this diagnostic is emitted only once.
11990 OrigLoc = SourceLocation();
11991 }
11992 InNonTrivialUnion = true;
11993 }
11994
11995 if (InNonTrivialUnion)
11996 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11997 << 0 << 2 << QT.getUnqualifiedType() << "";
11998
11999 for (const FieldDecl *FD : RD->fields())
12000 if (!shouldIgnoreForRecordTriviality(FD))
12001 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12002 }
12003
12004 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
12005 const FieldDecl *FD, bool InNonTrivialUnion) {}
12006 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12007 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
12008 bool InNonTrivialUnion) {}
12009
12010 // The non-trivial C union type or the struct/union type that contains a
12011 // non-trivial C union.
12012 QualType OrigTy;
12013 SourceLocation OrigLoc;
12014 Sema::NonTrivialCUnionContext UseContext;
12015 Sema &S;
12016};
12017
12018} // namespace
12019
12020void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
12021 NonTrivialCUnionContext UseContext,
12022 unsigned NonTrivialKind) {
12023 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||(((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT
.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion
()) && "shouldn't be called if type doesn't have a non-trivial C union"
) ? static_cast<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-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 12026, __PRETTY_FUNCTION__))
12024 QT.hasNonTrivialToPrimitiveDestructCUnion() ||(((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT
.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion
()) && "shouldn't be called if type doesn't have a non-trivial C union"
) ? static_cast<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-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 12026, __PRETTY_FUNCTION__))
12025 QT.hasNonTrivialToPrimitiveCopyCUnion()) &&(((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT
.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion
()) && "shouldn't be called if type doesn't have a non-trivial C union"
) ? static_cast<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-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 12026, __PRETTY_FUNCTION__))
12026 "shouldn't be called if type doesn't have a non-trivial C union")(((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT
.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion
()) && "shouldn't be called if type doesn't have a non-trivial C union"
) ? static_cast<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-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 12026, __PRETTY_FUNCTION__))
;
12027
12028 if ((NonTrivialKind & NTCUK_Init) &&
12029 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12030 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
12031 .visit(QT, nullptr, false);
12032 if ((NonTrivialKind & NTCUK_Destruct) &&
12033 QT.hasNonTrivialToPrimitiveDestructCUnion())
12034 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
12035 .visit(QT, nullptr, false);
12036 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
12037 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
12038 .visit(QT, nullptr, false);
12039}
12040
12041/// AddInitializerToDecl - Adds the initializer Init to the
12042/// declaration dcl. If DirectInit is true, this is C++ direct
12043/// initialization rather than copy initialization.
12044void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
12045 // If there is no declaration, there was an error parsing it. Just ignore
12046 // the initializer.
12047 if (!RealDecl || RealDecl->isInvalidDecl()) {
12048 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
12049 return;
12050 }
12051
12052 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
12053 // Pure-specifiers are handled in ActOnPureSpecifier.
12054 Diag(Method->getLocation(), diag::err_member_function_initialization)
12055 << Method->getDeclName() << Init->getSourceRange();
12056 Method->setInvalidDecl();
12057 return;
12058 }
12059
12060 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
12061 if (!VDecl) {
12062 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here")((!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"
) ? static_cast<void> (0) : __assert_fail ("!isa<FieldDecl>(RealDecl) && \"field init shouldn't get here\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 12062, __PRETTY_FUNCTION__))
;
12063 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
12064 RealDecl->setInvalidDecl();
12065 return;
12066 }
12067
12068 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
12069 if (VDecl->getType()->isUndeducedType()) {
12070 // Attempt typo correction early so that the type of the init expression can
12071 // be deduced based on the chosen correction if the original init contains a
12072 // TypoExpr.
12073 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
12074 if (!Res.isUsable()) {
12075 // There are unresolved typos in Init, just drop them.
12076 // FIXME: improve the recovery strategy to preserve the Init.
12077 RealDecl->setInvalidDecl();
12078 return;
12079 }
12080 if (Res.get()->containsErrors()) {
12081 // Invalidate the decl as we don't know the type for recovery-expr yet.
12082 RealDecl->setInvalidDecl();
12083 VDecl->setInit(Res.get());
12084 return;
12085 }
12086 Init = Res.get();
12087
12088 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
12089 return;
12090 }
12091
12092 // dllimport cannot be used on variable definitions.
12093 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
12094 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
12095 VDecl->setInvalidDecl();
12096 return;
12097 }
12098
12099 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
12100 // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
12101 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
12102 VDecl->setInvalidDecl();
12103 return;
12104 }
12105
12106 if (!VDecl->getType()->isDependentType()) {
12107 // A definition must end up with a complete type, which means it must be
12108 // complete with the restriction that an array type might be completed by
12109 // the initializer; note that later code assumes this restriction.
12110 QualType BaseDeclType = VDecl->getType();
12111 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
12112 BaseDeclType = Array->getElementType();
12113 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
12114 diag::err_typecheck_decl_incomplete_type)) {
12115 RealDecl->setInvalidDecl();
12116 return;
12117 }
12118
12119 // The variable can not have an abstract class type.
12120 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
12121 diag::err_abstract_type_in_decl,
12122 AbstractVariableType))
12123 VDecl->setInvalidDecl();
12124 }
12125
12126 // If adding the initializer will turn this declaration into a definition,
12127 // and we already have a definition for this variable, diagnose or otherwise
12128 // handle the situation.
12129 VarDecl *Def;
12130 if ((Def = VDecl->getDefinition()) && Def != VDecl &&
12131 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
12132 !VDecl->isThisDeclarationADemotedDefinition() &&
12133 checkVarDeclRedefinition(Def, VDecl))
12134 return;
12135
12136 if (getLangOpts().CPlusPlus) {
12137 // C++ [class.static.data]p4
12138 // If a static data member is of const integral or const
12139 // enumeration type, its declaration in the class definition can
12140 // specify a constant-initializer which shall be an integral
12141 // constant expression (5.19). In that case, the member can appear
12142 // in integral constant expressions. The member shall still be
12143 // defined in a namespace scope if it is used in the program and the
12144 // namespace scope definition shall not contain an initializer.
12145 //
12146 // We already performed a redefinition check above, but for static
12147 // data members we also need to check whether there was an in-class
12148 // declaration with an initializer.
12149 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
12150 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
12151 << VDecl->getDeclName();
12152 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
12153 diag::note_previous_initializer)
12154 << 0;
12155 return;
12156 }
12157
12158 if (VDecl->hasLocalStorage())
12159 setFunctionHasBranchProtectedScope();
12160
12161 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
12162 VDecl->setInvalidDecl();
12163 return;
12164 }
12165 }
12166
12167 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
12168 // a kernel function cannot be initialized."
12169 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
12170 Diag(VDecl->getLocation(), diag::err_local_cant_init);
12171 VDecl->setInvalidDecl();
12172 return;
12173 }
12174
12175 // The LoaderUninitialized attribute acts as a definition (of undef).
12176 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
12177 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
12178 VDecl->setInvalidDecl();
12179 return;
12180 }
12181
12182 // Get the decls type and save a reference for later, since
12183 // CheckInitializerTypes may change it.
12184 QualType DclT = VDecl->getType(), SavT = DclT;
12185
12186 // Expressions default to 'id' when we're in a debugger
12187 // and we are assigning it to a variable of Objective-C pointer type.
12188 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
12189 Init->getType() == Context.UnknownAnyTy) {
12190 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12191 if (Result.isInvalid()) {
12192 VDecl->setInvalidDecl();
12193 return;
12194 }
12195 Init = Result.get();
12196 }
12197
12198 // Perform the initialization.
12199 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
12200 if (!VDecl->isInvalidDecl()) {
12201 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12202 InitializationKind Kind = InitializationKind::CreateForInit(
12203 VDecl->getLocation(), DirectInit, Init);
12204
12205 MultiExprArg Args = Init;
12206 if (CXXDirectInit)
12207 Args = MultiExprArg(CXXDirectInit->getExprs(),
12208 CXXDirectInit->getNumExprs());
12209
12210 // Try to correct any TypoExprs in the initialization arguments.
12211 for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
12212 ExprResult Res = CorrectDelayedTyposInExpr(
12213 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
12214 [this, Entity, Kind](Expr *E) {
12215 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
12216 return Init.Failed() ? ExprError() : E;
12217 });
12218 if (Res.isInvalid()) {
12219 VDecl->setInvalidDecl();
12220 } else if (Res.get() != Args[Idx]) {
12221 Args[Idx] = Res.get();
12222 }
12223 }
12224 if (VDecl->isInvalidDecl())
12225 return;
12226
12227 InitializationSequence InitSeq(*this, Entity, Kind, Args,
12228 /*TopLevelOfInitList=*/false,
12229 /*TreatUnavailableAsInvalid=*/false);
12230 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
12231 if (Result.isInvalid()) {
12232 // If the provied initializer fails to initialize the var decl,
12233 // we attach a recovery expr for better recovery.
12234 auto RecoveryExpr =
12235 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
12236 if (RecoveryExpr.get())
12237 VDecl->setInit(RecoveryExpr.get());
12238 return;
12239 }
12240
12241 Init = Result.getAs<Expr>();
12242 }
12243
12244 // Check for self-references within variable initializers.
12245 // Variables declared within a function/method body (except for references)
12246 // are handled by a dataflow analysis.
12247 // This is undefined behavior in C++, but valid in C.
12248 if (getLangOpts().CPlusPlus) {
12249 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
12250 VDecl->getType()->isReferenceType()) {
12251 CheckSelfReference(*this, RealDecl, Init, DirectInit);
12252 }
12253 }
12254
12255 // If the type changed, it means we had an incomplete type that was
12256 // completed by the initializer. For example:
12257 // int ary[] = { 1, 3, 5 };
12258 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
12259 if (!VDecl->isInvalidDecl() && (DclT != SavT))
12260 VDecl->setType(DclT);
12261
12262 if (!VDecl->isInvalidDecl()) {
12263 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
12264
12265 if (VDecl->hasAttr<BlocksAttr>())
12266 checkRetainCycles(VDecl, Init);
12267
12268 // It is safe to assign a weak reference into a strong variable.
12269 // Although this code can still have problems:
12270 // id x = self.weakProp;
12271 // id y = self.weakProp;
12272 // we do not warn to warn spuriously when 'x' and 'y' are on separate
12273 // paths through the function. This should be revisited if
12274 // -Wrepeated-use-of-weak is made flow-sensitive.
12275 if (FunctionScopeInfo *FSI = getCurFunction())
12276 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
12277 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
12278 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12279 Init->getBeginLoc()))
12280 FSI->markSafeWeakUse(Init);
12281 }
12282
12283 // The initialization is usually a full-expression.
12284 //
12285 // FIXME: If this is a braced initialization of an aggregate, it is not
12286 // an expression, and each individual field initializer is a separate
12287 // full-expression. For instance, in:
12288 //
12289 // struct Temp { ~Temp(); };
12290 // struct S { S(Temp); };
12291 // struct T { S a, b; } t = { Temp(), Temp() }
12292 //
12293 // we should destroy the first Temp before constructing the second.
12294 ExprResult Result =
12295 ActOnFinishFullExpr(Init, VDecl->getLocation(),
12296 /*DiscardedValue*/ false, VDecl->isConstexpr());
12297 if (Result.isInvalid()) {
12298 VDecl->setInvalidDecl();
12299 return;
12300 }
12301 Init = Result.get();
12302
12303 // Attach the initializer to the decl.
12304 VDecl->setInit(Init);
12305
12306 if (VDecl->isLocalVarDecl()) {
12307 // Don't check the initializer if the declaration is malformed.
12308 if (VDecl->isInvalidDecl()) {
12309 // do nothing
12310
12311 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
12312 // This is true even in C++ for OpenCL.
12313 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
12314 CheckForConstantInitializer(Init, DclT);
12315
12316 // Otherwise, C++ does not restrict the initializer.
12317 } else if (getLangOpts().CPlusPlus) {
12318 // do nothing
12319
12320 // C99 6.7.8p4: All the expressions in an initializer for an object that has
12321 // static storage duration shall be constant expressions or string literals.
12322 } else if (VDecl->getStorageClass() == SC_Static) {
12323 CheckForConstantInitializer(Init, DclT);
12324
12325 // C89 is stricter than C99 for aggregate initializers.
12326 // C89 6.5.7p3: All the expressions [...] in an initializer list
12327 // for an object that has aggregate or union type shall be
12328 // constant expressions.
12329 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
12330 isa<InitListExpr>(Init)) {
12331 const Expr *Culprit;
12332 if (!Init->isConstantInitializer(Context, false, &Culprit)) {
12333 Diag(Culprit->getExprLoc(),
12334 diag::ext_aggregate_init_not_constant)
12335 << Culprit->getSourceRange();
12336 }
12337 }
12338
12339 if (auto *E = dyn_cast<ExprWithCleanups>(Init))
12340 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
12341 if (VDecl->hasLocalStorage())
12342 BE->getBlockDecl()->setCanAvoidCopyToHeap();
12343 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
12344 VDecl->getLexicalDeclContext()->isRecord()) {
12345 // This is an in-class initialization for a static data member, e.g.,
12346 //
12347 // struct S {
12348 // static const int value = 17;
12349 // };
12350
12351 // C++ [class.mem]p4:
12352 // A member-declarator can contain a constant-initializer only
12353 // if it declares a static member (9.4) of const integral or
12354 // const enumeration type, see 9.4.2.
12355 //
12356 // C++11 [class.static.data]p3:
12357 // If a non-volatile non-inline const static data member is of integral
12358 // or enumeration type, its declaration in the class definition can
12359 // specify a brace-or-equal-initializer in which every initializer-clause
12360 // that is an assignment-expression is a constant expression. A static
12361 // data member of literal type can be declared in the class definition
12362 // with the constexpr specifier; if so, its declaration shall specify a
12363 // brace-or-equal-initializer in which every initializer-clause that is
12364 // an assignment-expression is a constant expression.
12365
12366 // Do nothing on dependent types.
12367 if (DclT->isDependentType()) {
12368
12369 // Allow any 'static constexpr' members, whether or not they are of literal
12370 // type. We separately check that every constexpr variable is of literal
12371 // type.
12372 } else if (VDecl->isConstexpr()) {
12373
12374 // Require constness.
12375 } else if (!DclT.isConstQualified()) {
12376 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12377 << Init->getSourceRange();
12378 VDecl->setInvalidDecl();
12379
12380 // We allow integer constant expressions in all cases.
12381 } else if (DclT->isIntegralOrEnumerationType()) {
12382 // Check whether the expression is a constant expression.
12383 SourceLocation Loc;
12384 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12385 // In C++11, a non-constexpr const static data member with an
12386 // in-class initializer cannot be volatile.
12387 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12388 else if (Init->isValueDependent())
12389 ; // Nothing to check.
12390 else if (Init->isIntegerConstantExpr(Context, &Loc))
12391 ; // Ok, it's an ICE!
12392 else if (Init->getType()->isScopedEnumeralType() &&
12393 Init->isCXX11ConstantExpr(Context))
12394 ; // Ok, it is a scoped-enum constant expression.
12395 else if (Init->isEvaluatable(Context)) {
12396 // If we can constant fold the initializer through heroics, accept it,
12397 // but report this as a use of an extension for -pedantic.
12398 Diag(Loc, diag::ext_in_class_initializer_non_constant)
12399 << Init->getSourceRange();
12400 } else {
12401 // Otherwise, this is some crazy unknown case. Report the issue at the
12402 // location provided by the isIntegerConstantExpr failed check.
12403 Diag(Loc, diag::err_in_class_initializer_non_constant)
12404 << Init->getSourceRange();
12405 VDecl->setInvalidDecl();
12406 }
12407
12408 // We allow foldable floating-point constants as an extension.
12409 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12410 // In C++98, this is a GNU extension. In C++11, it is not, but we support
12411 // it anyway and provide a fixit to add the 'constexpr'.
12412 if (getLangOpts().CPlusPlus11) {
12413 Diag(VDecl->getLocation(),
12414 diag::ext_in_class_initializer_float_type_cxx11)
12415 << DclT << Init->getSourceRange();
12416 Diag(VDecl->getBeginLoc(),
12417 diag::note_in_class_initializer_float_type_cxx11)
12418 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12419 } else {
12420 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12421 << DclT << Init->getSourceRange();
12422
12423 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12424 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12425 << Init->getSourceRange();
12426 VDecl->setInvalidDecl();
12427 }
12428 }
12429
12430 // Suggest adding 'constexpr' in C++11 for literal types.
12431 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12432 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12433 << DclT << Init->getSourceRange()
12434 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12435 VDecl->setConstexpr(true);
12436
12437 } else {
12438 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12439 << DclT << Init->getSourceRange();
12440 VDecl->setInvalidDecl();
12441 }
12442 } else if (VDecl->isFileVarDecl()) {
12443 // In C, extern is typically used to avoid tentative definitions when
12444 // declaring variables in headers, but adding an intializer makes it a
12445 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12446 // In C++, extern is often used to give implictly static const variables
12447 // external linkage, so don't warn in that case. If selectany is present,
12448 // this might be header code intended for C and C++ inclusion, so apply the
12449 // C++ rules.
12450 if (VDecl->getStorageClass() == SC_Extern &&
12451 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12452 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12453 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12454 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12455 Diag(VDecl->getLocation(), diag::warn_extern_init);
12456
12457 // In Microsoft C++ mode, a const variable defined in namespace scope has
12458 // external linkage by default if the variable is declared with
12459 // __declspec(dllexport).
12460 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12461 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12462 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12463 VDecl->setStorageClass(SC_Extern);
12464
12465 // C99 6.7.8p4. All file scoped initializers need to be constant.
12466 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12467 CheckForConstantInitializer(Init, DclT);
12468 }
12469
12470 QualType InitType = Init->getType();
12471 if (!InitType.isNull() &&
12472 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12473 InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12474 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12475
12476 // We will represent direct-initialization similarly to copy-initialization:
12477 // int x(1); -as-> int x = 1;
12478 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12479 //
12480 // Clients that want to distinguish between the two forms, can check for
12481 // direct initializer using VarDecl::getInitStyle().
12482 // A major benefit is that clients that don't particularly care about which
12483 // exactly form was it (like the CodeGen) can handle both cases without
12484 // special case code.
12485
12486 // C++ 8.5p11:
12487 // The form of initialization (using parentheses or '=') is generally
12488 // insignificant, but does matter when the entity being initialized has a
12489 // class type.
12490 if (CXXDirectInit) {
12491 assert(DirectInit && "Call-style initializer must be direct init.")((DirectInit && "Call-style initializer must be direct init."
) ? static_cast<void> (0) : __assert_fail ("DirectInit && \"Call-style initializer must be direct init.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 12491, __PRETTY_FUNCTION__))
;
12492 VDecl->setInitStyle(VarDecl::CallInit);
12493 } else if (DirectInit) {
12494 // This must be list-initialization. No other way is direct-initialization.
12495 VDecl->setInitStyle(VarDecl::ListInit);
12496 }
12497
12498 if (LangOpts.OpenMP && VDecl->isFileVarDecl())
12499 DeclsToCheckForDeferredDiags.push_back(VDecl);
12500 CheckCompleteVariableDeclaration(VDecl);
12501}
12502
12503/// ActOnInitializerError - Given that there was an error parsing an
12504/// initializer for the given declaration, try to return to some form
12505/// of sanity.
12506void Sema::ActOnInitializerError(Decl *D) {
12507 // Our main concern here is re-establishing invariants like "a
12508 // variable's type is either dependent or complete".
12509 if (!D || D->isInvalidDecl()) return;
12510
12511 VarDecl *VD = dyn_cast<VarDecl>(D);
12512 if (!VD) return;
12513
12514 // Bindings are not usable if we can't make sense of the initializer.
12515 if (auto *DD = dyn_cast<DecompositionDecl>(D))
12516 for (auto *BD : DD->bindings())
12517 BD->setInvalidDecl();
12518
12519 // Auto types are meaningless if we can't make sense of the initializer.
12520 if (VD->getType()->isUndeducedType()) {
12521 D->setInvalidDecl();
12522 return;
12523 }
12524
12525 QualType Ty = VD->getType();
12526 if (Ty->isDependentType()) return;
12527
12528 // Require a complete type.
12529 if (RequireCompleteType(VD->getLocation(),
12530 Context.getBaseElementType(Ty),
12531 diag::err_typecheck_decl_incomplete_type)) {
12532 VD->setInvalidDecl();
12533 return;
12534 }
12535
12536 // Require a non-abstract type.
12537 if (RequireNonAbstractType(VD->getLocation(), Ty,
12538 diag::err_abstract_type_in_decl,
12539 AbstractVariableType)) {
12540 VD->setInvalidDecl();
12541 return;
12542 }
12543
12544 // Don't bother complaining about constructors or destructors,
12545 // though.
12546}
12547
12548void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
12549 // If there is no declaration, there was an error parsing it. Just ignore it.
12550 if (!RealDecl)
12551 return;
12552
12553 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12554 QualType Type = Var->getType();
12555
12556 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
12557 if (isa<DecompositionDecl>(RealDecl)) {
12558 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12559 Var->setInvalidDecl();
12560 return;
12561 }
12562
12563 if (Type->isUndeducedType() &&
12564 DeduceVariableDeclarationType(Var, false, nullptr))
12565 return;
12566
12567 // C++11 [class.static.data]p3: A static data member can be declared with
12568 // the constexpr specifier; if so, its declaration shall specify
12569 // a brace-or-equal-initializer.
12570 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12571 // the definition of a variable [...] or the declaration of a static data
12572 // member.
12573 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12574 !Var->isThisDeclarationADemotedDefinition()) {
12575 if (Var->isStaticDataMember()) {
12576 // C++1z removes the relevant rule; the in-class declaration is always
12577 // a definition there.
12578 if (!getLangOpts().CPlusPlus17 &&
12579 !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12580 Diag(Var->getLocation(),
12581 diag::err_constexpr_static_mem_var_requires_init)
12582 << Var;
12583 Var->setInvalidDecl();
12584 return;
12585 }
12586 } else {
12587 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12588 Var->setInvalidDecl();
12589 return;
12590 }
12591 }
12592
12593 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12594 // be initialized.
12595 if (!Var->isInvalidDecl() &&
12596 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12597 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12598 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12599 Var->setInvalidDecl();
12600 return;
12601 }
12602
12603 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
12604 if (Var->getStorageClass() == SC_Extern) {
12605 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
12606 << Var;
12607 Var->setInvalidDecl();
12608 return;
12609 }
12610 if (RequireCompleteType(Var->getLocation(), Var->getType(),
12611 diag::err_typecheck_decl_incomplete_type)) {
12612 Var->setInvalidDecl();
12613 return;
12614 }
12615 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12616 if (!RD->hasTrivialDefaultConstructor()) {
12617 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
12618 Var->setInvalidDecl();
12619 return;
12620 }
12621 }
12622 }
12623
12624 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
12625 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
12626 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12627 checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
12628 NTCUC_DefaultInitializedObject, NTCUK_Init);
12629
12630
12631 switch (DefKind) {
12632 case VarDecl::Definition:
12633 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
12634 break;
12635
12636 // We have an out-of-line definition of a static data member
12637 // that has an in-class initializer, so we type-check this like
12638 // a declaration.
12639 //
12640 LLVM_FALLTHROUGH[[gnu::fallthrough]];
12641
12642 case VarDecl::DeclarationOnly:
12643 // It's only a declaration.
12644
12645 // Block scope. C99 6.7p7: If an identifier for an object is
12646 // declared with no linkage (C99 6.2.2p6), the type for the
12647 // object shall be complete.
12648 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
12649 !Var->hasLinkage() && !Var->isInvalidDecl() &&
12650 RequireCompleteType(Var->getLocation(), Type,
12651 diag::err_typecheck_decl_incomplete_type))
12652 Var->setInvalidDecl();
12653
12654 // Make sure that the type is not abstract.
12655 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12656 RequireNonAbstractType(Var->getLocation(), Type,
12657 diag::err_abstract_type_in_decl,
12658 AbstractVariableType))
12659 Var->setInvalidDecl();
12660 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12661 Var->getStorageClass() == SC_PrivateExtern) {
12662 Diag(Var->getLocation(), diag::warn_private_extern);
12663 Diag(Var->getLocation(), diag::note_private_extern);
12664 }
12665
12666 if (Context.getTargetInfo().allowDebugInfoForExternalVar() &&
12667 !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
12668 ExternalDeclarations.push_back(Var);
12669
12670 return;
12671
12672 case VarDecl::TentativeDefinition:
12673 // File scope. C99 6.9.2p2: A declaration of an identifier for an
12674 // object that has file scope without an initializer, and without a
12675 // storage-class specifier or with the storage-class specifier "static",
12676 // constitutes a tentative definition. Note: A tentative definition with
12677 // external linkage is valid (C99 6.2.2p5).
12678 if (!Var->isInvalidDecl()) {
12679 if (const IncompleteArrayType *ArrayT
12680 = Context.getAsIncompleteArrayType(Type)) {
12681 if (RequireCompleteSizedType(
12682 Var->getLocation(), ArrayT->getElementType(),
12683 diag::err_array_incomplete_or_sizeless_type))
12684 Var->setInvalidDecl();
12685 } else if (Var->getStorageClass() == SC_Static) {
12686 // C99 6.9.2p3: If the declaration of an identifier for an object is
12687 // a tentative definition and has internal linkage (C99 6.2.2p3), the
12688 // declared type shall not be an incomplete type.
12689 // NOTE: code such as the following
12690 // static struct s;
12691 // struct s { int a; };
12692 // is accepted by gcc. Hence here we issue a warning instead of
12693 // an error and we do not invalidate the static declaration.
12694 // NOTE: to avoid multiple warnings, only check the first declaration.
12695 if (Var->isFirstDecl())
12696 RequireCompleteType(Var->getLocation(), Type,
12697 diag::ext_typecheck_decl_incomplete_type);
12698 }
12699 }
12700
12701 // Record the tentative definition; we're done.
12702 if (!Var->isInvalidDecl())
12703 TentativeDefinitions.push_back(Var);
12704 return;
12705 }
12706
12707 // Provide a specific diagnostic for uninitialized variable
12708 // definitions with incomplete array type.
12709 if (Type->isIncompleteArrayType()) {
12710 Diag(Var->getLocation(),
12711 diag::err_typecheck_incomplete_array_needs_initializer);
12712 Var->setInvalidDecl();
12713 return;
12714 }
12715
12716 // Provide a specific diagnostic for uninitialized variable
12717 // definitions with reference type.
12718 if (Type->isReferenceType()) {
12719 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
12720 << Var << SourceRange(Var->getLocation(), Var->getLocation());
12721 Var->setInvalidDecl();
12722 return;
12723 }
12724
12725 // Do not attempt to type-check the default initializer for a
12726 // variable with dependent type.
12727 if (Type->isDependentType())
12728 return;
12729
12730 if (Var->isInvalidDecl())
12731 return;
12732
12733 if (!Var->hasAttr<AliasAttr>()) {
12734 if (RequireCompleteType(Var->getLocation(),
12735 Context.getBaseElementType(Type),
12736 diag::err_typecheck_decl_incomplete_type)) {
12737 Var->setInvalidDecl();
12738 return;
12739 }
12740 } else {
12741 return;
12742 }
12743
12744 // The variable can not have an abstract class type.
12745 if (RequireNonAbstractType(Var->getLocation(), Type,
12746 diag::err_abstract_type_in_decl,
12747 AbstractVariableType)) {
12748 Var->setInvalidDecl();
12749 return;
12750 }
12751
12752 // Check for jumps past the implicit initializer. C++0x
12753 // clarifies that this applies to a "variable with automatic
12754 // storage duration", not a "local variable".
12755 // C++11 [stmt.dcl]p3
12756 // A program that jumps from a point where a variable with automatic
12757 // storage duration is not in scope to a point where it is in scope is
12758 // ill-formed unless the variable has scalar type, class type with a
12759 // trivial default constructor and a trivial destructor, a cv-qualified
12760 // version of one of these types, or an array of one of the preceding
12761 // types and is declared without an initializer.
12762 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
12763 if (const RecordType *Record
12764 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
12765 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
12766 // Mark the function (if we're in one) for further checking even if the
12767 // looser rules of C++11 do not require such checks, so that we can
12768 // diagnose incompatibilities with C++98.
12769 if (!CXXRecord->isPOD())
12770 setFunctionHasBranchProtectedScope();
12771 }
12772 }
12773 // In OpenCL, we can't initialize objects in the __local address space,
12774 // even implicitly, so don't synthesize an implicit initializer.
12775 if (getLangOpts().OpenCL &&
12776 Var->getType().getAddressSpace() == LangAS::opencl_local)
12777 return;
12778 // C++03 [dcl.init]p9:
12779 // If no initializer is specified for an object, and the
12780 // object is of (possibly cv-qualified) non-POD class type (or
12781 // array thereof), the object shall be default-initialized; if
12782 // the object is of const-qualified type, the underlying class
12783 // type shall have a user-declared default
12784 // constructor. Otherwise, if no initializer is specified for
12785 // a non- static object, the object and its subobjects, if
12786 // any, have an indeterminate initial value); if the object
12787 // or any of its subobjects are of const-qualified type, the
12788 // program is ill-formed.
12789 // C++0x [dcl.init]p11:
12790 // If no initializer is specified for an object, the object is
12791 // default-initialized; [...].
12792 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
12793 InitializationKind Kind
12794 = InitializationKind::CreateDefault(Var->getLocation());
12795
12796 InitializationSequence InitSeq(*this, Entity, Kind, None);
12797 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
12798
12799 if (Init.get()) {
12800 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
12801 // This is important for template substitution.
12802 Var->setInitStyle(VarDecl::CallInit);
12803 } else if (Init.isInvalid()) {
12804 // If default-init fails, attach a recovery-expr initializer to track
12805 // that initialization was attempted and failed.
12806 auto RecoveryExpr =
12807 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
12808 if (RecoveryExpr.get())
12809 Var->setInit(RecoveryExpr.get());
12810 }
12811
12812 CheckCompleteVariableDeclaration(Var);
12813 }
12814}
12815
12816void Sema::ActOnCXXForRangeDecl(Decl *D) {
12817 // If there is no declaration, there was an error parsing it. Ignore it.
12818 if (!D)
12819 return;
12820
12821 VarDecl *VD = dyn_cast<VarDecl>(D);
12822 if (!VD) {
12823 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
12824 D->setInvalidDecl();
12825 return;
12826 }
12827
12828 VD->setCXXForRangeDecl(true);
12829
12830 // for-range-declaration cannot be given a storage class specifier.
12831 int Error = -1;
12832 switch (VD->getStorageClass()) {
12833 case SC_None:
12834 break;
12835 case SC_Extern:
12836 Error = 0;
12837 break;
12838 case SC_Static:
12839 Error = 1;
12840 break;
12841 case SC_PrivateExtern:
12842 Error = 2;
12843 break;
12844 case SC_Auto:
12845 Error = 3;
12846 break;
12847 case SC_Register:
12848 Error = 4;
12849 break;
12850 }
12851
12852 // for-range-declaration cannot be given a storage class specifier con't.
12853 switch (VD->getTSCSpec()) {
12854 case TSCS_thread_local:
12855 Error = 6;
12856 break;
12857 case TSCS___thread:
12858 case TSCS__Thread_local:
12859 case TSCS_unspecified:
12860 break;
12861 }
12862
12863 if (Error != -1) {
12864 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
12865 << VD << Error;
12866 D->setInvalidDecl();
12867 }
12868}
12869
12870StmtResult
12871Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
12872 IdentifierInfo *Ident,
12873 ParsedAttributes &Attrs,
12874 SourceLocation AttrEnd) {
12875 // C++1y [stmt.iter]p1:
12876 // A range-based for statement of the form
12877 // for ( for-range-identifier : for-range-initializer ) statement
12878 // is equivalent to
12879 // for ( auto&& for-range-identifier : for-range-initializer ) statement
12880 DeclSpec DS(Attrs.getPool().getFactory());
12881
12882 const char *PrevSpec;
12883 unsigned DiagID;
12884 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
12885 getPrintingPolicy());
12886
12887 Declarator D(DS, DeclaratorContext::ForInit);
12888 D.SetIdentifier(Ident, IdentLoc);
12889 D.takeAttributes(Attrs, AttrEnd);
12890
12891 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
12892 IdentLoc);
12893 Decl *Var = ActOnDeclarator(S, D);
12894 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
12895 FinalizeDeclaration(Var);
12896 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
12897 AttrEnd.isValid() ? AttrEnd : IdentLoc);
12898}
12899
12900void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
12901 if (var->isInvalidDecl()) return;
12902
12903 if (getLangOpts().OpenCL) {
12904 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
12905 // initialiser
12906 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
12907 !var->hasInit()) {
12908 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
12909 << 1 /*Init*/;
12910 var->setInvalidDecl();
12911 return;
12912 }
12913 }
12914
12915 // In Objective-C, don't allow jumps past the implicit initialization of a
12916 // local retaining variable.
12917 if (getLangOpts().ObjC &&
12918 var->hasLocalStorage()) {
12919 switch (var->getType().getObjCLifetime()) {
12920 case Qualifiers::OCL_None:
12921 case Qualifiers::OCL_ExplicitNone:
12922 case Qualifiers::OCL_Autoreleasing:
12923 break;
12924
12925 case Qualifiers::OCL_Weak:
12926 case Qualifiers::OCL_Strong:
12927 setFunctionHasBranchProtectedScope();
12928 break;
12929 }
12930 }
12931
12932 if (var->hasLocalStorage() &&
12933 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
12934 setFunctionHasBranchProtectedScope();
12935
12936 // Warn about externally-visible variables being defined without a
12937 // prior declaration. We only want to do this for global
12938 // declarations, but we also specifically need to avoid doing it for
12939 // class members because the linkage of an anonymous class can
12940 // change if it's later given a typedef name.
12941 if (var->isThisDeclarationADefinition() &&
12942 var->getDeclContext()->getRedeclContext()->isFileContext() &&
12943 var->isExternallyVisible() && var->hasLinkage() &&
12944 !var->isInline() && !var->getDescribedVarTemplate() &&
12945 !isa<VarTemplatePartialSpecializationDecl>(var) &&
12946 !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
12947 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
12948 var->getLocation())) {
12949 // Find a previous declaration that's not a definition.
12950 VarDecl *prev = var->getPreviousDecl();
12951 while (prev && prev->isThisDeclarationADefinition())
12952 prev = prev->getPreviousDecl();
12953
12954 if (!prev) {
12955 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
12956 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
12957 << /* variable */ 0;
12958 }
12959 }
12960
12961 // Cache the result of checking for constant initialization.
12962 Optional<bool> CacheHasConstInit;
12963 const Expr *CacheCulprit = nullptr;
12964 auto checkConstInit = [&]() mutable {
12965 if (!CacheHasConstInit)
12966 CacheHasConstInit = var->getInit()->isConstantInitializer(
12967 Context, var->getType()->isReferenceType(), &CacheCulprit);
12968 return *CacheHasConstInit;
12969 };
12970
12971 if (var->getTLSKind() == VarDecl::TLS_Static) {
12972 if (var->getType().isDestructedType()) {
12973 // GNU C++98 edits for __thread, [basic.start.term]p3:
12974 // The type of an object with thread storage duration shall not
12975 // have a non-trivial destructor.
12976 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
12977 if (getLangOpts().CPlusPlus11)
12978 Diag(var->getLocation(), diag::note_use_thread_local);
12979 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
12980 if (!checkConstInit()) {
12981 // GNU C++98 edits for __thread, [basic.start.init]p4:
12982 // An object of thread storage duration shall not require dynamic
12983 // initialization.
12984 // FIXME: Need strict checking here.
12985 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
12986 << CacheCulprit->getSourceRange();
12987 if (getLangOpts().CPlusPlus11)
12988 Diag(var->getLocation(), diag::note_use_thread_local);
12989 }
12990 }
12991 }
12992
12993 // Apply section attributes and pragmas to global variables.
12994 bool GlobalStorage = var->hasGlobalStorage();
12995 if (GlobalStorage && var->isThisDeclarationADefinition() &&
12996 !inTemplateInstantiation()) {
12997 PragmaStack<StringLiteral *> *Stack = nullptr;
12998 int SectionFlags = ASTContext::PSF_Read;
12999 if (var->getType().isConstQualified())
13000 Stack = &ConstSegStack;
13001 else if (!var->getInit()) {
13002 Stack = &BSSSegStack;
13003 SectionFlags |= ASTContext::PSF_Write;
13004 } else {
13005 Stack = &DataSegStack;
13006 SectionFlags |= ASTContext::PSF_Write;
13007 }
13008 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
13009 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
13010 SectionFlags |= ASTContext::PSF_Implicit;
13011 UnifySection(SA->getName(), SectionFlags, var);
13012 } else if (Stack->CurrentValue) {
13013 SectionFlags |= ASTContext::PSF_Implicit;
13014 auto SectionName = Stack->CurrentValue->getString();
13015 var->addAttr(SectionAttr::CreateImplicit(
13016 Context, SectionName, Stack->CurrentPragmaLocation,
13017 AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
13018 if (UnifySection(SectionName, SectionFlags, var))
13019 var->dropAttr<SectionAttr>();
13020 }
13021
13022 // Apply the init_seg attribute if this has an initializer. If the
13023 // initializer turns out to not be dynamic, we'll end up ignoring this
13024 // attribute.
13025 if (CurInitSeg && var->getInit())
13026 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
13027 CurInitSegLoc,
13028 AttributeCommonInfo::AS_Pragma));
13029 }
13030
13031 if (!var->getType()->isStructureType() && var->hasInit() &&
13032 isa<InitListExpr>(var->getInit())) {
13033 const auto *ILE = cast<InitListExpr>(var->getInit());
13034 unsigned NumInits = ILE->getNumInits();
13035 if (NumInits > 2)
13036 for (unsigned I = 0; I < NumInits; ++I) {
13037 const auto *Init = ILE->getInit(I);
13038 if (!Init)
13039 break;
13040 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13041 if (!SL)
13042 break;
13043
13044 unsigned NumConcat = SL->getNumConcatenated();
13045 // Diagnose missing comma in string array initialization.
13046 // Do not warn when all the elements in the initializer are concatenated
13047 // together. Do not warn for macros too.
13048 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
13049 bool OnlyOneMissingComma = true;
13050 for (unsigned J = I + 1; J < NumInits; ++J) {
13051 const auto *Init = ILE->getInit(J);
13052 if (!Init)
13053 break;
13054 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13055 if (!SLJ || SLJ->getNumConcatenated() > 1) {
13056 OnlyOneMissingComma = false;
13057 break;
13058 }
13059 }
13060
13061 if (OnlyOneMissingComma) {
13062 SmallVector<FixItHint, 1> Hints;
13063 for (unsigned i = 0; i < NumConcat - 1; ++i)
13064 Hints.push_back(FixItHint::CreateInsertion(
13065 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
13066
13067 Diag(SL->getStrTokenLoc(1),
13068 diag::warn_concatenated_literal_array_init)
13069 << Hints;
13070 Diag(SL->getBeginLoc(),
13071 diag::note_concatenated_string_literal_silence);
13072 }
13073 // In any case, stop now.
13074 break;
13075 }
13076 }
13077 }
13078
13079 // All the following checks are C++ only.
13080 if (!getLangOpts().CPlusPlus) {
13081 // If this variable must be emitted, add it as an initializer for the
13082 // current module.
13083 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13084 Context.addModuleInitializer(ModuleScopes.back().Module, var);
13085 return;
13086 }
13087
13088 QualType type = var->getType();
13089
13090 if (var->hasAttr<BlocksAttr>())
13091 getCurFunction()->addByrefBlockVar(var);
13092
13093 Expr *Init = var->getInit();
13094 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
13095 QualType baseType = Context.getBaseElementType(type);
13096
13097 // Check whether the initializer is sufficiently constant.
13098 if (!type->isDependentType() && Init && !Init->isValueDependent() &&
13099 (GlobalStorage || var->isConstexpr() ||
13100 var->mightBeUsableInConstantExpressions(Context))) {
13101 // If this variable might have a constant initializer or might be usable in
13102 // constant expressions, check whether or not it actually is now. We can't
13103 // do this lazily, because the result might depend on things that change
13104 // later, such as which constexpr functions happen to be defined.
13105 SmallVector<PartialDiagnosticAt, 8> Notes;
13106 bool HasConstInit;
13107 if (!getLangOpts().CPlusPlus11) {
13108 // Prior to C++11, in contexts where a constant initializer is required,
13109 // the set of valid constant initializers is described by syntactic rules
13110 // in [expr.const]p2-6.
13111 // FIXME: Stricter checking for these rules would be useful for constinit /
13112 // -Wglobal-constructors.
13113 HasConstInit = checkConstInit();
13114
13115 // Compute and cache the constant value, and remember that we have a
13116 // constant initializer.
13117 if (HasConstInit) {
13118 (void)var->checkForConstantInitialization(Notes);
13119 Notes.clear();
13120 } else if (CacheCulprit) {
13121 Notes.emplace_back(CacheCulprit->getExprLoc(),
13122 PDiag(diag::note_invalid_subexpr_in_const_expr));
13123 Notes.back().second << CacheCulprit->getSourceRange();
13124 }
13125 } else {
13126 // Evaluate the initializer to see if it's a constant initializer.
13127 HasConstInit = var->checkForConstantInitialization(Notes);
13128 }
13129
13130 if (HasConstInit) {
13131 // FIXME: Consider replacing the initializer with a ConstantExpr.
13132 } else if (var->isConstexpr()) {
13133 SourceLocation DiagLoc = var->getLocation();
13134 // If the note doesn't add any useful information other than a source
13135 // location, fold it into the primary diagnostic.
13136 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13137 diag::note_invalid_subexpr_in_const_expr) {
13138 DiagLoc = Notes[0].first;
13139 Notes.clear();
13140 }
13141 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
13142 << var << Init->getSourceRange();
13143 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
13144 Diag(Notes[I].first, Notes[I].second);
13145 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
13146 auto *Attr = var->getAttr<ConstInitAttr>();
13147 Diag(var->getLocation(), diag::err_require_constant_init_failed)
13148 << Init->getSourceRange();
13149 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
13150 << Attr->getRange() << Attr->isConstinit();
13151 for (auto &it : Notes)
13152 Diag(it.first, it.second);
13153 } else if (IsGlobal &&
13154 !getDiagnostics().isIgnored(diag::warn_global_constructor,
13155 var->getLocation())) {
13156 // Warn about globals which don't have a constant initializer. Don't
13157 // warn about globals with a non-trivial destructor because we already
13158 // warned about them.
13159 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
13160 if (!(RD && !RD->hasTrivialDestructor())) {
13161 // checkConstInit() here permits trivial default initialization even in
13162 // C++11 onwards, where such an initializer is not a constant initializer
13163 // but nonetheless doesn't require a global constructor.
13164 if (!checkConstInit())
13165 Diag(var->getLocation(), diag::warn_global_constructor)
13166 << Init->getSourceRange();
13167 }
13168 }
13169 }
13170
13171 // Require the destructor.
13172 if (!type->isDependentType())
13173 if (const RecordType *recordType = baseType->getAs<RecordType>())
13174 FinalizeVarWithDestructor(var, recordType);
13175
13176 // If this variable must be emitted, add it as an initializer for the current
13177 // module.
13178 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13179 Context.addModuleInitializer(ModuleScopes.back().Module, var);
13180
13181 // Build the bindings if this is a structured binding declaration.
13182 if (auto *DD = dyn_cast<DecompositionDecl>(var))
13183 CheckCompleteDecompositionDeclaration(DD);
13184}
13185
13186/// Determines if a variable's alignment is dependent.
13187static bool hasDependentAlignment(VarDecl *VD) {
13188 if (VD->getType()->isDependentType())
13189 return true;
13190 for (auto *I : VD->specific_attrs<AlignedAttr>())
13191 if (I->isAlignmentDependent())
13192 return true;
13193 return false;
13194}
13195
13196/// Check if VD needs to be dllexport/dllimport due to being in a
13197/// dllexport/import function.
13198void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
13199 assert(VD->isStaticLocal())((VD->isStaticLocal()) ? static_cast<void> (0) : __assert_fail
("VD->isStaticLocal()", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 13199, __PRETTY_FUNCTION__))
;
13200
13201 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13202
13203 // Find outermost function when VD is in lambda function.
13204 while (FD && !getDLLAttr(FD) &&
13205 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
13206 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
13207 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
13208 }
13209
13210 if (!FD)
13211 return;
13212
13213 // Static locals inherit dll attributes from their function.
13214 if (Attr *A = getDLLAttr(FD)) {
13215 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
13216 NewAttr->setInherited(true);
13217 VD->addAttr(NewAttr);
13218 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
13219 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
13220 NewAttr->setInherited(true);
13221 VD->addAttr(NewAttr);
13222
13223 // Export this function to enforce exporting this static variable even
13224 // if it is not used in this compilation unit.
13225 if (!FD->hasAttr<DLLExportAttr>())
13226 FD->addAttr(NewAttr);
13227
13228 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
13229 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
13230 NewAttr->setInherited(true);
13231 VD->addAttr(NewAttr);
13232 }
13233}
13234
13235/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
13236/// any semantic actions necessary after any initializer has been attached.
13237void Sema::FinalizeDeclaration(Decl *ThisDecl) {
13238 // Note that we are no longer parsing the initializer for this declaration.
13239 ParsingInitForAutoVars.erase(ThisDecl);
13240
13241 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
13242 if (!VD)
13243 return;
13244
13245 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
13246 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
13247 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
13248 if (PragmaClangBSSSection.Valid)
13249 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
13250 Context, PragmaClangBSSSection.SectionName,
13251 PragmaClangBSSSection.PragmaLocation,
13252 AttributeCommonInfo::AS_Pragma));
13253 if (PragmaClangDataSection.Valid)
13254 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
13255 Context, PragmaClangDataSection.SectionName,
13256 PragmaClangDataSection.PragmaLocation,
13257 AttributeCommonInfo::AS_Pragma));
13258 if (PragmaClangRodataSection.Valid)
13259 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
13260 Context, PragmaClangRodataSection.SectionName,
13261 PragmaClangRodataSection.PragmaLocation,
13262 AttributeCommonInfo::AS_Pragma));
13263 if (PragmaClangRelroSection.Valid)
13264 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
13265 Context, PragmaClangRelroSection.SectionName,
13266 PragmaClangRelroSection.PragmaLocation,
13267 AttributeCommonInfo::AS_Pragma));
13268 }
13269
13270 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
13271 for (auto *BD : DD->bindings()) {
13272 FinalizeDeclaration(BD);
13273 }
13274 }
13275
13276 checkAttributesAfterMerging(*this, *VD);
13277
13278 // Perform TLS alignment check here after attributes attached to the variable
13279 // which may affect the alignment have been processed. Only perform the check
13280 // if the target has a maximum TLS alignment (zero means no constraints).
13281 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
13282 // Protect the check so that it's not performed on dependent types and
13283 // dependent alignments (we can't determine the alignment in that case).
13284 if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
13285 !VD->isInvalidDecl()) {
13286 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
13287 if (Context.getDeclAlign(VD) > MaxAlignChars) {
13288 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
13289 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
13290 << (unsigned)MaxAlignChars.getQuantity();
13291 }
13292 }
13293 }
13294
13295 if (VD->isStaticLocal())
13296 CheckStaticLocalForDllExport(VD);
13297
13298 // Perform check for initializers of device-side global variables.
13299 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
13300 // 7.5). We must also apply the same checks to all __shared__
13301 // variables whether they are local or not. CUDA also allows
13302 // constant initializers for __constant__ and __device__ variables.
13303 if (getLangOpts().CUDA)
13304 checkAllowedCUDAInitializer(VD);
13305
13306 // Grab the dllimport or dllexport attribute off of the VarDecl.
13307 const InheritableAttr *DLLAttr = getDLLAttr(VD);
13308
13309 // Imported static data members cannot be defined out-of-line.
13310 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
13311 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
13312 VD->isThisDeclarationADefinition()) {
13313 // We allow definitions of dllimport class template static data members
13314 // with a warning.
13315 CXXRecordDecl *Context =
13316 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
13317 bool IsClassTemplateMember =
13318 isa<ClassTemplatePartialSpecializationDecl>(Context) ||
13319 Context->getDescribedClassTemplate();
13320
13321 Diag(VD->getLocation(),
13322 IsClassTemplateMember
13323 ? diag::warn_attribute_dllimport_static_field_definition
13324 : diag::err_attribute_dllimport_static_field_definition);
13325 Diag(IA->getLocation(), diag::note_attribute);
13326 if (!IsClassTemplateMember)
13327 VD->setInvalidDecl();
13328 }
13329 }
13330
13331 // dllimport/dllexport variables cannot be thread local, their TLS index
13332 // isn't exported with the variable.
13333 if (DLLAttr && VD->getTLSKind()) {
13334 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13335 if (F && getDLLAttr(F)) {
13336 assert(VD->isStaticLocal())((VD->isStaticLocal()) ? static_cast<void> (0) : __assert_fail
("VD->isStaticLocal()", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 13336, __PRETTY_FUNCTION__))
;
13337 // But if this is a static local in a dlimport/dllexport function, the
13338 // function will never be inlined, which means the var would never be
13339 // imported, so having it marked import/export is safe.
13340 } else {
13341 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
13342 << DLLAttr;
13343 VD->setInvalidDecl();
13344 }
13345 }
13346
13347 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
13348 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13349 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13350 << Attr;
13351 VD->dropAttr<UsedAttr>();
13352 }
13353 }
13354 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
13355 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13356 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13357 << Attr;
13358 VD->dropAttr<RetainAttr>();
13359 }
13360 }
13361
13362 const DeclContext *DC = VD->getDeclContext();
13363 // If there's a #pragma GCC visibility in scope, and this isn't a class
13364 // member, set the visibility of this variable.
13365 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
13366 AddPushedVisibilityAttribute(VD);
13367
13368 // FIXME: Warn on unused var template partial specializations.
13369 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
13370 MarkUnusedFileScopedDecl(VD);
13371
13372 // Now we have parsed the initializer and can update the table of magic
13373 // tag values.
13374 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
13375 !VD->getType()->isIntegralOrEnumerationType())
13376 return;
13377
13378 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
13379 const Expr *MagicValueExpr = VD->getInit();
13380 if (!MagicValueExpr) {
13381 continue;
13382 }
13383 Optional<llvm::APSInt> MagicValueInt;
13384 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
13385 Diag(I->getRange().getBegin(),
13386 diag::err_type_tag_for_datatype_not_ice)
13387 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13388 continue;
13389 }
13390 if (MagicValueInt->getActiveBits() > 64) {
13391 Diag(I->getRange().getBegin(),
13392 diag::err_type_tag_for_datatype_too_large)
13393 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13394 continue;
13395 }
13396 uint64_t MagicValue = MagicValueInt->getZExtValue();
13397 RegisterTypeTagForDatatype(I->getArgumentKind(),
13398 MagicValue,
13399 I->getMatchingCType(),
13400 I->getLayoutCompatible(),
13401 I->getMustBeNull());
13402 }
13403}
13404
13405static bool hasDeducedAuto(DeclaratorDecl *DD) {
13406 auto *VD = dyn_cast<VarDecl>(DD);
13407 return VD && !VD->getType()->hasAutoForTrailingReturnType();
13408}
13409
13410Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
13411 ArrayRef<Decl *> Group) {
13412 SmallVector<Decl*, 8> Decls;
13413
13414 if (DS.isTypeSpecOwned())
13415 Decls.push_back(DS.getRepAsDecl());
13416
13417 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
13418 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
13419 bool DiagnosedMultipleDecomps = false;
13420 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
13421 bool DiagnosedNonDeducedAuto = false;
13422
13423 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13424 if (Decl *D = Group[i]) {
13425 // For declarators, there are some additional syntactic-ish checks we need
13426 // to perform.
13427 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
13428 if (!FirstDeclaratorInGroup)
13429 FirstDeclaratorInGroup = DD;
13430 if (!FirstDecompDeclaratorInGroup)
13431 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
13432 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
13433 !hasDeducedAuto(DD))
13434 FirstNonDeducedAutoInGroup = DD;
13435
13436 if (FirstDeclaratorInGroup != DD) {
13437 // A decomposition declaration cannot be combined with any other
13438 // declaration in the same group.
13439 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
13440 Diag(FirstDecompDeclaratorInGroup->getLocation(),
13441 diag::err_decomp_decl_not_alone)
13442 << FirstDeclaratorInGroup->getSourceRange()
13443 << DD->getSourceRange();
13444 DiagnosedMultipleDecomps = true;
13445 }
13446
13447 // A declarator that uses 'auto' in any way other than to declare a
13448 // variable with a deduced type cannot be combined with any other
13449 // declarator in the same group.
13450 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
13451 Diag(FirstNonDeducedAutoInGroup->getLocation(),
13452 diag::err_auto_non_deduced_not_alone)
13453 << FirstNonDeducedAutoInGroup->getType()
13454 ->hasAutoForTrailingReturnType()
13455 << FirstDeclaratorInGroup->getSourceRange()
13456 << DD->getSourceRange();
13457 DiagnosedNonDeducedAuto = true;
13458 }
13459 }
13460 }
13461
13462 Decls.push_back(D);
13463 }
13464 }
13465
13466 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
13467 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13468 handleTagNumbering(Tag, S);
13469 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13470 getLangOpts().CPlusPlus)
13471 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
13472 }
13473 }
13474
13475 return BuildDeclaratorGroup(Decls);
13476}
13477
13478/// BuildDeclaratorGroup - convert a list of declarations into a declaration
13479/// group, performing any necessary semantic checking.
13480Sema::DeclGroupPtrTy
13481Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
13482 // C++14 [dcl.spec.auto]p7: (DR1347)
13483 // If the type that replaces the placeholder type is not the same in each
13484 // deduction, the program is ill-formed.
13485 if (Group.size() > 1) {
13486 QualType Deduced;
13487 VarDecl *DeducedDecl = nullptr;
13488 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13489 VarDecl *D = dyn_cast<VarDecl>(Group[i]);
13490 if (!D || D->isInvalidDecl())
13491 break;
13492 DeducedType *DT = D->getType()->getContainedDeducedType();
13493 if (!DT || DT->getDeducedType().isNull())
13494 continue;
13495 if (Deduced.isNull()) {
13496 Deduced = DT->getDeducedType();
13497 DeducedDecl = D;
13498 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
13499 auto *AT = dyn_cast<AutoType>(DT);
13500 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
13501 diag::err_auto_different_deductions)
13502 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
13503 << DeducedDecl->getDeclName() << DT->getDeducedType()
13504 << D->getDeclName();
13505 if (DeducedDecl->hasInit())
13506 Dia << DeducedDecl->getInit()->getSourceRange();
13507 if (D->getInit())
13508 Dia << D->getInit()->getSourceRange();
13509 D->setInvalidDecl();
13510 break;
13511 }
13512 }
13513 }
13514
13515 ActOnDocumentableDecls(Group);
13516
13517 return DeclGroupPtrTy::make(
13518 DeclGroupRef::Create(Context, Group.data(), Group.size()));
13519}
13520
13521void Sema::ActOnDocumentableDecl(Decl *D) {
13522 ActOnDocumentableDecls(D);
13523}
13524
13525void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
13526 // Don't parse the comment if Doxygen diagnostics are ignored.
13527 if (Group.empty() || !Group[0])
13528 return;
13529
13530 if (Diags.isIgnored(diag::warn_doc_param_not_found,
13531 Group[0]->getLocation()) &&
13532 Diags.isIgnored(diag::warn_unknown_comment_command_name,
13533 Group[0]->getLocation()))
13534 return;
13535
13536 if (Group.size() >= 2) {
13537 // This is a decl group. Normally it will contain only declarations
13538 // produced from declarator list. But in case we have any definitions or
13539 // additional declaration references:
13540 // 'typedef struct S {} S;'
13541 // 'typedef struct S *S;'
13542 // 'struct S *pS;'
13543 // FinalizeDeclaratorGroup adds these as separate declarations.
13544 Decl *MaybeTagDecl = Group[0];
13545 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
13546 Group = Group.slice(1);
13547 }
13548 }
13549
13550 // FIMXE: We assume every Decl in the group is in the same file.
13551 // This is false when preprocessor constructs the group from decls in
13552 // different files (e. g. macros or #include).
13553 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
13554}
13555
13556/// Common checks for a parameter-declaration that should apply to both function
13557/// parameters and non-type template parameters.
13558void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
13559 // Check that there are no default arguments inside the type of this
13560 // parameter.
13561 if (getLangOpts().CPlusPlus)
13562 CheckExtraCXXDefaultArguments(D);
13563
13564 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
13565 if (D.getCXXScopeSpec().isSet()) {
13566 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
13567 << D.getCXXScopeSpec().getRange();
13568 }
13569
13570 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
13571 // simple identifier except [...irrelevant cases...].
13572 switch (D.getName().getKind()) {
13573 case UnqualifiedIdKind::IK_Identifier:
13574 break;
13575
13576 case UnqualifiedIdKind::IK_OperatorFunctionId:
13577 case UnqualifiedIdKind::IK_ConversionFunctionId:
13578 case UnqualifiedIdKind::IK_LiteralOperatorId:
13579 case UnqualifiedIdKind::IK_ConstructorName:
13580 case UnqualifiedIdKind::IK_DestructorName:
13581 case UnqualifiedIdKind::IK_ImplicitSelfParam:
13582 case UnqualifiedIdKind::IK_DeductionGuideName:
13583 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
13584 << GetNameForDeclarator(D).getName();
13585 break;
13586
13587 case UnqualifiedIdKind::IK_TemplateId:
13588 case UnqualifiedIdKind::IK_ConstructorTemplateId:
13589 // GetNameForDeclarator would not produce a useful name in this case.
13590 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
13591 break;
13592 }
13593}
13594
13595/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
13596/// to introduce parameters into function prototype scope.
13597Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
13598 const DeclSpec &DS = D.getDeclSpec();
13599
13600 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
13601
13602 // C++03 [dcl.stc]p2 also permits 'auto'.
13603 StorageClass SC = SC_None;
13604 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
13605 SC = SC_Register;
13606 // In C++11, the 'register' storage class specifier is deprecated.
13607 // In C++17, it is not allowed, but we tolerate it as an extension.
13608 if (getLangOpts().CPlusPlus11) {
13609 Diag(DS.getStorageClassSpecLoc(),
13610 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
13611 : diag::warn_deprecated_register)
13612 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
13613 }
13614 } else if (getLangOpts().CPlusPlus &&
13615 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
13616 SC = SC_Auto;
13617 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
13618 Diag(DS.getStorageClassSpecLoc(),
13619 diag::err_invalid_storage_class_in_func_decl);
13620 D.getMutableDeclSpec().ClearStorageClassSpecs();
13621 }
13622
13623 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
13624 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
13625 << DeclSpec::getSpecifierName(TSCS);
13626 if (DS.isInlineSpecified())
13627 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
13628 << getLangOpts().CPlusPlus17;
13629 if (DS.hasConstexprSpecifier())
13630 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
13631 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
13632
13633 DiagnoseFunctionSpecifiers(DS);
13634
13635 CheckFunctionOrTemplateParamDeclarator(S, D);
13636
13637 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13638 QualType parmDeclType = TInfo->getType();
13639
13640 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
13641 IdentifierInfo *II = D.getIdentifier();
13642 if (II) {
13643 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
13644 ForVisibleRedeclaration);
13645 LookupName(R, S);
13646 if (R.isSingleResult()) {
13647 NamedDecl *PrevDecl = R.getFoundDecl();
13648 if (PrevDecl->isTemplateParameter()) {
13649 // Maybe we will complain about the shadowed template parameter.
13650 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13651 // Just pretend that we didn't see the previous declaration.
13652 PrevDecl = nullptr;
13653 } else if (S->isDeclScope(PrevDecl)) {
13654 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
13655 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13656
13657 // Recover by removing the name
13658 II = nullptr;
13659 D.SetIdentifier(nullptr, D.getIdentifierLoc());
13660 D.setInvalidType(true);
13661 }
13662 }
13663 }
13664
13665 // Temporarily put parameter variables in the translation unit, not
13666 // the enclosing context. This prevents them from accidentally
13667 // looking like class members in C++.
13668 ParmVarDecl *New =
13669 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
13670 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
13671
13672 if (D.isInvalidType())
13673 New->setInvalidDecl();
13674
13675 assert(S->isFunctionPrototypeScope())((S->isFunctionPrototypeScope()) ? static_cast<void>
(0) : __assert_fail ("S->isFunctionPrototypeScope()", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 13675, __PRETTY_FUNCTION__))
;
13676 assert(S->getFunctionPrototypeDepth() >= 1)((S->getFunctionPrototypeDepth() >= 1) ? static_cast<
void> (0) : __assert_fail ("S->getFunctionPrototypeDepth() >= 1"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 13676, __PRETTY_FUNCTION__))
;
13677 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
13678 S->getNextFunctionPrototypeIndex());
13679
13680 // Add the parameter declaration into this scope.
13681 S->AddDecl(New);
13682 if (II)
13683 IdResolver.AddDecl(New);
13684
13685 ProcessDeclAttributes(S, New, D);
13686
13687 if (D.getDeclSpec().isModulePrivateSpecified())
13688 Diag(New->getLocation(), diag::err_module_private_local)
13689 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13690 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13691
13692 if (New->hasAttr<BlocksAttr>()) {
13693 Diag(New->getLocation(), diag::err_block_on_nonlocal);
13694 }
13695
13696 if (getLangOpts().OpenCL)
13697 deduceOpenCLAddressSpace(New);
13698
13699 return New;
13700}
13701
13702/// Synthesizes a variable for a parameter arising from a
13703/// typedef.
13704ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
13705 SourceLocation Loc,
13706 QualType T) {
13707 /* FIXME: setting StartLoc == Loc.
13708 Would it be worth to modify callers so as to provide proper source
13709 location for the unnamed parameters, embedding the parameter's type? */
13710 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
13711 T, Context.getTrivialTypeSourceInfo(T, Loc),
13712 SC_None, nullptr);
13713 Param->setImplicit();
13714 return Param;
13715}
13716
13717void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
13718 // Don't diagnose unused-parameter errors in template instantiations; we
13719 // will already have done so in the template itself.
13720 if (inTemplateInstantiation())
13721 return;
13722
13723 for (const ParmVarDecl *Parameter : Parameters) {
13724 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
13725 !Parameter->hasAttr<UnusedAttr>()) {
13726 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
13727 << Parameter->getDeclName();
13728 }
13729 }
13730}
13731
13732void Sema::DiagnoseSizeOfParametersAndReturnValue(
13733 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
13734 if (LangOpts.NumLargeByValueCopy == 0) // No check.
13735 return;
13736
13737 // Warn if the return value is pass-by-value and larger than the specified
13738 // threshold.
13739 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
13740 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
13741 if (Size > LangOpts.NumLargeByValueCopy)
13742 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
13743 }
13744
13745 // Warn if any parameter is pass-by-value and larger than the specified
13746 // threshold.
13747 for (const ParmVarDecl *Parameter : Parameters) {
13748 QualType T = Parameter->getType();
13749 if (T->isDependentType() || !T.isPODType(Context))
13750 continue;
13751 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
13752 if (Size > LangOpts.NumLargeByValueCopy)
13753 Diag(Parameter->getLocation(), diag::warn_parameter_size)
13754 << Parameter << Size;
13755 }
13756}
13757
13758ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
13759 SourceLocation NameLoc, IdentifierInfo *Name,
13760 QualType T, TypeSourceInfo *TSInfo,
13761 StorageClass SC) {
13762 // In ARC, infer a lifetime qualifier for appropriate parameter types.
13763 if (getLangOpts().ObjCAutoRefCount &&
13764 T.getObjCLifetime() == Qualifiers::OCL_None &&
13765 T->isObjCLifetimeType()) {
13766
13767 Qualifiers::ObjCLifetime lifetime;
13768
13769 // Special cases for arrays:
13770 // - if it's const, use __unsafe_unretained
13771 // - otherwise, it's an error
13772 if (T->isArrayType()) {
13773 if (!T.isConstQualified()) {
13774 if (DelayedDiagnostics.shouldDelayDiagnostics())
13775 DelayedDiagnostics.add(
13776 sema::DelayedDiagnostic::makeForbiddenType(
13777 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
13778 else
13779 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
13780 << TSInfo->getTypeLoc().getSourceRange();
13781 }
13782 lifetime = Qualifiers::OCL_ExplicitNone;
13783 } else {
13784 lifetime = T->getObjCARCImplicitLifetime();
13785 }
13786 T = Context.getLifetimeQualifiedType(T, lifetime);
13787 }
13788
13789 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
13790 Context.getAdjustedParameterType(T),
13791 TSInfo, SC, nullptr);
13792
13793 // Make a note if we created a new pack in the scope of a lambda, so that
13794 // we know that references to that pack must also be expanded within the
13795 // lambda scope.
13796 if (New->isParameterPack())
13797 if (auto *LSI = getEnclosingLambda())
13798 LSI->LocalPacks.push_back(New);
13799
13800 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
13801 New->getType().hasNonTrivialToPrimitiveCopyCUnion())
13802 checkNonTrivialCUnion(New->getType(), New->getLocation(),
13803 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
13804
13805 // Parameters can not be abstract class types.
13806 // For record types, this is done by the AbstractClassUsageDiagnoser once
13807 // the class has been completely parsed.
13808 if (!CurContext->isRecord() &&
13809 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
13810 AbstractParamType))
13811 New->setInvalidDecl();
13812
13813 // Parameter declarators cannot be interface types. All ObjC objects are
13814 // passed by reference.
13815 if (T->isObjCObjectType()) {
13816 SourceLocation TypeEndLoc =
13817 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
13818 Diag(NameLoc,
13819 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
13820 << FixItHint::CreateInsertion(TypeEndLoc, "*");
13821 T = Context.getObjCObjectPointerType(T);
13822 New->setType(T);
13823 }
13824
13825 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
13826 // duration shall not be qualified by an address-space qualifier."
13827 // Since all parameters have automatic store duration, they can not have
13828 // an address space.
13829 if (T.getAddressSpace() != LangAS::Default &&
13830 // OpenCL allows function arguments declared to be an array of a type
13831 // to be qualified with an address space.
13832 !(getLangOpts().OpenCL &&
13833 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
13834 Diag(NameLoc, diag::err_arg_with_address_space);
13835 New->setInvalidDecl();
13836 }
13837
13838 // PPC MMA non-pointer types are not allowed as function argument types.
13839 if (Context.getTargetInfo().getTriple().isPPC64() &&
13840 CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
13841 New->setInvalidDecl();
13842 }
13843
13844 return New;
13845}
13846
13847void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
13848 SourceLocation LocAfterDecls) {
13849 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
13850
13851 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
13852 // for a K&R function.
13853 if (!FTI.hasPrototype) {
13854 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
13855 --i;
13856 if (FTI.Params[i].Param == nullptr) {
13857 SmallString<256> Code;
13858 llvm::raw_svector_ostream(Code)
13859 << " int " << FTI.Params[i].Ident->getName() << ";\n";
13860 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
13861 << FTI.Params[i].Ident
13862 << FixItHint::CreateInsertion(LocAfterDecls, Code);
13863
13864 // Implicitly declare the argument as type 'int' for lack of a better
13865 // type.
13866 AttributeFactory attrs;
13867 DeclSpec DS(attrs);
13868 const char* PrevSpec; // unused
13869 unsigned DiagID; // unused
13870 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
13871 DiagID, Context.getPrintingPolicy());
13872 // Use the identifier location for the type source range.
13873 DS.SetRangeStart(FTI.Params[i].IdentLoc);
13874 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
13875 Declarator ParamD(DS, DeclaratorContext::KNRTypeList);
13876 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
13877 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
13878 }
13879 }
13880 }
13881}
13882
13883Decl *
13884Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
13885 MultiTemplateParamsArg TemplateParameterLists,
13886 SkipBodyInfo *SkipBody) {
13887 assert(getCurFunctionDecl() == nullptr && "Function parsing confused")((getCurFunctionDecl() == nullptr && "Function parsing confused"
) ? static_cast<void> (0) : __assert_fail ("getCurFunctionDecl() == nullptr && \"Function parsing confused\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 13887, __PRETTY_FUNCTION__))
;
13888 assert(D.isFunctionDeclarator() && "Not a function declarator!")((D.isFunctionDeclarator() && "Not a function declarator!"
) ? static_cast<void> (0) : __assert_fail ("D.isFunctionDeclarator() && \"Not a function declarator!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 13888, __PRETTY_FUNCTION__))
;
13889 Scope *ParentScope = FnBodyScope->getParent();
13890
13891 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
13892 // we define a non-templated function definition, we will create a declaration
13893 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
13894 // The base function declaration will have the equivalent of an `omp declare
13895 // variant` annotation which specifies the mangled definition as a
13896 // specialization function under the OpenMP context defined as part of the
13897 // `omp begin declare variant`.
13898 SmallVector<FunctionDecl *, 4> Bases;
13899 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
13900 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
13901 ParentScope, D, TemplateParameterLists, Bases);
13902
13903 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
13904 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
13905 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
13906
13907 if (!Bases.empty())
13908 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
13909
13910 return Dcl;
13911}
13912
13913void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
13914 Consumer.HandleInlineFunctionDefinition(D);
13915}
13916
13917static bool
13918ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
13919 const FunctionDecl *&PossiblePrototype) {
13920 // Don't warn about invalid declarations.
13921 if (FD->isInvalidDecl())
13922 return false;
13923
13924 // Or declarations that aren't global.
13925 if (!FD->isGlobal())
13926 return false;
13927
13928 // Don't warn about C++ member functions.
13929 if (isa<CXXMethodDecl>(FD))
13930 return false;
13931
13932 // Don't warn about 'main'.
13933 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
13934 if (IdentifierInfo *II = FD->getIdentifier())
13935 if (II->isStr("main") || II->isStr("efi_main"))
13936 return false;
13937
13938 // Don't warn about inline functions.
13939 if (FD->isInlined())
13940 return false;
13941
13942 // Don't warn about function templates.
13943 if (FD->getDescribedFunctionTemplate())
13944 return false;
13945
13946 // Don't warn about function template specializations.
13947 if (FD->isFunctionTemplateSpecialization())
13948 return false;
13949
13950 // Don't warn for OpenCL kernels.
13951 if (FD->hasAttr<OpenCLKernelAttr>())
13952 return false;
13953
13954 // Don't warn on explicitly deleted functions.
13955 if (FD->isDeleted())
13956 return false;
13957
13958 for (const FunctionDecl *Prev = FD->getPreviousDecl();
13959 Prev; Prev = Prev->getPreviousDecl()) {
13960 // Ignore any declarations that occur in function or method
13961 // scope, because they aren't visible from the header.
13962 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
13963 continue;
13964
13965 PossiblePrototype = Prev;
13966 return Prev->getType()->isFunctionNoProtoType();
13967 }
13968
13969 return true;
13970}
13971
13972void
13973Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
13974 const FunctionDecl *EffectiveDefinition,
13975 SkipBodyInfo *SkipBody) {
13976 const FunctionDecl *Definition = EffectiveDefinition;
13977 if (!Definition &&
13978 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
13979 return;
13980
13981 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
13982 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
13983 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
13984 // A merged copy of the same function, instantiated as a member of
13985 // the same class, is OK.
13986 if (declaresSameEntity(OrigFD, OrigDef) &&
13987 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
13988 cast<Decl>(FD->getLexicalDeclContext())))
13989 return;
13990 }
13991 }
13992 }
13993
13994 if (canRedefineFunction(Definition, getLangOpts()))
13995 return;
13996
13997 // Don't emit an error when this is redefinition of a typo-corrected
13998 // definition.
13999 if (TypoCorrectedFunctionDefinitions.count(Definition))
14000 return;
14001
14002 // If we don't have a visible definition of the function, and it's inline or
14003 // a template, skip the new definition.
14004 if (SkipBody && !hasVisibleDefinition(Definition) &&
14005 (Definition->getFormalLinkage() == InternalLinkage ||
14006 Definition->isInlined() ||
14007 Definition->getDescribedFunctionTemplate() ||
14008 Definition->getNumTemplateParameterLists())) {
14009 SkipBody->ShouldSkip = true;
14010 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
14011 if (auto *TD = Definition->getDescribedFunctionTemplate())
14012 makeMergedDefinitionVisible(TD);
14013 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
14014 return;
14015 }
14016
14017 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
14018 Definition->getStorageClass() == SC_Extern)
14019 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
14020 << FD << getLangOpts().CPlusPlus;
14021 else
14022 Diag(FD->getLocation(), diag::err_redefinition) << FD;
14023
14024 Diag(Definition->getLocation(), diag::note_previous_definition);
14025 FD->setInvalidDecl();
14026}
14027
14028static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
14029 Sema &S) {
14030 CXXRecordDecl *const LambdaClass = CallOperator->getParent();
14031
14032 LambdaScopeInfo *LSI = S.PushLambdaScope();
14033 LSI->CallOperator = CallOperator;
14034 LSI->Lambda = LambdaClass;
14035 LSI->ReturnType = CallOperator->getReturnType();
14036 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
14037
14038 if (LCD == LCD_None)
14039 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
14040 else if (LCD == LCD_ByCopy)
14041 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
14042 else if (LCD == LCD_ByRef)
14043 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
14044 DeclarationNameInfo DNI = CallOperator->getNameInfo();
14045
14046 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
14047 LSI->Mutable = !CallOperator->isConst();
14048
14049 // Add the captures to the LSI so they can be noted as already
14050 // captured within tryCaptureVar.
14051 auto I = LambdaClass->field_begin();
14052 for (const auto &C : LambdaClass->captures()) {
14053 if (C.capturesVariable()) {
14054 VarDecl *VD = C.getCapturedVar();
14055 if (VD->isInitCapture())
14056 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
14057 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
14058 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
14059 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
14060 /*EllipsisLoc*/C.isPackExpansion()
14061 ? C.getEllipsisLoc() : SourceLocation(),
14062 I->getType(), /*Invalid*/false);
14063
14064 } else if (C.capturesThis()) {
14065 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
14066 C.getCaptureKind() == LCK_StarThis);
14067 } else {
14068 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
14069 I->getType());
14070 }
14071 ++I;
14072 }
14073}
14074
14075Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
14076 SkipBodyInfo *SkipBody) {
14077 if (!D) {
14078 // Parsing the function declaration failed in some way. Push on a fake scope
14079 // anyway so we can try to parse the function body.
14080 PushFunctionScope();
14081 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14082 return D;
14083 }
14084
14085 FunctionDecl *FD = nullptr;
14086
14087 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
14088 FD = FunTmpl->getTemplatedDecl();
14089 else
14090 FD = cast<FunctionDecl>(D);
14091
14092 // Do not push if it is a lambda because one is already pushed when building
14093 // the lambda in ActOnStartOfLambdaDefinition().
14094 if (!isLambdaCallOperator(FD))
14095 PushExpressionEvaluationContext(
14096 FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
14097 : ExprEvalContexts.back().Context);
14098
14099 // Check for defining attributes before the check for redefinition.
14100 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
14101 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
14102 FD->dropAttr<AliasAttr>();
14103 FD->setInvalidDecl();
14104 }
14105 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
14106 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
14107 FD->dropAttr<IFuncAttr>();
14108 FD->setInvalidDecl();
14109 }
14110
14111 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
14112 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
14113 Ctor->isDefaultConstructor() &&
14114 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14115 // If this is an MS ABI dllexport default constructor, instantiate any
14116 // default arguments.
14117 InstantiateDefaultCtorDefaultArgs(Ctor);
14118 }
14119 }
14120
14121 // See if this is a redefinition. If 'will have body' (or similar) is already
14122 // set, then these checks were already performed when it was set.
14123 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
14124 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
14125 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
14126
14127 // If we're skipping the body, we're done. Don't enter the scope.
14128 if (SkipBody && SkipBody->ShouldSkip)
14129 return D;
14130 }
14131
14132 // Mark this function as "will have a body eventually". This lets users to
14133 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
14134 // this function.
14135 FD->setWillHaveBody();
14136
14137 // If we are instantiating a generic lambda call operator, push
14138 // a LambdaScopeInfo onto the function stack. But use the information
14139 // that's already been calculated (ActOnLambdaExpr) to prime the current
14140 // LambdaScopeInfo.
14141 // When the template operator is being specialized, the LambdaScopeInfo,
14142 // has to be properly restored so that tryCaptureVariable doesn't try
14143 // and capture any new variables. In addition when calculating potential
14144 // captures during transformation of nested lambdas, it is necessary to
14145 // have the LSI properly restored.
14146 if (isGenericLambdaCallOperatorSpecialization(FD)) {
14147 assert(inTemplateInstantiation() &&((inTemplateInstantiation() && "There should be an active template instantiation on the stack "
"when instantiating a generic lambda!") ? static_cast<void
> (0) : __assert_fail ("inTemplateInstantiation() && \"There should be an active template instantiation on the stack \" \"when instantiating a generic lambda!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 14149, __PRETTY_FUNCTION__))
14148 "There should be an active template instantiation on the stack "((inTemplateInstantiation() && "There should be an active template instantiation on the stack "
"when instantiating a generic lambda!") ? static_cast<void
> (0) : __assert_fail ("inTemplateInstantiation() && \"There should be an active template instantiation on the stack \" \"when instantiating a generic lambda!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 14149, __PRETTY_FUNCTION__))
14149 "when instantiating a generic lambda!")((inTemplateInstantiation() && "There should be an active template instantiation on the stack "
"when instantiating a generic lambda!") ? static_cast<void
> (0) : __assert_fail ("inTemplateInstantiation() && \"There should be an active template instantiation on the stack \" \"when instantiating a generic lambda!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 14149, __PRETTY_FUNCTION__))
;
14150 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
14151 } else {
14152 // Enter a new function scope
14153 PushFunctionScope();
14154 }
14155
14156 // Builtin functions cannot be defined.
14157 if (unsigned BuiltinID = FD->getBuiltinID()) {
14158 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
14159 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
14160 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
14161 FD->setInvalidDecl();
14162 }
14163 }
14164
14165 // The return type of a function definition must be complete
14166 // (C99 6.9.1p3, C++ [dcl.fct]p6).
14167 QualType ResultType = FD->getReturnType();
14168 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
14169 !FD->isInvalidDecl() &&
14170 RequireCompleteType(FD->getLocation(), ResultType,
14171 diag::err_func_def_incomplete_result))
14172 FD->setInvalidDecl();
14173
14174 if (FnBodyScope)
14175 PushDeclContext(FnBodyScope, FD);
14176
14177 // Check the validity of our function parameters
14178 CheckParmsForFunctionDef(FD->parameters(),
14179 /*CheckParameterNames=*/true);
14180
14181 // Add non-parameter declarations already in the function to the current
14182 // scope.
14183 if (FnBodyScope) {
14184 for (Decl *NPD : FD->decls()) {
14185 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
14186 if (!NonParmDecl)
14187 continue;
14188 assert(!isa<ParmVarDecl>(NonParmDecl) &&((!isa<ParmVarDecl>(NonParmDecl) && "parameters should not be in newly created FD yet"
) ? static_cast<void> (0) : __assert_fail ("!isa<ParmVarDecl>(NonParmDecl) && \"parameters should not be in newly created FD yet\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 14189, __PRETTY_FUNCTION__))
14189 "parameters should not be in newly created FD yet")((!isa<ParmVarDecl>(NonParmDecl) && "parameters should not be in newly created FD yet"
) ? static_cast<void> (0) : __assert_fail ("!isa<ParmVarDecl>(NonParmDecl) && \"parameters should not be in newly created FD yet\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 14189, __PRETTY_FUNCTION__))
;
14190
14191 // If the decl has a name, make it accessible in the current scope.
14192 if (NonParmDecl->getDeclName())
14193 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
14194
14195 // Similarly, dive into enums and fish their constants out, making them
14196 // accessible in this scope.
14197 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
14198 for (auto *EI : ED->enumerators())
14199 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
14200 }
14201 }
14202 }
14203
14204 // Introduce our parameters into the function scope
14205 for (auto Param : FD->parameters()) {
14206 Param->setOwningFunction(FD);
14207
14208 // If this has an identifier, add it to the scope stack.
14209 if (Param->getIdentifier() && FnBodyScope) {
14210 CheckShadow(FnBodyScope, Param);
14211
14212 PushOnScopeChains(Param, FnBodyScope);
14213 }
14214 }
14215
14216 // Ensure that the function's exception specification is instantiated.
14217 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
14218 ResolveExceptionSpec(D->getLocation(), FPT);
14219
14220 // dllimport cannot be applied to non-inline function definitions.
14221 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
14222 !FD->isTemplateInstantiation()) {
14223 assert(!FD->hasAttr<DLLExportAttr>())((!FD->hasAttr<DLLExportAttr>()) ? static_cast<void
> (0) : __assert_fail ("!FD->hasAttr<DLLExportAttr>()"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 14223, __PRETTY_FUNCTION__))
;
14224 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
14225 FD->setInvalidDecl();
14226 return D;
14227 }
14228 // We want to attach documentation to original Decl (which might be
14229 // a function template).
14230 ActOnDocumentableDecl(D);
14231 if (getCurLexicalContext()->isObjCContainer() &&
14232 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
14233 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
14234 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
14235
14236 return D;
14237}
14238
14239/// Given the set of return statements within a function body,
14240/// compute the variables that are subject to the named return value
14241/// optimization.
14242///
14243/// Each of the variables that is subject to the named return value
14244/// optimization will be marked as NRVO variables in the AST, and any
14245/// return statement that has a marked NRVO variable as its NRVO candidate can
14246/// use the named return value optimization.
14247///
14248/// This function applies a very simplistic algorithm for NRVO: if every return
14249/// statement in the scope of a variable has the same NRVO candidate, that
14250/// candidate is an NRVO variable.
14251void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
14252 ReturnStmt **Returns = Scope->Returns.data();
14253
14254 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
14255 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
14256 if (!NRVOCandidate->isNRVOVariable())
14257 Returns[I]->setNRVOCandidate(nullptr);
14258 }
14259 }
14260}
14261
14262bool Sema::canDelayFunctionBody(const Declarator &D) {
14263 // We can't delay parsing the body of a constexpr function template (yet).
14264 if (D.getDeclSpec().hasConstexprSpecifier())
14265 return false;
14266
14267 // We can't delay parsing the body of a function template with a deduced
14268 // return type (yet).
14269 if (D.getDeclSpec().hasAutoTypeSpec()) {
14270 // If the placeholder introduces a non-deduced trailing return type,
14271 // we can still delay parsing it.
14272 if (D.getNumTypeObjects()) {
14273 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
14274 if (Outer.Kind == DeclaratorChunk::Function &&
14275 Outer.Fun.hasTrailingReturnType()) {
14276 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
14277 return Ty.isNull() || !Ty->isUndeducedType();
14278 }
14279 }
14280 return false;
14281 }
14282
14283 return true;
14284}
14285
14286bool Sema::canSkipFunctionBody(Decl *D) {
14287 // We cannot skip the body of a function (or function template) which is
14288 // constexpr, since we may need to evaluate its body in order to parse the
14289 // rest of the file.
14290 // We cannot skip the body of a function with an undeduced return type,
14291 // because any callers of that function need to know the type.
14292 if (const FunctionDecl *FD = D->getAsFunction()) {
14293 if (FD->isConstexpr())
14294 return false;
14295 // We can't simply call Type::isUndeducedType here, because inside template
14296 // auto can be deduced to a dependent type, which is not considered
14297 // "undeduced".
14298 if (FD->getReturnType()->getContainedDeducedType())
14299 return false;
14300 }
14301 return Consumer.shouldSkipFunctionBody(D);
14302}
14303
14304Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
14305 if (!Decl)
14306 return nullptr;
14307 if (FunctionDecl *FD = Decl->getAsFunction())
14308 FD->setHasSkippedBody();
14309 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
14310 MD->setHasSkippedBody();
14311 return Decl;
14312}
14313
14314Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
14315 return ActOnFinishFunctionBody(D, BodyArg, false);
14316}
14317
14318/// RAII object that pops an ExpressionEvaluationContext when exiting a function
14319/// body.
14320class ExitFunctionBodyRAII {
14321public:
14322 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
14323 ~ExitFunctionBodyRAII() {
14324 if (!IsLambda)
14325 S.PopExpressionEvaluationContext();
14326 }
14327
14328private:
14329 Sema &S;
14330 bool IsLambda = false;
14331};
14332
14333static void diagnoseImplicitlyRetainedSelf(Sema &S) {
14334 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
14335
14336 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
14337 if (EscapeInfo.count(BD))
14338 return EscapeInfo[BD];
14339
14340 bool R = false;
14341 const BlockDecl *CurBD = BD;
14342
14343 do {
14344 R = !CurBD->doesNotEscape();
14345 if (R)
14346 break;
14347 CurBD = CurBD->getParent()->getInnermostBlockDecl();
14348 } while (CurBD);
14349
14350 return EscapeInfo[BD] = R;
14351 };
14352
14353 // If the location where 'self' is implicitly retained is inside a escaping
14354 // block, emit a diagnostic.
14355 for (const std::pair<SourceLocation, const BlockDecl *> &P :
14356 S.ImplicitlyRetainedSelfLocs)
14357 if (IsOrNestedInEscapingBlock(P.second))
14358 S.Diag(P.first, diag::warn_implicitly_retains_self)
14359 << FixItHint::CreateInsertion(P.first, "self->");
14360}
14361
14362Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
14363 bool IsInstantiation) {
14364 FunctionScopeInfo *FSI = getCurFunction();
14365 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
14366
14367 if (FSI->UsesFPIntrin && !FD->hasAttr<StrictFPAttr>())
14368 FD->addAttr(StrictFPAttr::CreateImplicit(Context));
14369
14370 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14371 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
14372
14373 if (getLangOpts().Coroutines && FSI->isCoroutine())
14374 CheckCompletedCoroutineBody(FD, Body);
14375
14376 // Do not call PopExpressionEvaluationContext() if it is a lambda because one
14377 // is already popped when finishing the lambda in BuildLambdaExpr(). This is
14378 // meant to pop the context added in ActOnStartOfFunctionDef().
14379 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
14380
14381 if (FD) {
14382 FD->setBody(Body);
14383 FD->setWillHaveBody(false);
14384
14385 if (getLangOpts().CPlusPlus14) {
14386 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
14387 FD->getReturnType()->isUndeducedType()) {
14388 // If the function has a deduced result type but contains no 'return'
14389 // statements, the result type as written must be exactly 'auto', and
14390 // the deduced result type is 'void'.
14391 if (!FD->getReturnType()->getAs<AutoType>()) {
14392 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
14393 << FD->getReturnType();
14394 FD->setInvalidDecl();
14395 } else {
14396 // Substitute 'void' for the 'auto' in the type.
14397 TypeLoc ResultType = getReturnTypeLoc(FD);
14398 Context.adjustDeducedFunctionResultType(
14399 FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
14400 }
14401 }
14402 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
14403 // In C++11, we don't use 'auto' deduction rules for lambda call
14404 // operators because we don't support return type deduction.
14405 auto *LSI = getCurLambda();
14406 if (LSI->HasImplicitReturnType) {
14407 deduceClosureReturnType(*LSI);
14408
14409 // C++11 [expr.prim.lambda]p4:
14410 // [...] if there are no return statements in the compound-statement
14411 // [the deduced type is] the type void
14412 QualType RetType =
14413 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
14414
14415 // Update the return type to the deduced type.
14416 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
14417 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
14418 Proto->getExtProtoInfo()));
14419 }
14420 }
14421
14422 // If the function implicitly returns zero (like 'main') or is naked,
14423 // don't complain about missing return statements.
14424 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
14425 WP.disableCheckFallThrough();
14426
14427 // MSVC permits the use of pure specifier (=0) on function definition,
14428 // defined at class scope, warn about this non-standard construct.
14429 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
14430 Diag(FD->getLocation(), diag::ext_pure_function_definition);
14431
14432 if (!FD->isInvalidDecl()) {
14433 // Don't diagnose unused parameters of defaulted or deleted functions.
14434 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
14435 DiagnoseUnusedParameters(FD->parameters());
14436 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
14437 FD->getReturnType(), FD);
14438
14439 // If this is a structor, we need a vtable.
14440 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
14441 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
14442 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
14443 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
14444
14445 // Try to apply the named return value optimization. We have to check
14446 // if we can do this here because lambdas keep return statements around
14447 // to deduce an implicit return type.
14448 if (FD->getReturnType()->isRecordType() &&
14449 (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
14450 computeNRVO(Body, FSI);
14451 }
14452
14453 // GNU warning -Wmissing-prototypes:
14454 // Warn if a global function is defined without a previous
14455 // prototype declaration. This warning is issued even if the
14456 // definition itself provides a prototype. The aim is to detect
14457 // global functions that fail to be declared in header files.
14458 const FunctionDecl *PossiblePrototype = nullptr;
14459 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
14460 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
14461
14462 if (PossiblePrototype) {
14463 // We found a declaration that is not a prototype,
14464 // but that could be a zero-parameter prototype
14465 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
14466 TypeLoc TL = TI->getTypeLoc();
14467 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
14468 Diag(PossiblePrototype->getLocation(),
14469 diag::note_declaration_not_a_prototype)
14470 << (FD->getNumParams() != 0)
14471 << (FD->getNumParams() == 0
14472 ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
14473 : FixItHint{});
14474 }
14475 } else {
14476 // Returns true if the token beginning at this Loc is `const`.
14477 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
14478 const LangOptions &LangOpts) {
14479 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
14480 if (LocInfo.first.isInvalid())
14481 return false;
14482
14483 bool Invalid = false;
14484 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
14485 if (Invalid)
14486 return false;
14487
14488 if (LocInfo.second > Buffer.size())
14489 return false;
14490
14491 const char *LexStart = Buffer.data() + LocInfo.second;
14492 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
14493
14494 return StartTok.consume_front("const") &&
14495 (StartTok.empty() || isWhitespace(StartTok[0]) ||
14496 StartTok.startswith("/*") || StartTok.startswith("//"));
14497 };
14498
14499 auto findBeginLoc = [&]() {
14500 // If the return type has `const` qualifier, we want to insert
14501 // `static` before `const` (and not before the typename).
14502 if ((FD->getReturnType()->isAnyPointerType() &&
14503 FD->getReturnType()->getPointeeType().isConstQualified()) ||
14504 FD->getReturnType().isConstQualified()) {
14505 // But only do this if we can determine where the `const` is.
14506
14507 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
14508 getLangOpts()))
14509
14510 return FD->getBeginLoc();
14511 }
14512 return FD->getTypeSpecStartLoc();
14513 };
14514 Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14515 << /* function */ 1
14516 << (FD->getStorageClass() == SC_None
14517 ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
14518 : FixItHint{});
14519 }
14520
14521 // GNU warning -Wstrict-prototypes
14522 // Warn if K&R function is defined without a previous declaration.
14523 // This warning is issued only if the definition itself does not provide
14524 // a prototype. Only K&R definitions do not provide a prototype.
14525 if (!FD->hasWrittenPrototype()) {
14526 TypeSourceInfo *TI = FD->getTypeSourceInfo();
14527 TypeLoc TL = TI->getTypeLoc();
14528 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
14529 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
14530 }
14531 }
14532
14533 // Warn on CPUDispatch with an actual body.
14534 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
14535 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
14536 if (!CmpndBody->body_empty())
14537 Diag(CmpndBody->body_front()->getBeginLoc(),
14538 diag::warn_dispatch_body_ignored);
14539
14540 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
14541 const CXXMethodDecl *KeyFunction;
14542 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
14543 MD->isVirtual() &&
14544 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
14545 MD == KeyFunction->getCanonicalDecl()) {
14546 // Update the key-function state if necessary for this ABI.
14547 if (FD->isInlined() &&
14548 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
14549 Context.setNonKeyFunction(MD);
14550
14551 // If the newly-chosen key function is already defined, then we
14552 // need to mark the vtable as used retroactively.
14553 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
14554 const FunctionDecl *Definition;
14555 if (KeyFunction && KeyFunction->isDefined(Definition))
14556 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
14557 } else {
14558 // We just defined they key function; mark the vtable as used.
14559 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
14560 }
14561 }
14562 }
14563
14564 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&(((FD == getCurFunctionDecl() || getCurLambda()->CallOperator
== FD) && "Function parsing confused") ? static_cast
<void> (0) : __assert_fail ("(FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && \"Function parsing confused\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 14565, __PRETTY_FUNCTION__))
14565 "Function parsing confused")(((FD == getCurFunctionDecl() || getCurLambda()->CallOperator
== FD) && "Function parsing confused") ? static_cast
<void> (0) : __assert_fail ("(FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && \"Function parsing confused\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 14565, __PRETTY_FUNCTION__))
;
14566 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
14567 assert(MD == getCurMethodDecl() && "Method parsing confused")((MD == getCurMethodDecl() && "Method parsing confused"
) ? static_cast<void> (0) : __assert_fail ("MD == getCurMethodDecl() && \"Method parsing confused\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 14567, __PRETTY_FUNCTION__))
;
14568 MD->setBody(Body);
14569 if (!MD->isInvalidDecl()) {
14570 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
14571 MD->getReturnType(), MD);
14572
14573 if (Body)
14574 computeNRVO(Body, FSI);
14575 }
14576 if (FSI->ObjCShouldCallSuper) {
14577 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
14578 << MD->getSelector().getAsString();
14579 FSI->ObjCShouldCallSuper = false;
14580 }
14581 if (FSI->ObjCWarnForNoDesignatedInitChain) {
14582 const ObjCMethodDecl *InitMethod = nullptr;
14583 bool isDesignated =
14584 MD->isDesignatedInitializerForTheInterface(&InitMethod);
14585 assert(isDesignated && InitMethod)((isDesignated && InitMethod) ? static_cast<void>
(0) : __assert_fail ("isDesignated && InitMethod", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 14585, __PRETTY_FUNCTION__))
;
14586 (void)isDesignated;
14587
14588 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
14589 auto IFace = MD->getClassInterface();
14590 if (!IFace)
14591 return false;
14592 auto SuperD = IFace->getSuperClass();
14593 if (!SuperD)
14594 return false;
14595 return SuperD->getIdentifier() ==
14596 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
14597 };
14598 // Don't issue this warning for unavailable inits or direct subclasses
14599 // of NSObject.
14600 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
14601 Diag(MD->getLocation(),
14602 diag::warn_objc_designated_init_missing_super_call);
14603 Diag(InitMethod->getLocation(),
14604 diag::note_objc_designated_init_marked_here);
14605 }
14606 FSI->ObjCWarnForNoDesignatedInitChain = false;
14607 }
14608 if (FSI->ObjCWarnForNoInitDelegation) {
14609 // Don't issue this warning for unavaialable inits.
14610 if (!MD->isUnavailable())
14611 Diag(MD->getLocation(),
14612 diag::warn_objc_secondary_init_missing_init_call);
14613 FSI->ObjCWarnForNoInitDelegation = false;
14614 }
14615
14616 diagnoseImplicitlyRetainedSelf(*this);
14617 } else {
14618 // Parsing the function declaration failed in some way. Pop the fake scope
14619 // we pushed on.
14620 PopFunctionScopeInfo(ActivePolicy, dcl);
14621 return nullptr;
14622 }
14623
14624 if (Body && FSI->HasPotentialAvailabilityViolations)
14625 DiagnoseUnguardedAvailabilityViolations(dcl);
14626
14627 assert(!FSI->ObjCShouldCallSuper &&((!FSI->ObjCShouldCallSuper && "This should only be set for ObjC methods, which should have been "
"handled in the block above.") ? static_cast<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-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 14629, __PRETTY_FUNCTION__))
14628 "This should only be set for ObjC methods, which should have been "((!FSI->ObjCShouldCallSuper && "This should only be set for ObjC methods, which should have been "
"handled in the block above.") ? static_cast<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-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 14629, __PRETTY_FUNCTION__))
14629 "handled in the block above.")((!FSI->ObjCShouldCallSuper && "This should only be set for ObjC methods, which should have been "
"handled in the block above.") ? static_cast<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-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 14629, __PRETTY_FUNCTION__))
;
14630
14631 // Verify and clean out per-function state.
14632 if (Body && (!FD || !FD->isDefaulted())) {
14633 // C++ constructors that have function-try-blocks can't have return
14634 // statements in the handlers of that block. (C++ [except.handle]p14)
14635 // Verify this.
14636 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
14637 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
14638
14639 // Verify that gotos and switch cases don't jump into scopes illegally.
14640 if (FSI->NeedsScopeChecking() &&
14641 !PP.isCodeCompletionEnabled())
14642 DiagnoseInvalidJumps(Body);
14643
14644 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
14645 if (!Destructor->getParent()->isDependentType())
14646 CheckDestructor(Destructor);
14647
14648 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14649 Destructor->getParent());
14650 }
14651
14652 // If any errors have occurred, clear out any temporaries that may have
14653 // been leftover. This ensures that these temporaries won't be picked up for
14654 // deletion in some later function.
14655 if (hasUncompilableErrorOccurred() ||
14656 getDiagnostics().getSuppressAllDiagnostics()) {
14657 DiscardCleanupsInEvaluationContext();
14658 }
14659 if (!hasUncompilableErrorOccurred() &&
14660 !isa<FunctionTemplateDecl>(dcl)) {
14661 // Since the body is valid, issue any analysis-based warnings that are
14662 // enabled.
14663 ActivePolicy = &WP;
14664 }
14665
14666 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
14667 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
14668 FD->setInvalidDecl();
14669
14670 if (FD && FD->hasAttr<NakedAttr>()) {
14671 for (const Stmt *S : Body->children()) {
14672 // Allow local register variables without initializer as they don't
14673 // require prologue.
14674 bool RegisterVariables = false;
14675 if (auto *DS = dyn_cast<DeclStmt>(S)) {
14676 for (const auto *Decl : DS->decls()) {
14677 if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
14678 RegisterVariables =
14679 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
14680 if (!RegisterVariables)
14681 break;
14682 }
14683 }
14684 }
14685 if (RegisterVariables)
14686 continue;
14687 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
14688 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
14689 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
14690 FD->setInvalidDecl();
14691 break;
14692 }
14693 }
14694 }
14695
14696 assert(ExprCleanupObjects.size() ==((ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects
&& "Leftover temporaries in function") ? static_cast
<void> (0) : __assert_fail ("ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && \"Leftover temporaries in function\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 14698, __PRETTY_FUNCTION__))
14697 ExprEvalContexts.back().NumCleanupObjects &&((ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects
&& "Leftover temporaries in function") ? static_cast
<void> (0) : __assert_fail ("ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && \"Leftover temporaries in function\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 14698, __PRETTY_FUNCTION__))
14698 "Leftover temporaries in function")((ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects
&& "Leftover temporaries in function") ? static_cast
<void> (0) : __assert_fail ("ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && \"Leftover temporaries in function\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 14698, __PRETTY_FUNCTION__))
;
14699 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function")((!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"
) ? static_cast<void> (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"Unaccounted cleanups in function\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 14699, __PRETTY_FUNCTION__))
;
14700 assert(MaybeODRUseExprs.empty() &&((MaybeODRUseExprs.empty() && "Leftover expressions for odr-use checking"
) ? static_cast<void> (0) : __assert_fail ("MaybeODRUseExprs.empty() && \"Leftover expressions for odr-use checking\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 14701, __PRETTY_FUNCTION__))
14701 "Leftover expressions for odr-use checking")((MaybeODRUseExprs.empty() && "Leftover expressions for odr-use checking"
) ? static_cast<void> (0) : __assert_fail ("MaybeODRUseExprs.empty() && \"Leftover expressions for odr-use checking\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 14701, __PRETTY_FUNCTION__))
;
14702 }
14703
14704 if (!IsInstantiation)
14705 PopDeclContext();
14706
14707 PopFunctionScopeInfo(ActivePolicy, dcl);
14708 // If any errors have occurred, clear out any temporaries that may have
14709 // been leftover. This ensures that these temporaries won't be picked up for
14710 // deletion in some later function.
14711 if (hasUncompilableErrorOccurred()) {
14712 DiscardCleanupsInEvaluationContext();
14713 }
14714
14715 if (FD && (LangOpts.OpenMP || LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
14716 auto ES = getEmissionStatus(FD);
14717 if (ES == Sema::FunctionEmissionStatus::Emitted ||
14718 ES == Sema::FunctionEmissionStatus::Unknown)
14719 DeclsToCheckForDeferredDiags.push_back(FD);
14720 }
14721
14722 return dcl;
14723}
14724
14725/// When we finish delayed parsing of an attribute, we must attach it to the
14726/// relevant Decl.
14727void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
14728 ParsedAttributes &Attrs) {
14729 // Always attach attributes to the underlying decl.
14730 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
14731 D = TD->getTemplatedDecl();
14732 ProcessDeclAttributeList(S, D, Attrs);
14733
14734 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
14735 if (Method->isStatic())
14736 checkThisInStaticMemberFunctionAttributes(Method);
14737}
14738
14739/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
14740/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
14741NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
14742 IdentifierInfo &II, Scope *S) {
14743 // Find the scope in which the identifier is injected and the corresponding
14744 // DeclContext.
14745 // FIXME: C89 does not say what happens if there is no enclosing block scope.
14746 // In that case, we inject the declaration into the translation unit scope
14747 // instead.
14748 Scope *BlockScope = S;
14749 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
14750 BlockScope = BlockScope->getParent();
14751
14752 Scope *ContextScope = BlockScope;
14753 while (!ContextScope->getEntity())
14754 ContextScope = ContextScope->getParent();
14755 ContextRAII SavedContext(*this, ContextScope->getEntity());
14756
14757 // Before we produce a declaration for an implicitly defined
14758 // function, see whether there was a locally-scoped declaration of
14759 // this name as a function or variable. If so, use that
14760 // (non-visible) declaration, and complain about it.
14761 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
14762 if (ExternCPrev) {
14763 // We still need to inject the function into the enclosing block scope so
14764 // that later (non-call) uses can see it.
14765 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
14766
14767 // C89 footnote 38:
14768 // If in fact it is not defined as having type "function returning int",
14769 // the behavior is undefined.
14770 if (!isa<FunctionDecl>(ExternCPrev) ||
14771 !Context.typesAreCompatible(
14772 cast<FunctionDecl>(ExternCPrev)->getType(),
14773 Context.getFunctionNoProtoType(Context.IntTy))) {
14774 Diag(Loc, diag::ext_use_out_of_scope_declaration)
14775 << ExternCPrev << !getLangOpts().C99;
14776 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
14777 return ExternCPrev;
14778 }
14779 }
14780
14781 // Extension in C99. Legal in C90, but warn about it.
14782 unsigned diag_id;
14783 if (II.getName().startswith("__builtin_"))
14784 diag_id = diag::warn_builtin_unknown;
14785 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
14786 else if (getLangOpts().OpenCL)
14787 diag_id = diag::err_opencl_implicit_function_decl;
14788 else if (getLangOpts().C99)
14789 diag_id = diag::ext_implicit_function_decl;
14790 else
14791 diag_id = diag::warn_implicit_function_decl;
14792 Diag(Loc, diag_id) << &II;
14793
14794 // If we found a prior declaration of this function, don't bother building
14795 // another one. We've already pushed that one into scope, so there's nothing
14796 // more to do.
14797 if (ExternCPrev)
14798 return ExternCPrev;
14799
14800 // Because typo correction is expensive, only do it if the implicit
14801 // function declaration is going to be treated as an error.
14802 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
14803 TypoCorrection Corrected;
14804 DeclFilterCCC<FunctionDecl> CCC{};
14805 if (S && (Corrected =
14806 CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
14807 S, nullptr, CCC, CTK_NonError)))
14808 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
14809 /*ErrorRecovery*/false);
14810 }
14811
14812 // Set a Declarator for the implicit definition: int foo();
14813 const char *Dummy;
14814 AttributeFactory attrFactory;
14815 DeclSpec DS(attrFactory);
14816 unsigned DiagID;
14817 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
14818 Context.getPrintingPolicy());
14819 (void)Error; // Silence warning.
14820 assert(!Error && "Error setting up implicit decl!")((!Error && "Error setting up implicit decl!") ? static_cast
<void> (0) : __assert_fail ("!Error && \"Error setting up implicit decl!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 14820, __PRETTY_FUNCTION__))
;
14821 SourceLocation NoLoc;
14822 Declarator D(DS, DeclaratorContext::Block);
14823 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
14824 /*IsAmbiguous=*/false,
14825 /*LParenLoc=*/NoLoc,
14826 /*Params=*/nullptr,
14827 /*NumParams=*/0,
14828 /*EllipsisLoc=*/NoLoc,
14829 /*RParenLoc=*/NoLoc,
14830 /*RefQualifierIsLvalueRef=*/true,
14831 /*RefQualifierLoc=*/NoLoc,
14832 /*MutableLoc=*/NoLoc, EST_None,
14833 /*ESpecRange=*/SourceRange(),
14834 /*Exceptions=*/nullptr,
14835 /*ExceptionRanges=*/nullptr,
14836 /*NumExceptions=*/0,
14837 /*NoexceptExpr=*/nullptr,
14838 /*ExceptionSpecTokens=*/nullptr,
14839 /*DeclsInPrototype=*/None, Loc,
14840 Loc, D),
14841 std::move(DS.getAttributes()), SourceLocation());
14842 D.SetIdentifier(&II, Loc);
14843
14844 // Insert this function into the enclosing block scope.
14845 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
14846 FD->setImplicit();
14847
14848 AddKnownFunctionAttributes(FD);
14849
14850 return FD;
14851}
14852
14853/// If this function is a C++ replaceable global allocation function
14854/// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
14855/// adds any function attributes that we know a priori based on the standard.
14856///
14857/// We need to check for duplicate attributes both here and where user-written
14858/// attributes are applied to declarations.
14859void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
14860 FunctionDecl *FD) {
14861 if (FD->isInvalidDecl())
14862 return;
14863
14864 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
14865 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
14866 return;
14867
14868 Optional<unsigned> AlignmentParam;
14869 bool IsNothrow = false;
14870 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
14871 return;
14872
14873 // C++2a [basic.stc.dynamic.allocation]p4:
14874 // An allocation function that has a non-throwing exception specification
14875 // indicates failure by returning a null pointer value. Any other allocation
14876 // function never returns a null pointer value and indicates failure only by
14877 // throwing an exception [...]
14878 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
14879 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
14880
14881 // C++2a [basic.stc.dynamic.allocation]p2:
14882 // An allocation function attempts to allocate the requested amount of
14883 // storage. [...] If the request succeeds, the value returned by a
14884 // replaceable allocation function is a [...] pointer value p0 different
14885 // from any previously returned value p1 [...]
14886 //
14887 // However, this particular information is being added in codegen,
14888 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
14889
14890 // C++2a [basic.stc.dynamic.allocation]p2:
14891 // An allocation function attempts to allocate the requested amount of
14892 // storage. If it is successful, it returns the address of the start of a
14893 // block of storage whose length in bytes is at least as large as the
14894 // requested size.
14895 if (!FD->hasAttr<AllocSizeAttr>()) {
14896 FD->addAttr(AllocSizeAttr::CreateImplicit(
14897 Context, /*ElemSizeParam=*/ParamIdx(1, FD),
14898 /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
14899 }
14900
14901 // C++2a [basic.stc.dynamic.allocation]p3:
14902 // For an allocation function [...], the pointer returned on a successful
14903 // call shall represent the address of storage that is aligned as follows:
14904 // (3.1) If the allocation function takes an argument of type
14905 // std​::​align_­val_­t, the storage will have the alignment
14906 // specified by the value of this argument.
14907 if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) {
14908 FD->addAttr(AllocAlignAttr::CreateImplicit(
14909 Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation()));
14910 }
14911
14912 // FIXME:
14913 // C++2a [basic.stc.dynamic.allocation]p3:
14914 // For an allocation function [...], the pointer returned on a successful
14915 // call shall represent the address of storage that is aligned as follows:
14916 // (3.2) Otherwise, if the allocation function is named operator new[],
14917 // the storage is aligned for any object that does not have
14918 // new-extended alignment ([basic.align]) and is no larger than the
14919 // requested size.
14920 // (3.3) Otherwise, the storage is aligned for any object that does not
14921 // have new-extended alignment and is of the requested size.
14922}
14923
14924/// Adds any function attributes that we know a priori based on
14925/// the declaration of this function.
14926///
14927/// These attributes can apply both to implicitly-declared builtins
14928/// (like __builtin___printf_chk) or to library-declared functions
14929/// like NSLog or printf.
14930///
14931/// We need to check for duplicate attributes both here and where user-written
14932/// attributes are applied to declarations.
14933void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
14934 if (FD->isInvalidDecl())
14935 return;
14936
14937 // If this is a built-in function, map its builtin attributes to
14938 // actual attributes.
14939 if (unsigned BuiltinID = FD->getBuiltinID()) {
14940 // Handle printf-formatting attributes.
14941 unsigned FormatIdx;
14942 bool HasVAListArg;
14943 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
14944 if (!FD->hasAttr<FormatAttr>()) {
14945 const char *fmt = "printf";
14946 unsigned int NumParams = FD->getNumParams();
14947 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
14948 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
14949 fmt = "NSString";
14950 FD->addAttr(FormatAttr::CreateImplicit(Context,
14951 &Context.Idents.get(fmt),
14952 FormatIdx+1,
14953 HasVAListArg ? 0 : FormatIdx+2,
14954 FD->getLocation()));
14955 }
14956 }
14957 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
14958 HasVAListArg)) {
14959 if (!FD->hasAttr<FormatAttr>())
14960 FD->addAttr(FormatAttr::CreateImplicit(Context,
14961 &Context.Idents.get("scanf"),
14962 FormatIdx+1,
14963 HasVAListArg ? 0 : FormatIdx+2,
14964 FD->getLocation()));
14965 }
14966
14967 // Handle automatically recognized callbacks.
14968 SmallVector<int, 4> Encoding;
14969 if (!FD->hasAttr<CallbackAttr>() &&
14970 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
14971 FD->addAttr(CallbackAttr::CreateImplicit(
14972 Context, Encoding.data(), Encoding.size(), FD->getLocation()));
14973
14974 // Mark const if we don't care about errno and that is the only thing
14975 // preventing the function from being const. This allows IRgen to use LLVM
14976 // intrinsics for such functions.
14977 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
14978 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
14979 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14980
14981 // We make "fma" on some platforms const because we know it does not set
14982 // errno in those environments even though it could set errno based on the
14983 // C standard.
14984 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
14985 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
14986 !FD->hasAttr<ConstAttr>()) {
14987 switch (BuiltinID) {
14988 case Builtin::BI__builtin_fma:
14989 case Builtin::BI__builtin_fmaf:
14990 case Builtin::BI__builtin_fmal:
14991 case Builtin::BIfma:
14992 case Builtin::BIfmaf:
14993 case Builtin::BIfmal:
14994 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14995 break;
14996 default:
14997 break;
14998 }
14999 }
15000
15001 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
15002 !FD->hasAttr<ReturnsTwiceAttr>())
15003 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
15004 FD->getLocation()));
15005 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
15006 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15007 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
15008 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
15009 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
15010 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15011 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
15012 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
15013 // Add the appropriate attribute, depending on the CUDA compilation mode
15014 // and which target the builtin belongs to. For example, during host
15015 // compilation, aux builtins are __device__, while the rest are __host__.
15016 if (getLangOpts().CUDAIsDevice !=
15017 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
15018 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
15019 else
15020 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
15021 }
15022 }
15023
15024 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
15025
15026 // If C++ exceptions are enabled but we are told extern "C" functions cannot
15027 // throw, add an implicit nothrow attribute to any extern "C" function we come
15028 // across.
15029 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
15030 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
15031 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
15032 if (!FPT || FPT->getExceptionSpecType() == EST_None)
15033 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15034 }
15035
15036 IdentifierInfo *Name = FD->getIdentifier();
15037 if (!Name)
15038 return;
15039 if ((!getLangOpts().CPlusPlus &&
15040 FD->getDeclContext()->isTranslationUnit()) ||
15041 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
15042 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
15043 LinkageSpecDecl::lang_c)) {
15044 // Okay: this could be a libc/libm/Objective-C function we know
15045 // about.
15046 } else
15047 return;
15048
15049 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
15050 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
15051 // target-specific builtins, perhaps?
15052 if (!FD->hasAttr<FormatAttr>())
15053 FD->addAttr(FormatAttr::CreateImplicit(Context,
15054 &Context.Idents.get("printf"), 2,
15055 Name->isStr("vasprintf") ? 0 : 3,
15056 FD->getLocation()));
15057 }
15058
15059 if (Name->isStr("__CFStringMakeConstantString")) {
15060 // We already have a __builtin___CFStringMakeConstantString,
15061 // but builds that use -fno-constant-cfstrings don't go through that.
15062 if (!FD->hasAttr<FormatArgAttr>())
15063 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
15064 FD->getLocation()));
15065 }
15066}
15067
15068TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
15069 TypeSourceInfo *TInfo) {
15070 assert(D.getIdentifier() && "Wrong callback for declspec without declarator")((D.getIdentifier() && "Wrong callback for declspec without declarator"
) ? static_cast<void> (0) : __assert_fail ("D.getIdentifier() && \"Wrong callback for declspec without declarator\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 15070, __PRETTY_FUNCTION__))
;
15071 assert(!T.isNull() && "GetTypeForDeclarator() returned null type")((!T.isNull() && "GetTypeForDeclarator() returned null type"
) ? static_cast<void> (0) : __assert_fail ("!T.isNull() && \"GetTypeForDeclarator() returned null type\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 15071, __PRETTY_FUNCTION__))
;
15072
15073 if (!TInfo) {
15074 assert(D.isInvalidType() && "no declarator info for valid type")((D.isInvalidType() && "no declarator info for valid type"
) ? static_cast<void> (0) : __assert_fail ("D.isInvalidType() && \"no declarator info for valid type\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 15074, __PRETTY_FUNCTION__))
;
15075 TInfo = Context.getTrivialTypeSourceInfo(T);
15076 }
15077
15078 // Scope manipulation handled by caller.
15079 TypedefDecl *NewTD =
15080 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
15081 D.getIdentifierLoc(), D.getIdentifier(), TInfo);
15082
15083 // Bail out immediately if we have an invalid declaration.
15084 if (D.isInvalidType()) {
15085 NewTD->setInvalidDecl();
15086 return NewTD;
15087 }
15088
15089 if (D.getDeclSpec().isModulePrivateSpecified()) {
15090 if (CurContext->isFunctionOrMethod())
15091 Diag(NewTD->getLocation(), diag::err_module_private_local)
15092 << 2 << NewTD
15093 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15094 << FixItHint::CreateRemoval(
15095 D.getDeclSpec().getModulePrivateSpecLoc());
15096 else
15097 NewTD->setModulePrivate();
15098 }
15099
15100 // C++ [dcl.typedef]p8:
15101 // If the typedef declaration defines an unnamed class (or
15102 // enum), the first typedef-name declared by the declaration
15103 // to be that class type (or enum type) is used to denote the
15104 // class type (or enum type) for linkage purposes only.
15105 // We need to check whether the type was declared in the declaration.
15106 switch (D.getDeclSpec().getTypeSpecType()) {
15107 case TST_enum:
15108 case TST_struct:
15109 case TST_interface:
15110 case TST_union:
15111 case TST_class: {
15112 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
15113 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
15114 break;
15115 }
15116
15117 default:
15118 break;
15119 }
15120
15121 return NewTD;
15122}
15123
15124/// Check that this is a valid underlying type for an enum declaration.
15125bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
15126 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
15127 QualType T = TI->getType();
15128
15129 if (T->isDependentType())
15130 return false;
15131
15132 // This doesn't use 'isIntegralType' despite the error message mentioning
15133 // integral type because isIntegralType would also allow enum types in C.
15134 if (const BuiltinType *BT = T->getAs<BuiltinType>())
15135 if (BT->isInteger())
15136 return false;
15137
15138 if (T->isExtIntType())
15139 return false;
15140
15141 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
15142}
15143
15144/// Check whether this is a valid redeclaration of a previous enumeration.
15145/// \return true if the redeclaration was invalid.
15146bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
15147 QualType EnumUnderlyingTy, bool IsFixed,
15148 const EnumDecl *Prev) {
15149 if (IsScoped != Prev->isScoped()) {
15150 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
15151 << Prev->isScoped();
15152 Diag(Prev->getLocation(), diag::note_previous_declaration);
15153 return true;
15154 }
15155
15156 if (IsFixed && Prev->isFixed()) {
15157 if (!EnumUnderlyingTy->isDependentType() &&
15158 !Prev->getIntegerType()->isDependentType() &&
15159 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
15160 Prev->getIntegerType())) {
15161 // TODO: Highlight the underlying type of the redeclaration.
15162 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
15163 << EnumUnderlyingTy << Prev->getIntegerType();
15164 Diag(Prev->getLocation(), diag::note_previous_declaration)
15165 << Prev->getIntegerTypeRange();
15166 return true;
15167 }
15168 } else if (IsFixed != Prev->isFixed()) {
15169 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
15170 << Prev->isFixed();
15171 Diag(Prev->getLocation(), diag::note_previous_declaration);
15172 return true;
15173 }
15174
15175 return false;
15176}
15177
15178/// Get diagnostic %select index for tag kind for
15179/// redeclaration diagnostic message.
15180/// WARNING: Indexes apply to particular diagnostics only!
15181///
15182/// \returns diagnostic %select index.
15183static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
15184 switch (Tag) {
15185 case TTK_Struct: return 0;
15186 case TTK_Interface: return 1;
15187 case TTK_Class: return 2;
15188 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!")::llvm::llvm_unreachable_internal("Invalid tag kind for redecl diagnostic!"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 15188)
;
15189 }
15190}
15191
15192/// Determine if tag kind is a class-key compatible with
15193/// class for redeclaration (class, struct, or __interface).
15194///
15195/// \returns true iff the tag kind is compatible.
15196static bool isClassCompatTagKind(TagTypeKind Tag)
15197{
15198 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
15199}
15200
15201Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
15202 TagTypeKind TTK) {
15203 if (isa<TypedefDecl>(PrevDecl))
15204 return NTK_Typedef;
15205 else if (isa<TypeAliasDecl>(PrevDecl))
15206 return NTK_TypeAlias;
15207 else if (isa<ClassTemplateDecl>(PrevDecl))
15208 return NTK_Template;
15209 else if (isa<TypeAliasTemplateDecl>(PrevDecl))
15210 return NTK_TypeAliasTemplate;
15211 else if (isa<TemplateTemplateParmDecl>(PrevDecl))
15212 return NTK_TemplateTemplateArgument;
15213 switch (TTK) {
15214 case TTK_Struct:
15215 case TTK_Interface:
15216 case TTK_Class:
15217 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
15218 case TTK_Union:
15219 return NTK_NonUnion;
15220 case TTK_Enum:
15221 return NTK_NonEnum;
15222 }
15223 llvm_unreachable("invalid TTK")::llvm::llvm_unreachable_internal("invalid TTK", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 15223)
;
15224}
15225
15226/// Determine whether a tag with a given kind is acceptable
15227/// as a redeclaration of the given tag declaration.
15228///
15229/// \returns true if the new tag kind is acceptable, false otherwise.
15230bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
15231 TagTypeKind NewTag, bool isDefinition,
15232 SourceLocation NewTagLoc,
15233 const IdentifierInfo *Name) {
15234 // C++ [dcl.type.elab]p3:
15235 // The class-key or enum keyword present in the
15236 // elaborated-type-specifier shall agree in kind with the
15237 // declaration to which the name in the elaborated-type-specifier
15238 // refers. This rule also applies to the form of
15239 // elaborated-type-specifier that declares a class-name or
15240 // friend class since it can be construed as referring to the
15241 // definition of the class. Thus, in any
15242 // elaborated-type-specifier, the enum keyword shall be used to
15243 // refer to an enumeration (7.2), the union class-key shall be
15244 // used to refer to a union (clause 9), and either the class or
15245 // struct class-key shall be used to refer to a class (clause 9)
15246 // declared using the class or struct class-key.
15247 TagTypeKind OldTag = Previous->getTagKind();
15248 if (OldTag != NewTag &&
15249 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
15250 return false;
15251
15252 // Tags are compatible, but we might still want to warn on mismatched tags.
15253 // Non-class tags can't be mismatched at this point.
15254 if (!isClassCompatTagKind(NewTag))
15255 return true;
15256
15257 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
15258 // by our warning analysis. We don't want to warn about mismatches with (eg)
15259 // declarations in system headers that are designed to be specialized, but if
15260 // a user asks us to warn, we should warn if their code contains mismatched
15261 // declarations.
15262 auto IsIgnoredLoc = [&](SourceLocation Loc) {
15263 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
15264 Loc);
15265 };
15266 if (IsIgnoredLoc(NewTagLoc))
15267 return true;
15268
15269 auto IsIgnored = [&](const TagDecl *Tag) {
15270 return IsIgnoredLoc(Tag->getLocation());
15271 };
15272 while (IsIgnored(Previous)) {
15273 Previous = Previous->getPreviousDecl();
15274 if (!Previous)
15275 return true;
15276 OldTag = Previous->getTagKind();
15277 }
15278
15279 bool isTemplate = false;
15280 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
15281 isTemplate = Record->getDescribedClassTemplate();
15282
15283 if (inTemplateInstantiation()) {
15284 if (OldTag != NewTag) {
15285 // In a template instantiation, do not offer fix-its for tag mismatches
15286 // since they usually mess up the template instead of fixing the problem.
15287 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15288 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15289 << getRedeclDiagFromTagKind(OldTag);
15290 // FIXME: Note previous location?
15291 }
15292 return true;
15293 }
15294
15295 if (isDefinition) {
15296 // On definitions, check all previous tags and issue a fix-it for each
15297 // one that doesn't match the current tag.
15298 if (Previous->getDefinition()) {
15299 // Don't suggest fix-its for redefinitions.
15300 return true;
15301 }
15302
15303 bool previousMismatch = false;
15304 for (const TagDecl *I : Previous->redecls()) {
15305 if (I->getTagKind() != NewTag) {
15306 // Ignore previous declarations for which the warning was disabled.
15307 if (IsIgnored(I))
15308 continue;
15309
15310 if (!previousMismatch) {
15311 previousMismatch = true;
15312 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
15313 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15314 << getRedeclDiagFromTagKind(I->getTagKind());
15315 }
15316 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
15317 << getRedeclDiagFromTagKind(NewTag)
15318 << FixItHint::CreateReplacement(I->getInnerLocStart(),
15319 TypeWithKeyword::getTagTypeKindName(NewTag));
15320 }
15321 }
15322 return true;
15323 }
15324
15325 // Identify the prevailing tag kind: this is the kind of the definition (if
15326 // there is a non-ignored definition), or otherwise the kind of the prior
15327 // (non-ignored) declaration.
15328 const TagDecl *PrevDef = Previous->getDefinition();
15329 if (PrevDef && IsIgnored(PrevDef))
15330 PrevDef = nullptr;
15331 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
15332 if (Redecl->getTagKind() != NewTag) {
15333 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15334 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15335 << getRedeclDiagFromTagKind(OldTag);
15336 Diag(Redecl->getLocation(), diag::note_previous_use);
15337
15338 // If there is a previous definition, suggest a fix-it.
15339 if (PrevDef) {
15340 Diag(NewTagLoc, diag::note_struct_class_suggestion)
15341 << getRedeclDiagFromTagKind(Redecl->getTagKind())
15342 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
15343 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
15344 }
15345 }
15346
15347 return true;
15348}
15349
15350/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
15351/// from an outer enclosing namespace or file scope inside a friend declaration.
15352/// This should provide the commented out code in the following snippet:
15353/// namespace N {
15354/// struct X;
15355/// namespace M {
15356/// struct Y { friend struct /*N::*/ X; };
15357/// }
15358/// }
15359static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
15360 SourceLocation NameLoc) {
15361 // While the decl is in a namespace, do repeated lookup of that name and see
15362 // if we get the same namespace back. If we do not, continue until
15363 // translation unit scope, at which point we have a fully qualified NNS.
15364 SmallVector<IdentifierInfo *, 4> Namespaces;
15365 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15366 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
15367 // This tag should be declared in a namespace, which can only be enclosed by
15368 // other namespaces. Bail if there's an anonymous namespace in the chain.
15369 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
15370 if (!Namespace || Namespace->isAnonymousNamespace())
15371 return FixItHint();
15372 IdentifierInfo *II = Namespace->getIdentifier();
15373 Namespaces.push_back(II);
15374 NamedDecl *Lookup = SemaRef.LookupSingleName(
15375 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
15376 if (Lookup == Namespace)
15377 break;
15378 }
15379
15380 // Once we have all the namespaces, reverse them to go outermost first, and
15381 // build an NNS.
15382 SmallString<64> Insertion;
15383 llvm::raw_svector_ostream OS(Insertion);
15384 if (DC->isTranslationUnit())
15385 OS << "::";
15386 std::reverse(Namespaces.begin(), Namespaces.end());
15387 for (auto *II : Namespaces)
15388 OS << II->getName() << "::";
15389 return FixItHint::CreateInsertion(NameLoc, Insertion);
15390}
15391
15392/// Determine whether a tag originally declared in context \p OldDC can
15393/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
15394/// found a declaration in \p OldDC as a previous decl, perhaps through a
15395/// using-declaration).
15396static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
15397 DeclContext *NewDC) {
15398 OldDC = OldDC->getRedeclContext();
15399 NewDC = NewDC->getRedeclContext();
15400
15401 if (OldDC->Equals(NewDC))
15402 return true;
15403
15404 // In MSVC mode, we allow a redeclaration if the contexts are related (either
15405 // encloses the other).
15406 if (S.getLangOpts().MSVCCompat &&
15407 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
15408 return true;
15409
15410 return false;
15411}
15412
15413/// This is invoked when we see 'struct foo' or 'struct {'. In the
15414/// former case, Name will be non-null. In the later case, Name will be null.
15415/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
15416/// reference/declaration/definition of a tag.
15417///
15418/// \param IsTypeSpecifier \c true if this is a type-specifier (or
15419/// trailing-type-specifier) other than one in an alias-declaration.
15420///
15421/// \param SkipBody If non-null, will be set to indicate if the caller should
15422/// skip the definition of this tag and treat it as if it were a declaration.
15423Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
15424 SourceLocation KWLoc, CXXScopeSpec &SS,
15425 IdentifierInfo *Name, SourceLocation NameLoc,
15426 const ParsedAttributesView &Attrs, AccessSpecifier AS,
15427 SourceLocation ModulePrivateLoc,
15428 MultiTemplateParamsArg TemplateParameterLists,
15429 bool &OwnedDecl, bool &IsDependent,
15430 SourceLocation ScopedEnumKWLoc,
15431 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
15432 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
15433 SkipBodyInfo *SkipBody) {
15434 // If this is not a definition, it must have a name.
15435 IdentifierInfo *OrigName = Name;
15436 assert((Name != nullptr || TUK == TUK_Definition) &&(((Name != nullptr || TUK == TUK_Definition) && "Nameless record must be a definition!"
) ? static_cast<void> (0) : __assert_fail ("(Name != nullptr || TUK == TUK_Definition) && \"Nameless record must be a definition!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 15437, __PRETTY_FUNCTION__))
15437 "Nameless record must be a definition!")(((Name != nullptr || TUK == TUK_Definition) && "Nameless record must be a definition!"
) ? static_cast<void> (0) : __assert_fail ("(Name != nullptr || TUK == TUK_Definition) && \"Nameless record must be a definition!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 15437, __PRETTY_FUNCTION__))
;
15438 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference)((TemplateParameterLists.size() == 0 || TUK != TUK_Reference)
? static_cast<void> (0) : __assert_fail ("TemplateParameterLists.size() == 0 || TUK != TUK_Reference"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 15438, __PRETTY_FUNCTION__))
;
15439
15440 OwnedDecl = false;
15441 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
15442 bool ScopedEnum = ScopedEnumKWLoc.isValid();
15443
15444 // FIXME: Check member specializations more carefully.
15445 bool isMemberSpecialization = false;
15446 bool Invalid = false;
15447
15448 // We only need to do this matching if we have template parameters
15449 // or a scope specifier, which also conveniently avoids this work
15450 // for non-C++ cases.
15451 if (TemplateParameterLists.size() > 0 ||
15452 (SS.isNotEmpty() && TUK != TUK_Reference)) {
15453 if (TemplateParameterList *TemplateParams =
15454 MatchTemplateParametersToScopeSpecifier(
15455 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
15456 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
15457 if (Kind == TTK_Enum) {
15458 Diag(KWLoc, diag::err_enum_template);
15459 return nullptr;
15460 }
15461
15462 if (TemplateParams->size() > 0) {
15463 // This is a declaration or definition of a class template (which may
15464 // be a member of another template).
15465
15466 if (Invalid)
15467 return nullptr;
15468
15469 OwnedDecl = false;
15470 DeclResult Result = CheckClassTemplate(
15471 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
15472 AS, ModulePrivateLoc,
15473 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
15474 TemplateParameterLists.data(), SkipBody);
15475 return Result.get();
15476 } else {
15477 // The "template<>" header is extraneous.
15478 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
15479 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
15480 isMemberSpecialization = true;
15481 }
15482 }
15483
15484 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
15485 CheckTemplateDeclScope(S, TemplateParameterLists.back()))
15486 return nullptr;
15487 }
15488
15489 // Figure out the underlying type if this a enum declaration. We need to do
15490 // this early, because it's needed to detect if this is an incompatible
15491 // redeclaration.
15492 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
15493 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
15494
15495 if (Kind == TTK_Enum) {
15496 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
15497 // No underlying type explicitly specified, or we failed to parse the
15498 // type, default to int.
15499 EnumUnderlying = Context.IntTy.getTypePtr();
15500 } else if (UnderlyingType.get()) {
15501 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
15502 // integral type; any cv-qualification is ignored.
15503 TypeSourceInfo *TI = nullptr;
15504 GetTypeFromParser(UnderlyingType.get(), &TI);
15505 EnumUnderlying = TI;
15506
15507 if (CheckEnumUnderlyingType(TI))
15508 // Recover by falling back to int.
15509 EnumUnderlying = Context.IntTy.getTypePtr();
15510
15511 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
15512 UPPC_FixedUnderlyingType))
15513 EnumUnderlying = Context.IntTy.getTypePtr();
15514
15515 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
15516 // For MSVC ABI compatibility, unfixed enums must use an underlying type
15517 // of 'int'. However, if this is an unfixed forward declaration, don't set
15518 // the underlying type unless the user enables -fms-compatibility. This
15519 // makes unfixed forward declared enums incomplete and is more conforming.
15520 if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
15521 EnumUnderlying = Context.IntTy.getTypePtr();
15522 }
15523 }
15524
15525 DeclContext *SearchDC = CurContext;
15526 DeclContext *DC = CurContext;
15527 bool isStdBadAlloc = false;
15528 bool isStdAlignValT = false;
15529
15530 RedeclarationKind Redecl = forRedeclarationInCurContext();
15531 if (TUK == TUK_Friend || TUK == TUK_Reference)
15532 Redecl = NotForRedeclaration;
15533
15534 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
15535 /// implemented asks for structural equivalence checking, the returned decl
15536 /// here is passed back to the parser, allowing the tag body to be parsed.
15537 auto createTagFromNewDecl = [&]() -> TagDecl * {
15538 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage")((!getLangOpts().CPlusPlus && "not meant for C++ usage"
) ? static_cast<void> (0) : __assert_fail ("!getLangOpts().CPlusPlus && \"not meant for C++ usage\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 15538, __PRETTY_FUNCTION__))
;
15539 // If there is an identifier, use the location of the identifier as the
15540 // location of the decl, otherwise use the location of the struct/union
15541 // keyword.
15542 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15543 TagDecl *New = nullptr;
15544
15545 if (Kind == TTK_Enum) {
15546 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
15547 ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
15548 // If this is an undefined enum, bail.
15549 if (TUK != TUK_Definition && !Invalid)
15550 return nullptr;
15551 if (EnumUnderlying) {
15552 EnumDecl *ED = cast<EnumDecl>(New);
15553 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
15554 ED->setIntegerTypeSourceInfo(TI);
15555 else
15556 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
15557 ED->setPromotionType(ED->getIntegerType());
15558 }
15559 } else { // struct/union
15560 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15561 nullptr);
15562 }
15563
15564 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15565 // Add alignment attributes if necessary; these attributes are checked
15566 // when the ASTContext lays out the structure.
15567 //
15568 // It is important for implementing the correct semantics that this
15569 // happen here (in ActOnTag). The #pragma pack stack is
15570 // maintained as a result of parser callbacks which can occur at
15571 // many points during the parsing of a struct declaration (because
15572 // the #pragma tokens are effectively skipped over during the
15573 // parsing of the struct).
15574 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15575 AddAlignmentAttributesForRecord(RD);
15576 AddMsStructLayoutForRecord(RD);
15577 }
15578 }
15579 New->setLexicalDeclContext(CurContext);
15580 return New;
15581 };
15582
15583 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
15584 if (Name && SS.isNotEmpty()) {
15585 // We have a nested-name tag ('struct foo::bar').
15586
15587 // Check for invalid 'foo::'.
15588 if (SS.isInvalid()) {
15589 Name = nullptr;
15590 goto CreateNewDecl;
15591 }
15592
15593 // If this is a friend or a reference to a class in a dependent
15594 // context, don't try to make a decl for it.
15595 if (TUK == TUK_Friend || TUK == TUK_Reference) {
15596 DC = computeDeclContext(SS, false);
15597 if (!DC) {
15598 IsDependent = true;
15599 return nullptr;
15600 }
15601 } else {
15602 DC = computeDeclContext(SS, true);
15603 if (!DC) {
15604 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
15605 << SS.getRange();
15606 return nullptr;
15607 }
15608 }
15609
15610 if (RequireCompleteDeclContext(SS, DC))
15611 return nullptr;
15612
15613 SearchDC = DC;
15614 // Look-up name inside 'foo::'.
15615 LookupQualifiedName(Previous, DC);
15616
15617 if (Previous.isAmbiguous())
15618 return nullptr;
15619
15620 if (Previous.empty()) {
15621 // Name lookup did not find anything. However, if the
15622 // nested-name-specifier refers to the current instantiation,
15623 // and that current instantiation has any dependent base
15624 // classes, we might find something at instantiation time: treat
15625 // this as a dependent elaborated-type-specifier.
15626 // But this only makes any sense for reference-like lookups.
15627 if (Previous.wasNotFoundInCurrentInstantiation() &&
15628 (TUK == TUK_Reference || TUK == TUK_Friend)) {
15629 IsDependent = true;
15630 return nullptr;
15631 }
15632
15633 // A tag 'foo::bar' must already exist.
15634 Diag(NameLoc, diag::err_not_tag_in_scope)
15635 << Kind << Name << DC << SS.getRange();
15636 Name = nullptr;
15637 Invalid = true;
15638 goto CreateNewDecl;
15639 }
15640 } else if (Name) {
15641 // C++14 [class.mem]p14:
15642 // If T is the name of a class, then each of the following shall have a
15643 // name different from T:
15644 // -- every member of class T that is itself a type
15645 if (TUK != TUK_Reference && TUK != TUK_Friend &&
15646 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
15647 return nullptr;
15648
15649 // If this is a named struct, check to see if there was a previous forward
15650 // declaration or definition.
15651 // FIXME: We're looking into outer scopes here, even when we
15652 // shouldn't be. Doing so can result in ambiguities that we
15653 // shouldn't be diagnosing.
15654 LookupName(Previous, S);
15655
15656 // When declaring or defining a tag, ignore ambiguities introduced
15657 // by types using'ed into this scope.
15658 if (Previous.isAmbiguous() &&
15659 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
15660 LookupResult::Filter F = Previous.makeFilter();
15661 while (F.hasNext()) {
15662 NamedDecl *ND = F.next();
15663 if (!ND->getDeclContext()->getRedeclContext()->Equals(
15664 SearchDC->getRedeclContext()))
15665 F.erase();
15666 }
15667 F.done();
15668 }
15669
15670 // C++11 [namespace.memdef]p3:
15671 // If the name in a friend declaration is neither qualified nor
15672 // a template-id and the declaration is a function or an
15673 // elaborated-type-specifier, the lookup to determine whether
15674 // the entity has been previously declared shall not consider
15675 // any scopes outside the innermost enclosing namespace.
15676 //
15677 // MSVC doesn't implement the above rule for types, so a friend tag
15678 // declaration may be a redeclaration of a type declared in an enclosing
15679 // scope. They do implement this rule for friend functions.
15680 //
15681 // Does it matter that this should be by scope instead of by
15682 // semantic context?
15683 if (!Previous.empty() && TUK == TUK_Friend) {
15684 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
15685 LookupResult::Filter F = Previous.makeFilter();
15686 bool FriendSawTagOutsideEnclosingNamespace = false;
15687 while (F.hasNext()) {
15688 NamedDecl *ND = F.next();
15689 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15690 if (DC->isFileContext() &&
15691 !EnclosingNS->Encloses(ND->getDeclContext())) {
15692 if (getLangOpts().MSVCCompat)
15693 FriendSawTagOutsideEnclosingNamespace = true;
15694 else
15695 F.erase();
15696 }
15697 }
15698 F.done();
15699
15700 // Diagnose this MSVC extension in the easy case where lookup would have
15701 // unambiguously found something outside the enclosing namespace.
15702 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
15703 NamedDecl *ND = Previous.getFoundDecl();
15704 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
15705 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
15706 }
15707 }
15708
15709 // Note: there used to be some attempt at recovery here.
15710 if (Previous.isAmbiguous())
15711 return nullptr;
15712
15713 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
15714 // FIXME: This makes sure that we ignore the contexts associated
15715 // with C structs, unions, and enums when looking for a matching
15716 // tag declaration or definition. See the similar lookup tweak
15717 // in Sema::LookupName; is there a better way to deal with this?
15718 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
15719 SearchDC = SearchDC->getParent();
15720 }
15721 }
15722
15723 if (Previous.isSingleResult() &&
15724 Previous.getFoundDecl()->isTemplateParameter()) {
15725 // Maybe we will complain about the shadowed template parameter.
15726 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
15727 // Just pretend that we didn't see the previous declaration.
15728 Previous.clear();
15729 }
15730
15731 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
15732 DC->Equals(getStdNamespace())) {
15733 if (Name->isStr("bad_alloc")) {
15734 // This is a declaration of or a reference to "std::bad_alloc".
15735 isStdBadAlloc = true;
15736
15737 // If std::bad_alloc has been implicitly declared (but made invisible to
15738 // name lookup), fill in this implicit declaration as the previous
15739 // declaration, so that the declarations get chained appropriately.
15740 if (Previous.empty() && StdBadAlloc)
15741 Previous.addDecl(getStdBadAlloc());
15742 } else if (Name->isStr("align_val_t")) {
15743 isStdAlignValT = true;
15744 if (Previous.empty() && StdAlignValT)
15745 Previous.addDecl(getStdAlignValT());
15746 }
15747 }
15748
15749 // If we didn't find a previous declaration, and this is a reference
15750 // (or friend reference), move to the correct scope. In C++, we
15751 // also need to do a redeclaration lookup there, just in case
15752 // there's a shadow friend decl.
15753 if (Name && Previous.empty() &&
15754 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
15755 if (Invalid) goto CreateNewDecl;
15756 assert(SS.isEmpty())((SS.isEmpty()) ? static_cast<void> (0) : __assert_fail
("SS.isEmpty()", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 15756, __PRETTY_FUNCTION__))
;
15757
15758 if (TUK == TUK_Reference || IsTemplateParamOrArg) {
15759 // C++ [basic.scope.pdecl]p5:
15760 // -- for an elaborated-type-specifier of the form
15761 //
15762 // class-key identifier
15763 //
15764 // if the elaborated-type-specifier is used in the
15765 // decl-specifier-seq or parameter-declaration-clause of a
15766 // function defined in namespace scope, the identifier is
15767 // declared as a class-name in the namespace that contains
15768 // the declaration; otherwise, except as a friend
15769 // declaration, the identifier is declared in the smallest
15770 // non-class, non-function-prototype scope that contains the
15771 // declaration.
15772 //
15773 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
15774 // C structs and unions.
15775 //
15776 // It is an error in C++ to declare (rather than define) an enum
15777 // type, including via an elaborated type specifier. We'll
15778 // diagnose that later; for now, declare the enum in the same
15779 // scope as we would have picked for any other tag type.
15780 //
15781 // GNU C also supports this behavior as part of its incomplete
15782 // enum types extension, while GNU C++ does not.
15783 //
15784 // Find the context where we'll be declaring the tag.
15785 // FIXME: We would like to maintain the current DeclContext as the
15786 // lexical context,
15787 SearchDC = getTagInjectionContext(SearchDC);
15788
15789 // Find the scope where we'll be declaring the tag.
15790 S = getTagInjectionScope(S, getLangOpts());
15791 } else {
15792 assert(TUK == TUK_Friend)((TUK == TUK_Friend) ? static_cast<void> (0) : __assert_fail
("TUK == TUK_Friend", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 15792, __PRETTY_FUNCTION__))
;
15793 // C++ [namespace.memdef]p3:
15794 // If a friend declaration in a non-local class first declares a
15795 // class or function, the friend class or function is a member of
15796 // the innermost enclosing namespace.
15797 SearchDC = SearchDC->getEnclosingNamespaceContext();
15798 }
15799
15800 // In C++, we need to do a redeclaration lookup to properly
15801 // diagnose some problems.
15802 // FIXME: redeclaration lookup is also used (with and without C++) to find a
15803 // hidden declaration so that we don't get ambiguity errors when using a
15804 // type declared by an elaborated-type-specifier. In C that is not correct
15805 // and we should instead merge compatible types found by lookup.
15806 if (getLangOpts().CPlusPlus) {
15807 // FIXME: This can perform qualified lookups into function contexts,
15808 // which are meaningless.
15809 Previous.setRedeclarationKind(forRedeclarationInCurContext());
15810 LookupQualifiedName(Previous, SearchDC);
15811 } else {
15812 Previous.setRedeclarationKind(forRedeclarationInCurContext());
15813 LookupName(Previous, S);
15814 }
15815 }
15816
15817 // If we have a known previous declaration to use, then use it.
15818 if (Previous.empty() && SkipBody && SkipBody->Previous)
15819 Previous.addDecl(SkipBody->Previous);
15820
15821 if (!Previous.empty()) {
15822 NamedDecl *PrevDecl = Previous.getFoundDecl();
15823 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
15824
15825 // It's okay to have a tag decl in the same scope as a typedef
15826 // which hides a tag decl in the same scope. Finding this
15827 // insanity with a redeclaration lookup can only actually happen
15828 // in C++.
15829 //
15830 // This is also okay for elaborated-type-specifiers, which is
15831 // technically forbidden by the current standard but which is
15832 // okay according to the likely resolution of an open issue;
15833 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
15834 if (getLangOpts().CPlusPlus) {
15835 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15836 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
15837 TagDecl *Tag = TT->getDecl();
15838 if (Tag->getDeclName() == Name &&
15839 Tag->getDeclContext()->getRedeclContext()
15840 ->Equals(TD->getDeclContext()->getRedeclContext())) {
15841 PrevDecl = Tag;
15842 Previous.clear();
15843 Previous.addDecl(Tag);
15844 Previous.resolveKind();
15845 }
15846 }
15847 }
15848 }
15849
15850 // If this is a redeclaration of a using shadow declaration, it must
15851 // declare a tag in the same context. In MSVC mode, we allow a
15852 // redefinition if either context is within the other.
15853 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
15854 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
15855 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
15856 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
15857 !(OldTag && isAcceptableTagRedeclContext(
15858 *this, OldTag->getDeclContext(), SearchDC))) {
15859 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
15860 Diag(Shadow->getTargetDecl()->getLocation(),
15861 diag::note_using_decl_target);
15862 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
15863 << 0;
15864 // Recover by ignoring the old declaration.
15865 Previous.clear();
15866 goto CreateNewDecl;
15867 }
15868 }
15869
15870 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
15871 // If this is a use of a previous tag, or if the tag is already declared
15872 // in the same scope (so that the definition/declaration completes or
15873 // rementions the tag), reuse the decl.
15874 if (TUK == TUK_Reference || TUK == TUK_Friend ||
15875 isDeclInScope(DirectPrevDecl, SearchDC, S,
15876 SS.isNotEmpty() || isMemberSpecialization)) {
15877 // Make sure that this wasn't declared as an enum and now used as a
15878 // struct or something similar.
15879 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
15880 TUK == TUK_Definition, KWLoc,
15881 Name)) {
15882 bool SafeToContinue
15883 = (PrevTagDecl->getTagKind() != TTK_Enum &&
15884 Kind != TTK_Enum);
15885 if (SafeToContinue)
15886 Diag(KWLoc, diag::err_use_with_wrong_tag)
15887 << Name
15888 << FixItHint::CreateReplacement(SourceRange(KWLoc),
15889 PrevTagDecl->getKindName());
15890 else
15891 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
15892 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
15893
15894 if (SafeToContinue)
15895 Kind = PrevTagDecl->getTagKind();
15896 else {
15897 // Recover by making this an anonymous redefinition.
15898 Name = nullptr;
15899 Previous.clear();
15900 Invalid = true;
15901 }
15902 }
15903
15904 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
15905 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
15906 if (TUK == TUK_Reference || TUK == TUK_Friend)
15907 return PrevTagDecl;
15908
15909 QualType EnumUnderlyingTy;
15910 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15911 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
15912 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
15913 EnumUnderlyingTy = QualType(T, 0);
15914
15915 // All conflicts with previous declarations are recovered by
15916 // returning the previous declaration, unless this is a definition,
15917 // in which case we want the caller to bail out.
15918 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
15919 ScopedEnum, EnumUnderlyingTy,
15920 IsFixed, PrevEnum))
15921 return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
15922 }
15923
15924 // C++11 [class.mem]p1:
15925 // A member shall not be declared twice in the member-specification,
15926 // except that a nested class or member class template can be declared
15927 // and then later defined.
15928 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
15929 S->isDeclScope(PrevDecl)) {
15930 Diag(NameLoc, diag::ext_member_redeclared);
15931 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
15932 }
15933
15934 if (!Invalid) {
15935 // If this is a use, just return the declaration we found, unless
15936 // we have attributes.
15937 if (TUK == TUK_Reference || TUK == TUK_Friend) {
15938 if (!Attrs.empty()) {
15939 // FIXME: Diagnose these attributes. For now, we create a new
15940 // declaration to hold them.
15941 } else if (TUK == TUK_Reference &&
15942 (PrevTagDecl->getFriendObjectKind() ==
15943 Decl::FOK_Undeclared ||
15944 PrevDecl->getOwningModule() != getCurrentModule()) &&
15945 SS.isEmpty()) {
15946 // This declaration is a reference to an existing entity, but
15947 // has different visibility from that entity: it either makes
15948 // a friend visible or it makes a type visible in a new module.
15949 // In either case, create a new declaration. We only do this if
15950 // the declaration would have meant the same thing if no prior
15951 // declaration were found, that is, if it was found in the same
15952 // scope where we would have injected a declaration.
15953 if (!getTagInjectionContext(CurContext)->getRedeclContext()
15954 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
15955 return PrevTagDecl;
15956 // This is in the injected scope, create a new declaration in
15957 // that scope.
15958 S = getTagInjectionScope(S, getLangOpts());
15959 } else {
15960 return PrevTagDecl;
15961 }
15962 }
15963
15964 // Diagnose attempts to redefine a tag.
15965 if (TUK == TUK_Definition) {
15966 if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
15967 // If we're defining a specialization and the previous definition
15968 // is from an implicit instantiation, don't emit an error
15969 // here; we'll catch this in the general case below.
15970 bool IsExplicitSpecializationAfterInstantiation = false;
15971 if (isMemberSpecialization) {
15972 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
15973 IsExplicitSpecializationAfterInstantiation =
15974 RD->getTemplateSpecializationKind() !=
15975 TSK_ExplicitSpecialization;
15976 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
15977 IsExplicitSpecializationAfterInstantiation =
15978 ED->getTemplateSpecializationKind() !=
15979 TSK_ExplicitSpecialization;
15980 }
15981
15982 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
15983 // not keep more that one definition around (merge them). However,
15984 // ensure the decl passes the structural compatibility check in
15985 // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
15986 NamedDecl *Hidden = nullptr;
15987 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
15988 // There is a definition of this tag, but it is not visible. We
15989 // explicitly make use of C++'s one definition rule here, and
15990 // assume that this definition is identical to the hidden one
15991 // we already have. Make the existing definition visible and
15992 // use it in place of this one.
15993 if (!getLangOpts().CPlusPlus) {
15994 // Postpone making the old definition visible until after we
15995 // complete parsing the new one and do the structural
15996 // comparison.
15997 SkipBody->CheckSameAsPrevious = true;
15998 SkipBody->New = createTagFromNewDecl();
15999 SkipBody->Previous = Def;
16000 return Def;
16001 } else {
16002 SkipBody->ShouldSkip = true;
16003 SkipBody->Previous = Def;
16004 makeMergedDefinitionVisible(Hidden);
16005 // Carry on and handle it like a normal definition. We'll
16006 // skip starting the definitiion later.
16007 }
16008 } else if (!IsExplicitSpecializationAfterInstantiation) {
16009 // A redeclaration in function prototype scope in C isn't
16010 // visible elsewhere, so merely issue a warning.
16011 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
16012 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
16013 else
16014 Diag(NameLoc, diag::err_redefinition) << Name;
16015 notePreviousDefinition(Def,
16016 NameLoc.isValid() ? NameLoc : KWLoc);
16017 // If this is a redefinition, recover by making this
16018 // struct be anonymous, which will make any later
16019 // references get the previous definition.
16020 Name = nullptr;
16021 Previous.clear();
16022 Invalid = true;
16023 }
16024 } else {
16025 // If the type is currently being defined, complain
16026 // about a nested redefinition.
16027 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
16028 if (TD->isBeingDefined()) {
16029 Diag(NameLoc, diag::err_nested_redefinition) << Name;
16030 Diag(PrevTagDecl->getLocation(),
16031 diag::note_previous_definition);
16032 Name = nullptr;
16033 Previous.clear();
16034 Invalid = true;
16035 }
16036 }
16037
16038 // Okay, this is definition of a previously declared or referenced
16039 // tag. We're going to create a new Decl for it.
16040 }
16041
16042 // Okay, we're going to make a redeclaration. If this is some kind
16043 // of reference, make sure we build the redeclaration in the same DC
16044 // as the original, and ignore the current access specifier.
16045 if (TUK == TUK_Friend || TUK == TUK_Reference) {
16046 SearchDC = PrevTagDecl->getDeclContext();
16047 AS = AS_none;
16048 }
16049 }
16050 // If we get here we have (another) forward declaration or we
16051 // have a definition. Just create a new decl.
16052
16053 } else {
16054 // If we get here, this is a definition of a new tag type in a nested
16055 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
16056 // new decl/type. We set PrevDecl to NULL so that the entities
16057 // have distinct types.
16058 Previous.clear();
16059 }
16060 // If we get here, we're going to create a new Decl. If PrevDecl
16061 // is non-NULL, it's a definition of the tag declared by
16062 // PrevDecl. If it's NULL, we have a new definition.
16063
16064 // Otherwise, PrevDecl is not a tag, but was found with tag
16065 // lookup. This is only actually possible in C++, where a few
16066 // things like templates still live in the tag namespace.
16067 } else {
16068 // Use a better diagnostic if an elaborated-type-specifier
16069 // found the wrong kind of type on the first
16070 // (non-redeclaration) lookup.
16071 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
16072 !Previous.isForRedeclaration()) {
16073 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16074 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
16075 << Kind;
16076 Diag(PrevDecl->getLocation(), diag::note_declared_at);
16077 Invalid = true;
16078
16079 // Otherwise, only diagnose if the declaration is in scope.
16080 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
16081 SS.isNotEmpty() || isMemberSpecialization)) {
16082 // do nothing
16083
16084 // Diagnose implicit declarations introduced by elaborated types.
16085 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
16086 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16087 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
16088 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16089 Invalid = true;
16090
16091 // Otherwise it's a declaration. Call out a particularly common
16092 // case here.
16093 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16094 unsigned Kind = 0;
16095 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
16096 Diag(NameLoc, diag::err_tag_definition_of_typedef)
16097 << Name << Kind << TND->getUnderlyingType();
16098 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16099 Invalid = true;
16100
16101 // Otherwise, diagnose.
16102 } else {
16103 // The tag name clashes with something else in the target scope,
16104 // issue an error and recover by making this tag be anonymous.
16105 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
16106 notePreviousDefinition(PrevDecl, NameLoc);
16107 Name = nullptr;
16108 Invalid = true;
16109 }
16110
16111 // The existing declaration isn't relevant to us; we're in a
16112 // new scope, so clear out the previous declaration.
16113 Previous.clear();
16114 }
16115 }
16116
16117CreateNewDecl:
16118
16119 TagDecl *PrevDecl = nullptr;
16120 if (Previous.isSingleResult())
16121 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
16122
16123 // If there is an identifier, use the location of the identifier as the
16124 // location of the decl, otherwise use the location of the struct/union
16125 // keyword.
16126 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16127
16128 // Otherwise, create a new declaration. If there is a previous
16129 // declaration of the same entity, the two will be linked via
16130 // PrevDecl.
16131 TagDecl *New;
16132
16133 if (Kind == TTK_Enum) {
16134 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16135 // enum X { A, B, C } D; D should chain to X.
16136 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
16137 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
16138 ScopedEnumUsesClassTag, IsFixed);
16139
16140 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
16141 StdAlignValT = cast<EnumDecl>(New);
16142
16143 // If this is an undefined enum, warn.
16144 if (TUK != TUK_Definition && !Invalid) {
16145 TagDecl *Def;
16146 if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
16147 // C++0x: 7.2p2: opaque-enum-declaration.
16148 // Conflicts are diagnosed above. Do nothing.
16149 }
16150 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
16151 Diag(Loc, diag::ext_forward_ref_enum_def)
16152 << New;
16153 Diag(Def->getLocation(), diag::note_previous_definition);
16154 } else {
16155 unsigned DiagID = diag::ext_forward_ref_enum;
16156 if (getLangOpts().MSVCCompat)
16157 DiagID = diag::ext_ms_forward_ref_enum;
16158 else if (getLangOpts().CPlusPlus)
16159 DiagID = diag::err_forward_ref_enum;
16160 Diag(Loc, DiagID);
16161 }
16162 }
16163
16164 if (EnumUnderlying) {
16165 EnumDecl *ED = cast<EnumDecl>(New);
16166 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16167 ED->setIntegerTypeSourceInfo(TI);
16168 else
16169 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
16170 ED->setPromotionType(ED->getIntegerType());
16171 assert(ED->isComplete() && "enum with type should be complete")((ED->isComplete() && "enum with type should be complete"
) ? static_cast<void> (0) : __assert_fail ("ED->isComplete() && \"enum with type should be complete\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 16171, __PRETTY_FUNCTION__))
;
16172 }
16173 } else {
16174 // struct/union/class
16175
16176 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16177 // struct X { int A; } D; D should chain to X.
16178 if (getLangOpts().CPlusPlus) {
16179 // FIXME: Look for a way to use RecordDecl for simple structs.
16180 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16181 cast_or_null<CXXRecordDecl>(PrevDecl));
16182
16183 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
16184 StdBadAlloc = cast<CXXRecordDecl>(New);
16185 } else
16186 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16187 cast_or_null<RecordDecl>(PrevDecl));
16188 }
16189
16190 // C++11 [dcl.type]p3:
16191 // A type-specifier-seq shall not define a class or enumeration [...].
16192 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
16193 TUK == TUK_Definition) {
16194 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
16195 << Context.getTagDeclType(New);
16196 Invalid = true;
16197 }
16198
16199 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
16200 DC->getDeclKind() == Decl::Enum) {
16201 Diag(New->getLocation(), diag::err_type_defined_in_enum)
16202 << Context.getTagDeclType(New);
16203 Invalid = true;
16204 }
16205
16206 // Maybe add qualifier info.
16207 if (SS.isNotEmpty()) {
16208 if (SS.isSet()) {
16209 // If this is either a declaration or a definition, check the
16210 // nested-name-specifier against the current context.
16211 if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
16212 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
16213 isMemberSpecialization))
16214 Invalid = true;
16215
16216 New->setQualifierInfo(SS.getWithLocInContext(Context));
16217 if (TemplateParameterLists.size() > 0) {
16218 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
16219 }
16220 }
16221 else
16222 Invalid = true;
16223 }
16224
16225 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16226 // Add alignment attributes if necessary; these attributes are checked when
16227 // the ASTContext lays out the structure.
16228 //
16229 // It is important for implementing the correct semantics that this
16230 // happen here (in ActOnTag). The #pragma pack stack is
16231 // maintained as a result of parser callbacks which can occur at
16232 // many points during the parsing of a struct declaration (because
16233 // the #pragma tokens are effectively skipped over during the
16234 // parsing of the struct).
16235 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16236 AddAlignmentAttributesForRecord(RD);
16237 AddMsStructLayoutForRecord(RD);
16238 }
16239 }
16240
16241 if (ModulePrivateLoc.isValid()) {
16242 if (isMemberSpecialization)
16243 Diag(New->getLocation(), diag::err_module_private_specialization)
16244 << 2
16245 << FixItHint::CreateRemoval(ModulePrivateLoc);
16246 // __module_private__ does not apply to local classes. However, we only
16247 // diagnose this as an error when the declaration specifiers are
16248 // freestanding. Here, we just ignore the __module_private__.
16249 else if (!SearchDC->isFunctionOrMethod())
16250 New->setModulePrivate();
16251 }
16252
16253 // If this is a specialization of a member class (of a class template),
16254 // check the specialization.
16255 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
16256 Invalid = true;
16257
16258 // If we're declaring or defining a tag in function prototype scope in C,
16259 // note that this type can only be used within the function and add it to
16260 // the list of decls to inject into the function definition scope.
16261 if ((Name || Kind == TTK_Enum) &&
16262 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
16263 if (getLangOpts().CPlusPlus) {
16264 // C++ [dcl.fct]p6:
16265 // Types shall not be defined in return or parameter types.
16266 if (TUK == TUK_Definition && !IsTypeSpecifier) {
16267 Diag(Loc, diag::err_type_defined_in_param_type)
16268 << Name;
16269 Invalid = true;
16270 }
16271 } else if (!PrevDecl) {
16272 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
16273 }
16274 }
16275
16276 if (Invalid)
16277 New->setInvalidDecl();
16278
16279 // Set the lexical context. If the tag has a C++ scope specifier, the
16280 // lexical context will be different from the semantic context.
16281 New->setLexicalDeclContext(CurContext);
16282
16283 // Mark this as a friend decl if applicable.
16284 // In Microsoft mode, a friend declaration also acts as a forward
16285 // declaration so we always pass true to setObjectOfFriendDecl to make
16286 // the tag name visible.
16287 if (TUK == TUK_Friend)
16288 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
16289
16290 // Set the access specifier.
16291 if (!Invalid && SearchDC->isRecord())
16292 SetMemberAccessSpecifier(New, PrevDecl, AS);
16293
16294 if (PrevDecl)
16295 CheckRedeclarationModuleOwnership(New, PrevDecl);
16296
16297 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
16298 New->startDefinition();
16299
16300 ProcessDeclAttributeList(S, New, Attrs);
16301 AddPragmaAttributes(S, New);
16302
16303 // If this has an identifier, add it to the scope stack.
16304 if (TUK == TUK_Friend) {
16305 // We might be replacing an existing declaration in the lookup tables;
16306 // if so, borrow its access specifier.
16307 if (PrevDecl)
16308 New->setAccess(PrevDecl->getAccess());
16309
16310 DeclContext *DC = New->getDeclContext()->getRedeclContext();
16311 DC->makeDeclVisibleInContext(New);
16312 if (Name) // can be null along some error paths
16313 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16314 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
16315 } else if (Name) {
16316 S = getNonFieldDeclScope(S);
16317 PushOnScopeChains(New, S, true);
16318 } else {
16319 CurContext->addDecl(New);
16320 }
16321
16322 // If this is the C FILE type, notify the AST context.
16323 if (IdentifierInfo *II = New->getIdentifier())
16324 if (!New->isInvalidDecl() &&
16325 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
16326 II->isStr("FILE"))
16327 Context.setFILEDecl(New);
16328
16329 if (PrevDecl)
16330 mergeDeclAttributes(New, PrevDecl);
16331
16332 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
16333 inferGslOwnerPointerAttribute(CXXRD);
16334
16335 // If there's a #pragma GCC visibility in scope, set the visibility of this
16336 // record.
16337 AddPushedVisibilityAttribute(New);
16338
16339 if (isMemberSpecialization && !New->isInvalidDecl())
16340 CompleteMemberSpecialization(New, Previous);
16341
16342 OwnedDecl = true;
16343 // In C++, don't return an invalid declaration. We can't recover well from
16344 // the cases where we make the type anonymous.
16345 if (Invalid && getLangOpts().CPlusPlus) {
16346 if (New->isBeingDefined())
16347 if (auto RD = dyn_cast<RecordDecl>(New))
16348 RD->completeDefinition();
16349 return nullptr;
16350 } else if (SkipBody && SkipBody->ShouldSkip) {
16351 return SkipBody->Previous;
16352 } else {
16353 return New;
16354 }
16355}
16356
16357void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
16358 AdjustDeclIfTemplate(TagD);
16359 TagDecl *Tag = cast<TagDecl>(TagD);
16360
16361 // Enter the tag context.
16362 PushDeclContext(S, Tag);
16363
16364 ActOnDocumentableDecl(TagD);
16365
16366 // If there's a #pragma GCC visibility in scope, set the visibility of this
16367 // record.
16368 AddPushedVisibilityAttribute(Tag);
16369}
16370
16371bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
16372 SkipBodyInfo &SkipBody) {
16373 if (!hasStructuralCompatLayout(Prev, SkipBody.New))
16374 return false;
16375
16376 // Make the previous decl visible.
16377 makeMergedDefinitionVisible(SkipBody.Previous);
16378 return true;
16379}
16380
16381Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
16382 assert(isa<ObjCContainerDecl>(IDecl) &&((isa<ObjCContainerDecl>(IDecl) && "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"
) ? static_cast<void> (0) : __assert_fail ("isa<ObjCContainerDecl>(IDecl) && \"ActOnObjCContainerStartDefinition - Not ObjCContainerDecl\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 16383, __PRETTY_FUNCTION__))
16383 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl")((isa<ObjCContainerDecl>(IDecl) && "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"
) ? static_cast<void> (0) : __assert_fail ("isa<ObjCContainerDecl>(IDecl) && \"ActOnObjCContainerStartDefinition - Not ObjCContainerDecl\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 16383, __PRETTY_FUNCTION__))
;
16384 DeclContext *OCD = cast<DeclContext>(IDecl);
16385 assert(OCD->getLexicalParent() == CurContext &&((OCD->getLexicalParent() == CurContext && "The next DeclContext should be lexically contained in the current one."
) ? static_cast<void> (0) : __assert_fail ("OCD->getLexicalParent() == CurContext && \"The next DeclContext should be lexically contained in the current one.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 16386, __PRETTY_FUNCTION__))
16386 "The next DeclContext should be lexically contained in the current one.")((OCD->getLexicalParent() == CurContext && "The next DeclContext should be lexically contained in the current one."
) ? static_cast<void> (0) : __assert_fail ("OCD->getLexicalParent() == CurContext && \"The next DeclContext should be lexically contained in the current one.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 16386, __PRETTY_FUNCTION__))
;
16387 CurContext = OCD;
16388 return IDecl;
16389}
16390
16391void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
16392 SourceLocation FinalLoc,
16393 bool IsFinalSpelledSealed,
16394 SourceLocation LBraceLoc) {
16395 AdjustDeclIfTemplate(TagD);
16396 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
16397
16398 FieldCollector->StartClass();
16399
16400 if (!Record->getIdentifier())
16401 return;
16402
16403 if (FinalLoc.isValid())
16404 Record->addAttr(FinalAttr::Create(
16405 Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
16406 static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
16407
16408 // C++ [class]p2:
16409 // [...] The class-name is also inserted into the scope of the
16410 // class itself; this is known as the injected-class-name. For
16411 // purposes of access checking, the injected-class-name is treated
16412 // as if it were a public member name.
16413 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
16414 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
16415 Record->getLocation(), Record->getIdentifier(),
16416 /*PrevDecl=*/nullptr,
16417 /*DelayTypeCreation=*/true);
16418 Context.getTypeDeclType(InjectedClassName, Record);
16419 InjectedClassName->setImplicit();
16420 InjectedClassName->setAccess(AS_public);
16421 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
16422 InjectedClassName->setDescribedClassTemplate(Template);
16423 PushOnScopeChains(InjectedClassName, S);
16424 assert(InjectedClassName->isInjectedClassName() &&((InjectedClassName->isInjectedClassName() && "Broken injected-class-name"
) ? static_cast<void> (0) : __assert_fail ("InjectedClassName->isInjectedClassName() && \"Broken injected-class-name\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 16425, __PRETTY_FUNCTION__))
16425 "Broken injected-class-name")((InjectedClassName->isInjectedClassName() && "Broken injected-class-name"
) ? static_cast<void> (0) : __assert_fail ("InjectedClassName->isInjectedClassName() && \"Broken injected-class-name\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 16425, __PRETTY_FUNCTION__))
;
16426}
16427
16428void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
16429 SourceRange BraceRange) {
16430 AdjustDeclIfTemplate(TagD);
16431 TagDecl *Tag = cast<TagDecl>(TagD);
16432 Tag->setBraceRange(BraceRange);
16433
16434 // Make sure we "complete" the definition even it is invalid.
16435 if (Tag->isBeingDefined()) {
16436 assert(Tag->isInvalidDecl() && "We should already have completed it")((Tag->isInvalidDecl() && "We should already have completed it"
) ? static_cast<void> (0) : __assert_fail ("Tag->isInvalidDecl() && \"We should already have completed it\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 16436, __PRETTY_FUNCTION__))
;
16437 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16438 RD->completeDefinition();
16439 }
16440
16441 if (isa<CXXRecordDecl>(Tag)) {
16442 FieldCollector->FinishClass();
16443 }
16444
16445 // Exit this scope of this tag's definition.
16446 PopDeclContext();
16447
16448 if (getCurLexicalContext()->isObjCContainer() &&
16449 Tag->getDeclContext()->isFileContext())
16450 Tag->setTopLevelDeclInObjCContainer();
16451
16452 // Notify the consumer that we've defined a tag.
16453 if (!Tag->isInvalidDecl())
16454 Consumer.HandleTagDeclDefinition(Tag);
16455}
16456
16457void Sema::ActOnObjCContainerFinishDefinition() {
16458 // Exit this scope of this interface definition.
16459 PopDeclContext();
16460}
16461
16462void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
16463 assert(DC == CurContext && "Mismatch of container contexts")((DC == CurContext && "Mismatch of container contexts"
) ? static_cast<void> (0) : __assert_fail ("DC == CurContext && \"Mismatch of container contexts\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 16463, __PRETTY_FUNCTION__))
;
16464 OriginalLexicalContext = DC;
16465 ActOnObjCContainerFinishDefinition();
16466}
16467
16468void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
16469 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
16470 OriginalLexicalContext = nullptr;
16471}
16472
16473void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
16474 AdjustDeclIfTemplate(TagD);
16475 TagDecl *Tag = cast<TagDecl>(TagD);
16476 Tag->setInvalidDecl();
16477
16478 // Make sure we "complete" the definition even it is invalid.
16479 if (Tag->isBeingDefined()) {
16480 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16481 RD->completeDefinition();
16482 }
16483
16484 // We're undoing ActOnTagStartDefinition here, not
16485 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
16486 // the FieldCollector.
16487
16488 PopDeclContext();
16489}
16490
16491// Note that FieldName may be null for anonymous bitfields.
16492ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
16493 IdentifierInfo *FieldName,
16494 QualType FieldTy, bool IsMsStruct,
16495 Expr *BitWidth, bool *ZeroWidth) {
16496 assert(BitWidth)((BitWidth) ? static_cast<void> (0) : __assert_fail ("BitWidth"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 16496, __PRETTY_FUNCTION__))
;
16497 if (BitWidth->containsErrors())
16498 return ExprError();
16499
16500 // Default to true; that shouldn't confuse checks for emptiness
16501 if (ZeroWidth)
16502 *ZeroWidth = true;
16503
16504 // C99 6.7.2.1p4 - verify the field type.
16505 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
16506 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
16507 // Handle incomplete and sizeless types with a specific error.
16508 if (RequireCompleteSizedType(FieldLoc, FieldTy,
16509 diag::err_field_incomplete_or_sizeless))
16510 return ExprError();
16511 if (FieldName)
16512 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
16513 << FieldName << FieldTy << BitWidth->getSourceRange();
16514 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
16515 << FieldTy << BitWidth->getSourceRange();
16516 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
16517 UPPC_BitFieldWidth))
16518 return ExprError();
16519
16520 // If the bit-width is type- or value-dependent, don't try to check
16521 // it now.
16522 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
16523 return BitWidth;
16524
16525 llvm::APSInt Value;
16526 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
16527 if (ICE.isInvalid())
16528 return ICE;
16529 BitWidth = ICE.get();
16530
16531 if (Value != 0 && ZeroWidth)
16532 *ZeroWidth = false;
16533
16534 // Zero-width bitfield is ok for anonymous field.
16535 if (Value == 0 && FieldName)
16536 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
16537
16538 if (Value.isSigned() && Value.isNegative()) {
16539 if (FieldName)
16540 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
16541 << FieldName << Value.toString(10);
16542 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
16543 << Value.toString(10);
16544 }
16545
16546 // The size of the bit-field must not exceed our maximum permitted object
16547 // size.
16548 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
16549 return Diag(FieldLoc, diag::err_bitfield_too_wide)
16550 << !FieldName << FieldName << Value.toString(10);
16551 }
16552
16553 if (!FieldTy->isDependentType()) {
16554 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
16555 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
16556 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
16557
16558 // Over-wide bitfields are an error in C or when using the MSVC bitfield
16559 // ABI.
16560 bool CStdConstraintViolation =
16561 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
16562 bool MSBitfieldViolation =
16563 Value.ugt(TypeStorageSize) &&
16564 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
16565 if (CStdConstraintViolation || MSBitfieldViolation) {
16566 unsigned DiagWidth =
16567 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
16568 if (FieldName)
16569 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
16570 << FieldName << Value.toString(10)
16571 << !CStdConstraintViolation << DiagWidth;
16572
16573 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
16574 << Value.toString(10) << !CStdConstraintViolation
16575 << DiagWidth;
16576 }
16577
16578 // Warn on types where the user might conceivably expect to get all
16579 // specified bits as value bits: that's all integral types other than
16580 // 'bool'.
16581 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
16582 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
16583 << FieldName << Value.toString(10)
16584 << (unsigned)TypeWidth;
16585 }
16586 }
16587
16588 return BitWidth;
16589}
16590
16591/// ActOnField - Each field of a C struct/union is passed into this in order
16592/// to create a FieldDecl object for it.
16593Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
16594 Declarator &D, Expr *BitfieldWidth) {
16595 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
1
Assuming null pointer is passed into cast
2
Passing null pointer value via 2nd parameter 'Record'
3
Calling 'Sema::HandleField'
16596 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
16597 /*InitStyle=*/ICIS_NoInit, AS_public);
16598 return Res;
16599}
16600
16601/// HandleField - Analyze a field of a C struct or a C++ data member.
16602///
16603FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
16604 SourceLocation DeclStart,
16605 Declarator &D, Expr *BitWidth,
16606 InClassInitStyle InitStyle,
16607 AccessSpecifier AS) {
16608 if (D.isDecompositionDeclarator()) {
4
Calling 'Declarator::isDecompositionDeclarator'
13
Returning from 'Declarator::isDecompositionDeclarator'
14
Taking false branch
16609 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
16610 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
16611 << Decomp.getSourceRange();
16612 return nullptr;
16613 }
16614
16615 IdentifierInfo *II = D.getIdentifier();
16616 SourceLocation Loc = DeclStart;
16617 if (II
14.1
'II' is null
14.1
'II' is null
14.1
'II' is null
) Loc = D.getIdentifierLoc();
15
Taking false branch
16618
16619 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16620 QualType T = TInfo->getType();
16621 if (getLangOpts().CPlusPlus) {
16
Assuming field 'CPlusPlus' is 0
17
Taking false branch
16622 CheckExtraCXXDefaultArguments(D);
16623
16624 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16625 UPPC_DataMemberType)) {
16626 D.setInvalidType();
16627 T = Context.IntTy;
16628 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
16629 }
16630 }
16631
16632 DiagnoseFunctionSpecifiers(D.getDeclSpec());
16633
16634 if (D.getDeclSpec().isInlineSpecified())
18
Assuming the condition is false
19
Taking false branch
16635 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
16636 << getLangOpts().CPlusPlus17;
16637 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
20
Assuming 'TSCS' is 0
21
Taking false branch
16638 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
16639 diag::err_invalid_thread)
16640 << DeclSpec::getSpecifierName(TSCS);
16641
16642 // Check to see if this name was declared as a member previously
16643 NamedDecl *PrevDecl = nullptr;
16644 LookupResult Previous(*this, II, Loc, LookupMemberName,
16645 ForVisibleRedeclaration);
16646 LookupName(Previous, S);
16647 switch (Previous.getResultKind()) {
22
Control jumps to 'case Ambiguous:' at line 16659
16648 case LookupResult::Found:
16649 case LookupResult::FoundUnresolvedValue:
16650 PrevDecl = Previous.getAsSingle<NamedDecl>();
16651 break;
16652
16653 case LookupResult::FoundOverloaded:
16654 PrevDecl = Previous.getRepresentativeDecl();
16655 break;
16656
16657 case LookupResult::NotFound:
16658 case LookupResult::NotFoundInCurrentInstantiation:
16659 case LookupResult::Ambiguous:
16660 break;
23
Execution continues on line 16662
16661 }
16662 Previous.suppressDiagnostics();
16663
16664 if (PrevDecl
23.1
'PrevDecl' is null
23.1
'PrevDecl' is null
23.1
'PrevDecl' is null
&& PrevDecl->isTemplateParameter()) {
16665 // Maybe we will complain about the shadowed template parameter.
16666 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16667 // Just pretend that we didn't see the previous declaration.
16668 PrevDecl = nullptr;
16669 }
16670
16671 if (PrevDecl
23.2
'PrevDecl' is null
23.2
'PrevDecl' is null
23.2
'PrevDecl' is null
&& !isDeclInScope(PrevDecl, Record, S))
16672 PrevDecl = nullptr;
16673
16674 bool Mutable
16675 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
24
Assuming the condition is false
16676 SourceLocation TSSL = D.getBeginLoc();
16677 FieldDecl *NewFD
16678 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
25
Passing null pointer value via 4th parameter 'Record'
26
Calling 'Sema::CheckFieldDecl'
16679 TSSL, AS, PrevDecl, &D);
16680
16681 if (NewFD->isInvalidDecl())
16682 Record->setInvalidDecl();
16683
16684 if (D.getDeclSpec().isModulePrivateSpecified())
16685 NewFD->setModulePrivate();
16686
16687 if (NewFD->isInvalidDecl() && PrevDecl) {
16688 // Don't introduce NewFD into scope; there's already something
16689 // with the same name in the same scope.
16690 } else if (II) {
16691 PushOnScopeChains(NewFD, S);
16692 } else
16693 Record->addDecl(NewFD);
16694
16695 return NewFD;
16696}
16697
16698/// Build a new FieldDecl and check its well-formedness.
16699///
16700/// This routine builds a new FieldDecl given the fields name, type,
16701/// record, etc. \p PrevDecl should refer to any previous declaration
16702/// with the same name and in the same scope as the field to be
16703/// created.
16704///
16705/// \returns a new FieldDecl.
16706///
16707/// \todo The Declarator argument is a hack. It will be removed once
16708FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
16709 TypeSourceInfo *TInfo,
16710 RecordDecl *Record, SourceLocation Loc,
16711 bool Mutable, Expr *BitWidth,
16712 InClassInitStyle InitStyle,
16713 SourceLocation TSSL,
16714 AccessSpecifier AS, NamedDecl *PrevDecl,
16715 Declarator *D) {
16716 IdentifierInfo *II = Name.getAsIdentifierInfo();
16717 bool InvalidDecl = false;
16718 if (D
26.1
'D' is non-null
26.1
'D' is non-null
26.1
'D' is non-null
) InvalidDecl = D->isInvalidType();
27
Taking true branch
28
Calling 'Declarator::isInvalidType'
32
Returning from 'Declarator::isInvalidType'
16719
16720 // If we receive a broken type, recover by assuming 'int' and
16721 // marking this declaration as invalid.
16722 if (T.isNull() || T->containsErrors()) {
33
Assuming the condition is false
34
Taking false branch
16723 InvalidDecl = true;
16724 T = Context.IntTy;
16725 }
16726
16727 QualType EltTy = Context.getBaseElementType(T);
16728 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
35
Assuming the condition is false
16729 if (RequireCompleteSizedType(Loc, EltTy,
16730 diag::err_field_incomplete_or_sizeless)) {
16731 // Fields of incomplete type force their record to be invalid.
16732 Record->setInvalidDecl();
16733 InvalidDecl = true;
16734 } else {
16735 NamedDecl *Def;
16736 EltTy->isIncompleteType(&Def);
16737 if (Def && Def->isInvalidDecl()) {
16738 Record->setInvalidDecl();
16739 InvalidDecl = true;
16740 }
16741 }
16742 }
16743
16744 // TR 18037 does not allow fields to be declared with address space
16745 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
36
Assuming the condition is false
37
Taking false branch
16746 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
16747 Diag(Loc, diag::err_field_with_address_space);
16748 Record->setInvalidDecl();
16749 InvalidDecl = true;
16750 }
16751
16752 if (LangOpts.OpenCL) {
38
Assuming field 'OpenCL' is 0
39
Taking false branch
16753 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
16754 // used as structure or union field: image, sampler, event or block types.
16755 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
16756 T->isBlockPointerType()) {
16757 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
16758 Record->setInvalidDecl();
16759 InvalidDecl = true;
16760 }
16761 // OpenCL v1.2 s6.9.c: bitfields are not supported.
16762 if (BitWidth) {
16763 Diag(Loc, diag::err_opencl_bitfields);
16764 InvalidDecl = true;
16765 }
16766 }
16767
16768 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
16769 if (!InvalidDecl
39.1
'InvalidDecl' is false
39.1
'InvalidDecl' is false
39.1
'InvalidDecl' is false
&& getLangOpts().CPlusPlus && !II && BitWidth &&
40
Assuming field 'CPlusPlus' is 0
16770 T.hasQualifiers()) {
16771 InvalidDecl = true;
16772 Diag(Loc, diag::err_anon_bitfield_qualifiers);
16773 }
16774
16775 // C99 6.7.2.1p8: A member of a structure or union may have any type other
16776 // than a variably modified type.
16777 if (!InvalidDecl
40.1
'InvalidDecl' is false
40.1
'InvalidDecl' is false
40.1
'InvalidDecl' is false
&& T->isVariablyModifiedType()) {
41
Assuming the condition is false
42
Taking false branch
16778 if (!tryToFixVariablyModifiedVarType(
16779 *this, TInfo, T, Loc, diag::err_typecheck_field_variable_size))
16780 InvalidDecl = true;
16781 }
16782
16783 // Fields can not have abstract class types
16784 if (!InvalidDecl
42.1
'InvalidDecl' is false
42.1
'InvalidDecl' is false
42.1
'InvalidDecl' is false
&& RequireNonAbstractType(Loc, T,
43
Assuming the condition is false
44
Taking false branch
16785 diag::err_abstract_type_in_decl,
16786 AbstractFieldType))
16787 InvalidDecl = true;
16788
16789 bool ZeroWidth = false;
16790 if (InvalidDecl
44.1
'InvalidDecl' is false
44.1
'InvalidDecl' is false
44.1
'InvalidDecl' is false
)
45
Taking false branch
16791 BitWidth = nullptr;
16792 // If this is declared as a bit-field, check the bit-field.
16793 if (BitWidth) {
46
Assuming 'BitWidth' is null
47
Taking false branch
16794 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
16795 &ZeroWidth).get();
16796 if (!BitWidth) {
16797 InvalidDecl = true;
16798 BitWidth = nullptr;
16799 ZeroWidth = false;
16800 }
16801 }
16802
16803 // Check that 'mutable' is consistent with the type of the declaration.
16804 if (!InvalidDecl
47.1
'InvalidDecl' is false
47.1
'InvalidDecl' is false
47.1
'InvalidDecl' is false
&& Mutable
47.2
'Mutable' is false
47.2
'Mutable' is false
47.2
'Mutable' is false
) {
48
Taking false branch
16805 unsigned DiagID = 0;
16806 if (T->isReferenceType())
16807 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
16808 : diag::err_mutable_reference;
16809 else if (T.isConstQualified())
16810 DiagID = diag::err_mutable_const;
16811
16812 if (DiagID) {
16813 SourceLocation ErrLoc = Loc;
16814 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
16815 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
16816 Diag(ErrLoc, DiagID);
16817 if (DiagID != diag::ext_mutable_reference) {
16818 Mutable = false;
16819 InvalidDecl = true;
16820 }
16821 }
16822 }
16823
16824 // C++11 [class.union]p8 (DR1460):
16825 // At most one variant member of a union may have a
16826 // brace-or-equal-initializer.
16827 if (InitStyle
48.1
'InitStyle' is equal to ICIS_NoInit
48.1
'InitStyle' is equal to ICIS_NoInit
48.1
'InitStyle' is equal to ICIS_NoInit
!= ICIS_NoInit)
49
Taking false branch
16828 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
16829
16830 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
16831 BitWidth, Mutable, InitStyle);
16832 if (InvalidDecl
49.1
'InvalidDecl' is false
49.1
'InvalidDecl' is false
49.1
'InvalidDecl' is false
)
50
Taking false branch
16833 NewFD->setInvalidDecl();
16834
16835 if (PrevDecl
50.1
'PrevDecl' is null
50.1
'PrevDecl' is null
50.1
'PrevDecl' is null
&& !isa<TagDecl>(PrevDecl)) {
16836 Diag(Loc, diag::err_duplicate_member) << II;
16837 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16838 NewFD->setInvalidDecl();
16839 }
16840
16841 if (!InvalidDecl
50.2
'InvalidDecl' is false
50.2
'InvalidDecl' is false
50.2
'InvalidDecl' is false
&& getLangOpts().CPlusPlus) {
51
Assuming field 'CPlusPlus' is not equal to 0
52
Taking true branch
16842 if (Record->isUnion()) {
53
Called C++ object pointer is null
16843 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16844 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
16845 if (RDecl->getDefinition()) {
16846 // C++ [class.union]p1: An object of a class with a non-trivial
16847 // constructor, a non-trivial copy constructor, a non-trivial
16848 // destructor, or a non-trivial copy assignment operator
16849 // cannot be a member of a union, nor can an array of such
16850 // objects.
16851 if (CheckNontrivialField(NewFD))
16852 NewFD->setInvalidDecl();
16853 }
16854 }
16855
16856 // C++ [class.union]p1: If a union contains a member of reference type,
16857 // the program is ill-formed, except when compiling with MSVC extensions
16858 // enabled.
16859 if (EltTy->isReferenceType()) {
16860 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
16861 diag::ext_union_member_of_reference_type :
16862 diag::err_union_member_of_reference_type)
16863 << NewFD->getDeclName() << EltTy;
16864 if (!getLangOpts().MicrosoftExt)
16865 NewFD->setInvalidDecl();
16866 }
16867 }
16868 }
16869
16870 // FIXME: We need to pass in the attributes given an AST
16871 // representation, not a parser representation.
16872 if (D) {
16873 // FIXME: The current scope is almost... but not entirely... correct here.
16874 ProcessDeclAttributes(getCurScope(), NewFD, *D);
16875
16876 if (NewFD->hasAttrs())
16877 CheckAlignasUnderalignment(NewFD);
16878 }
16879
16880 // In auto-retain/release, infer strong retension for fields of
16881 // retainable type.
16882 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
16883 NewFD->setInvalidDecl();
16884
16885 if (T.isObjCGCWeak())
16886 Diag(Loc, diag::warn_attribute_weak_on_field);
16887
16888 // PPC MMA non-pointer types are not allowed as field types.
16889 if (Context.getTargetInfo().getTriple().isPPC64() &&
16890 CheckPPCMMAType(T, NewFD->getLocation()))
16891 NewFD->setInvalidDecl();
16892
16893 NewFD->setAccess(AS);
16894 return NewFD;
16895}
16896
16897bool Sema::CheckNontrivialField(FieldDecl *FD) {
16898 assert(FD)((FD) ? static_cast<void> (0) : __assert_fail ("FD", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 16898, __PRETTY_FUNCTION__))
;
16899 assert(getLangOpts().CPlusPlus && "valid check only for C++")((getLangOpts().CPlusPlus && "valid check only for C++"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"valid check only for C++\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 16899, __PRETTY_FUNCTION__))
;
16900
16901 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
16902 return false;
16903
16904 QualType EltTy = Context.getBaseElementType(FD->getType());
16905 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16906 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
16907 if (RDecl->getDefinition()) {
16908 // We check for copy constructors before constructors
16909 // because otherwise we'll never get complaints about
16910 // copy constructors.
16911
16912 CXXSpecialMember member = CXXInvalid;
16913 // We're required to check for any non-trivial constructors. Since the
16914 // implicit default constructor is suppressed if there are any
16915 // user-declared constructors, we just need to check that there is a
16916 // trivial default constructor and a trivial copy constructor. (We don't
16917 // worry about move constructors here, since this is a C++98 check.)
16918 if (RDecl->hasNonTrivialCopyConstructor())
16919 member = CXXCopyConstructor;
16920 else if (!RDecl->hasTrivialDefaultConstructor())
16921 member = CXXDefaultConstructor;
16922 else if (RDecl->hasNonTrivialCopyAssignment())
16923 member = CXXCopyAssignment;
16924 else if (RDecl->hasNonTrivialDestructor())
16925 member = CXXDestructor;
16926
16927 if (member != CXXInvalid) {
16928 if (!getLangOpts().CPlusPlus11 &&
16929 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
16930 // Objective-C++ ARC: it is an error to have a non-trivial field of
16931 // a union. However, system headers in Objective-C programs
16932 // occasionally have Objective-C lifetime objects within unions,
16933 // and rather than cause the program to fail, we make those
16934 // members unavailable.
16935 SourceLocation Loc = FD->getLocation();
16936 if (getSourceManager().isInSystemHeader(Loc)) {
16937 if (!FD->hasAttr<UnavailableAttr>())
16938 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
16939 UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
16940 return false;
16941 }
16942 }
16943
16944 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
16945 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
16946 diag::err_illegal_union_or_anon_struct_member)
16947 << FD->getParent()->isUnion() << FD->getDeclName() << member;
16948 DiagnoseNontrivial(RDecl, member);
16949 return !getLangOpts().CPlusPlus11;
16950 }
16951 }
16952 }
16953
16954 return false;
16955}
16956
16957/// TranslateIvarVisibility - Translate visibility from a token ID to an
16958/// AST enum value.
16959static ObjCIvarDecl::AccessControl
16960TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
16961 switch (ivarVisibility) {
16962 default: llvm_unreachable("Unknown visitibility kind")::llvm::llvm_unreachable_internal("Unknown visitibility kind"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 16962)
;
16963 case tok::objc_private: return ObjCIvarDecl::Private;
16964 case tok::objc_public: return ObjCIvarDecl::Public;
16965 case tok::objc_protected: return ObjCIvarDecl::Protected;
16966 case tok::objc_package: return ObjCIvarDecl::Package;
16967 }
16968}
16969
16970/// ActOnIvar - Each ivar field of an objective-c class is passed into this
16971/// in order to create an IvarDecl object for it.
16972Decl *Sema::ActOnIvar(Scope *S,
16973 SourceLocation DeclStart,
16974 Declarator &D, Expr *BitfieldWidth,
16975 tok::ObjCKeywordKind Visibility) {
16976
16977 IdentifierInfo *II = D.getIdentifier();
16978 Expr *BitWidth = (Expr*)BitfieldWidth;
16979 SourceLocation Loc = DeclStart;
16980 if (II) Loc = D.getIdentifierLoc();
16981
16982 // FIXME: Unnamed fields can be handled in various different ways, for
16983 // example, unnamed unions inject all members into the struct namespace!
16984
16985 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16986 QualType T = TInfo->getType();
16987
16988 if (BitWidth) {
16989 // 6.7.2.1p3, 6.7.2.1p4
16990 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
16991 if (!BitWidth)
16992 D.setInvalidType();
16993 } else {
16994 // Not a bitfield.
16995
16996 // validate II.
16997
16998 }
16999 if (T->isReferenceType()) {
17000 Diag(Loc, diag::err_ivar_reference_type);
17001 D.setInvalidType();
17002 }
17003 // C99 6.7.2.1p8: A member of a structure or union may have any type other
17004 // than a variably modified type.
17005 else if (T->isVariablyModifiedType()) {
17006 if (!tryToFixVariablyModifiedVarType(
17007 *this, TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
17008 D.setInvalidType();
17009 }
17010
17011 // Get the visibility (access control) for this ivar.
17012 ObjCIvarDecl::AccessControl ac =
17013 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
17014 : ObjCIvarDecl::None;
17015 // Must set ivar's DeclContext to its enclosing interface.
17016 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
17017 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
17018 return nullptr;
17019 ObjCContainerDecl *EnclosingContext;
17020 if (ObjCImplementationDecl *IMPDecl =
17021 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17022 if (LangOpts.ObjCRuntime.isFragile()) {
17023 // Case of ivar declared in an implementation. Context is that of its class.
17024 EnclosingContext = IMPDecl->getClassInterface();
17025 assert(EnclosingContext && "Implementation has no class interface!")((EnclosingContext && "Implementation has no class interface!"
) ? static_cast<void> (0) : __assert_fail ("EnclosingContext && \"Implementation has no class interface!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 17025, __PRETTY_FUNCTION__))
;
17026 }
17027 else
17028 EnclosingContext = EnclosingDecl;
17029 } else {
17030 if (ObjCCategoryDecl *CDecl =
17031 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17032 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
17033 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
17034 return nullptr;
17035 }
17036 }
17037 EnclosingContext = EnclosingDecl;
17038 }
17039
17040 // Construct the decl.
17041 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
17042 DeclStart, Loc, II, T,
17043 TInfo, ac, (Expr *)BitfieldWidth);
17044
17045 if (II) {
17046 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
17047 ForVisibleRedeclaration);
17048 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
17049 && !isa<TagDecl>(PrevDecl)) {
17050 Diag(Loc, diag::err_duplicate_member) << II;
17051 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17052 NewID->setInvalidDecl();
17053 }
17054 }
17055
17056 // Process attributes attached to the ivar.
17057 ProcessDeclAttributes(S, NewID, D);
17058
17059 if (D.isInvalidType())
17060 NewID->setInvalidDecl();
17061
17062 // In ARC, infer 'retaining' for ivars of retainable type.
17063 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
17064 NewID->setInvalidDecl();
17065
17066 if (D.getDeclSpec().isModulePrivateSpecified())
17067 NewID->setModulePrivate();
17068
17069 if (II) {
17070 // FIXME: When interfaces are DeclContexts, we'll need to add
17071 // these to the interface.
17072 S->AddDecl(NewID);
17073 IdResolver.AddDecl(NewID);
17074 }
17075
17076 if (LangOpts.ObjCRuntime.isNonFragile() &&
17077 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
17078 Diag(Loc, diag::warn_ivars_in_interface);
17079
17080 return NewID;
17081}
17082
17083/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
17084/// class and class extensions. For every class \@interface and class
17085/// extension \@interface, if the last ivar is a bitfield of any type,
17086/// then add an implicit `char :0` ivar to the end of that interface.
17087void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
17088 SmallVectorImpl<Decl *> &AllIvarDecls) {
17089 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
17090 return;
17091
17092 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
17093 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
17094
17095 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
17096 return;
17097 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
17098 if (!ID) {
17099 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
17100 if (!CD->IsClassExtension())
17101 return;
17102 }
17103 // No need to add this to end of @implementation.
17104 else
17105 return;
17106 }
17107 // All conditions are met. Add a new bitfield to the tail end of ivars.
17108 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
17109 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
17110
17111 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
17112 DeclLoc, DeclLoc, nullptr,
17113 Context.CharTy,
17114 Context.getTrivialTypeSourceInfo(Context.CharTy,
17115 DeclLoc),
17116 ObjCIvarDecl::Private, BW,
17117 true);
17118 AllIvarDecls.push_back(Ivar);
17119}
17120
17121void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
17122 ArrayRef<Decl *> Fields, SourceLocation LBrac,
17123 SourceLocation RBrac,
17124 const ParsedAttributesView &Attrs) {
17125 assert(EnclosingDecl && "missing record or interface decl")((EnclosingDecl && "missing record or interface decl"
) ? static_cast<void> (0) : __assert_fail ("EnclosingDecl && \"missing record or interface decl\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 17125, __PRETTY_FUNCTION__))
;
17126
17127 // If this is an Objective-C @implementation or category and we have
17128 // new fields here we should reset the layout of the interface since
17129 // it will now change.
17130 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
17131 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
17132 switch (DC->getKind()) {
17133 default: break;
17134 case Decl::ObjCCategory:
17135 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
17136 break;
17137 case Decl::ObjCImplementation:
17138 Context.
17139 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
17140 break;
17141 }
17142 }
17143
17144 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
17145 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
17146
17147 // Start counting up the number of named members; make sure to include
17148 // members of anonymous structs and unions in the total.
17149 unsigned NumNamedMembers = 0;
17150 if (Record) {
17151 for (const auto *I : Record->decls()) {
17152 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
17153 if (IFD->getDeclName())
17154 ++NumNamedMembers;
17155 }
17156 }
17157
17158 // Verify that all the fields are okay.
17159 SmallVector<FieldDecl*, 32> RecFields;
17160
17161 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
17162 i != end; ++i) {
17163 FieldDecl *FD = cast<FieldDecl>(*i);
17164
17165 // Get the type for the field.
17166 const Type *FDTy = FD->getType().getTypePtr();
17167
17168 if (!FD->isAnonymousStructOrUnion()) {
17169 // Remember all fields written by the user.
17170 RecFields.push_back(FD);
17171 }
17172
17173 // If the field is already invalid for some reason, don't emit more
17174 // diagnostics about it.
17175 if (FD->isInvalidDecl()) {
17176 EnclosingDecl->setInvalidDecl();
17177 continue;
17178 }
17179
17180 // C99 6.7.2.1p2:
17181 // A structure or union shall not contain a member with
17182 // incomplete or function type (hence, a structure shall not
17183 // contain an instance of itself, but may contain a pointer to
17184 // an instance of itself), except that the last member of a
17185 // structure with more than one named member may have incomplete
17186 // array type; such a structure (and any union containing,
17187 // possibly recursively, a member that is such a structure)
17188 // shall not be a member of a structure or an element of an
17189 // array.
17190 bool IsLastField = (i + 1 == Fields.end());
17191 if (FDTy->isFunctionType()) {
17192 // Field declared as a function.
17193 Diag(FD->getLocation(), diag::err_field_declared_as_function)
17194 << FD->getDeclName();
17195 FD->setInvalidDecl();
17196 EnclosingDecl->setInvalidDecl();
17197 continue;
17198 } else if (FDTy->isIncompleteArrayType() &&
17199 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
17200 if (Record) {
17201 // Flexible array member.
17202 // Microsoft and g++ is more permissive regarding flexible array.
17203 // It will accept flexible array in union and also
17204 // as the sole element of a struct/class.
17205 unsigned DiagID = 0;
17206 if (!Record->isUnion() && !IsLastField) {
17207 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
17208 << FD->getDeclName() << FD->getType() << Record->getTagKind();
17209 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
17210 FD->setInvalidDecl();
17211 EnclosingDecl->setInvalidDecl();
17212 continue;
17213 } else if (Record->isUnion())
17214 DiagID = getLangOpts().MicrosoftExt
17215 ? diag::ext_flexible_array_union_ms
17216 : getLangOpts().CPlusPlus
17217 ? diag::ext_flexible_array_union_gnu
17218 : diag::err_flexible_array_union;
17219 else if (NumNamedMembers < 1)
17220 DiagID = getLangOpts().MicrosoftExt
17221 ? diag::ext_flexible_array_empty_aggregate_ms
17222 : getLangOpts().CPlusPlus
17223 ? diag::ext_flexible_array_empty_aggregate_gnu
17224 : diag::err_flexible_array_empty_aggregate;
17225
17226 if (DiagID)
17227 Diag(FD->getLocation(), DiagID) << FD->getDeclName()
17228 << Record->getTagKind();
17229 // While the layout of types that contain virtual bases is not specified
17230 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
17231 // virtual bases after the derived members. This would make a flexible
17232 // array member declared at the end of an object not adjacent to the end
17233 // of the type.
17234 if (CXXRecord && CXXRecord->getNumVBases() != 0)
17235 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
17236 << FD->getDeclName() << Record->getTagKind();
17237 if (!getLangOpts().C99)
17238 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
17239 << FD->getDeclName() << Record->getTagKind();
17240
17241 // If the element type has a non-trivial destructor, we would not
17242 // implicitly destroy the elements, so disallow it for now.
17243 //
17244 // FIXME: GCC allows this. We should probably either implicitly delete
17245 // the destructor of the containing class, or just allow this.
17246 QualType BaseElem = Context.getBaseElementType(FD->getType());
17247 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
17248 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
17249 << FD->getDeclName() << FD->getType();
17250 FD->setInvalidDecl();
17251 EnclosingDecl->setInvalidDecl();
17252 continue;
17253 }
17254 // Okay, we have a legal flexible array member at the end of the struct.
17255 Record->setHasFlexibleArrayMember(true);
17256 } else {
17257 // In ObjCContainerDecl ivars with incomplete array type are accepted,
17258 // unless they are followed by another ivar. That check is done
17259 // elsewhere, after synthesized ivars are known.
17260 }
17261 } else if (!FDTy->isDependentType() &&
17262 RequireCompleteSizedType(
17263 FD->getLocation(), FD->getType(),
17264 diag::err_field_incomplete_or_sizeless)) {
17265 // Incomplete type
17266 FD->setInvalidDecl();
17267 EnclosingDecl->setInvalidDecl();
17268 continue;
17269 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
17270 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
17271 // A type which contains a flexible array member is considered to be a
17272 // flexible array member.
17273 Record->setHasFlexibleArrayMember(true);
17274 if (!Record->isUnion()) {
17275 // If this is a struct/class and this is not the last element, reject
17276 // it. Note that GCC supports variable sized arrays in the middle of
17277 // structures.
17278 if (!IsLastField)
17279 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
17280 << FD->getDeclName() << FD->getType();
17281 else {
17282 // We support flexible arrays at the end of structs in
17283 // other structs as an extension.
17284 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
17285 << FD->getDeclName();
17286 }
17287 }
17288 }
17289 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
17290 RequireNonAbstractType(FD->getLocation(), FD->getType(),
17291 diag::err_abstract_type_in_decl,
17292 AbstractIvarType)) {
17293 // Ivars can not have abstract class types
17294 FD->setInvalidDecl();
17295 }
17296 if (Record && FDTTy->getDecl()->hasObjectMember())
17297 Record->setHasObjectMember(true);
17298 if (Record && FDTTy->getDecl()->hasVolatileMember())
17299 Record->setHasVolatileMember(true);
17300 } else if (FDTy->isObjCObjectType()) {
17301 /// A field cannot be an Objective-c object
17302 Diag(FD->getLocation(), diag::err_statically_allocated_object)
17303 << FixItHint::CreateInsertion(FD->getLocation(), "*");
17304 QualType T = Context.getObjCObjectPointerType(FD->getType());
17305 FD->setType(T);
17306 } else if (Record && Record->isUnion() &&
17307 FD->getType().hasNonTrivialObjCLifetime() &&
17308 getSourceManager().isInSystemHeader(FD->getLocation()) &&
17309 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
17310 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
17311 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
17312 // For backward compatibility, fields of C unions declared in system
17313 // headers that have non-trivial ObjC ownership qualifications are marked
17314 // as unavailable unless the qualifier is explicit and __strong. This can
17315 // break ABI compatibility between programs compiled with ARC and MRR, but
17316 // is a better option than rejecting programs using those unions under
17317 // ARC.
17318 FD->addAttr(UnavailableAttr::CreateImplicit(
17319 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
17320 FD->getLocation()));
17321 } else if (getLangOpts().ObjC &&
17322 getLangOpts().getGC() != LangOptions::NonGC && Record &&
17323 !Record->hasObjectMember()) {
17324 if (FD->getType()->isObjCObjectPointerType() ||
17325 FD->getType().isObjCGCStrong())
17326 Record->setHasObjectMember(true);
17327 else if (Context.getAsArrayType(FD->getType())) {
17328 QualType BaseType = Context.getBaseElementType(FD->getType());
17329 if (BaseType->isRecordType() &&
17330 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
17331 Record->setHasObjectMember(true);
17332 else if (BaseType->isObjCObjectPointerType() ||
17333 BaseType.isObjCGCStrong())
17334 Record->setHasObjectMember(true);
17335 }
17336 }
17337
17338 if (Record && !getLangOpts().CPlusPlus &&
17339 !shouldIgnoreForRecordTriviality(FD)) {
17340 QualType FT = FD->getType();
17341 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
17342 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
17343 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
17344 Record->isUnion())
17345 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
17346 }
17347 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
17348 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
17349 Record->setNonTrivialToPrimitiveCopy(true);
17350 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
17351 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
17352 }
17353 if (FT.isDestructedType()) {
17354 Record->setNonTrivialToPrimitiveDestroy(true);
17355 Record->setParamDestroyedInCallee(true);
17356 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
17357 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
17358 }
17359
17360 if (const auto *RT = FT->getAs<RecordType>()) {
17361 if (RT->getDecl()->getArgPassingRestrictions() ==
17362 RecordDecl::APK_CanNeverPassInRegs)
17363 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17364 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
17365 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17366 }
17367
17368 if (Record && FD->getType().isVolatileQualified())
17369 Record->setHasVolatileMember(true);
17370 // Keep track of the number of named members.
17371 if (FD->getIdentifier())
17372 ++NumNamedMembers;
17373 }
17374
17375 // Okay, we successfully defined 'Record'.
17376 if (Record) {
17377 bool Completed = false;
17378 if (CXXRecord) {
17379 if (!CXXRecord->isInvalidDecl()) {
17380 // Set access bits correctly on the directly-declared conversions.
17381 for (CXXRecordDecl::conversion_iterator
17382 I = CXXRecord->conversion_begin(),
17383 E = CXXRecord->conversion_end(); I != E; ++I)
17384 I.setAccess((*I)->getAccess());
17385 }
17386
17387 // Add any implicitly-declared members to this class.
17388 AddImplicitlyDeclaredMembersToClass(CXXRecord);
17389
17390 if (!CXXRecord->isDependentType()) {
17391 if (!CXXRecord->isInvalidDecl()) {
17392 // If we have virtual base classes, we may end up finding multiple
17393 // final overriders for a given virtual function. Check for this
17394 // problem now.
17395 if (CXXRecord->getNumVBases()) {
17396 CXXFinalOverriderMap FinalOverriders;
17397 CXXRecord->getFinalOverriders(FinalOverriders);
17398
17399 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
17400 MEnd = FinalOverriders.end();
17401 M != MEnd; ++M) {
17402 for (OverridingMethods::iterator SO = M->second.begin(),
17403 SOEnd = M->second.end();
17404 SO != SOEnd; ++SO) {
17405 assert(SO->second.size() > 0 &&((SO->second.size() > 0 && "Virtual function without overriding functions?"
) ? static_cast<void> (0) : __assert_fail ("SO->second.size() > 0 && \"Virtual function without overriding functions?\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 17406, __PRETTY_FUNCTION__))
17406 "Virtual function without overriding functions?")((SO->second.size() > 0 && "Virtual function without overriding functions?"
) ? static_cast<void> (0) : __assert_fail ("SO->second.size() > 0 && \"Virtual function without overriding functions?\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 17406, __PRETTY_FUNCTION__))
;
17407 if (SO->second.size() == 1)
17408 continue;
17409
17410 // C++ [class.virtual]p2:
17411 // In a derived class, if a virtual member function of a base
17412 // class subobject has more than one final overrider the
17413 // program is ill-formed.
17414 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
17415 << (const NamedDecl *)M->first << Record;
17416 Diag(M->first->getLocation(),
17417 diag::note_overridden_virtual_function);
17418 for (OverridingMethods::overriding_iterator
17419 OM = SO->second.begin(),
17420 OMEnd = SO->second.end();
17421 OM != OMEnd; ++OM)
17422 Diag(OM->Method->getLocation(), diag::note_final_overrider)
17423 << (const NamedDecl *)M->first << OM->Method->getParent();
17424
17425 Record->setInvalidDecl();
17426 }
17427 }
17428 CXXRecord->completeDefinition(&FinalOverriders);
17429 Completed = true;
17430 }
17431 }
17432 }
17433 }
17434
17435 if (!Completed)
17436 Record->completeDefinition();
17437
17438 // Handle attributes before checking the layout.
17439 ProcessDeclAttributeList(S, Record, Attrs);
17440
17441 // We may have deferred checking for a deleted destructor. Check now.
17442 if (CXXRecord) {
17443 auto *Dtor = CXXRecord->getDestructor();
17444 if (Dtor && Dtor->isImplicit() &&
17445 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
17446 CXXRecord->setImplicitDestructorIsDeleted();
17447 SetDeclDeleted(Dtor, CXXRecord->getLocation());
17448 }
17449 }
17450
17451 if (Record->hasAttrs()) {
17452 CheckAlignasUnderalignment(Record);
17453
17454 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
17455 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
17456 IA->getRange(), IA->getBestCase(),
17457 IA->getInheritanceModel());
17458 }
17459
17460 // Check if the structure/union declaration is a type that can have zero
17461 // size in C. For C this is a language extension, for C++ it may cause
17462 // compatibility problems.
17463 bool CheckForZeroSize;
17464 if (!getLangOpts().CPlusPlus) {
17465 CheckForZeroSize = true;
17466 } else {
17467 // For C++ filter out types that cannot be referenced in C code.
17468 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
17469 CheckForZeroSize =
17470 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
17471 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
17472 CXXRecord->isCLike();
17473 }
17474 if (CheckForZeroSize) {
17475 bool ZeroSize = true;
17476 bool IsEmpty = true;
17477 unsigned NonBitFields = 0;
17478 for (RecordDecl::field_iterator I = Record->field_begin(),
17479 E = Record->field_end();
17480 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
17481 IsEmpty = false;
17482 if (I->isUnnamedBitfield()) {
17483 if (!I->isZeroLengthBitField(Context))
17484 ZeroSize = false;
17485 } else {
17486 ++NonBitFields;
17487 QualType FieldType = I->getType();
17488 if (FieldType->isIncompleteType() ||
17489 !Context.getTypeSizeInChars(FieldType).isZero())
17490 ZeroSize = false;
17491 }
17492 }
17493
17494 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
17495 // allowed in C++, but warn if its declaration is inside
17496 // extern "C" block.
17497 if (ZeroSize) {
17498 Diag(RecLoc, getLangOpts().CPlusPlus ?
17499 diag::warn_zero_size_struct_union_in_extern_c :
17500 diag::warn_zero_size_struct_union_compat)
17501 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
17502 }
17503
17504 // Structs without named members are extension in C (C99 6.7.2.1p7),
17505 // but are accepted by GCC.
17506 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
17507 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
17508 diag::ext_no_named_members_in_struct_union)
17509 << Record->isUnion();
17510 }
17511 }
17512 } else {
17513 ObjCIvarDecl **ClsFields =
17514 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
17515 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
17516 ID->setEndOfDefinitionLoc(RBrac);
17517 // Add ivar's to class's DeclContext.
17518 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17519 ClsFields[i]->setLexicalDeclContext(ID);
17520 ID->addDecl(ClsFields[i]);
17521 }
17522 // Must enforce the rule that ivars in the base classes may not be
17523 // duplicates.
17524 if (ID->getSuperClass())
17525 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
17526 } else if (ObjCImplementationDecl *IMPDecl =
17527 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17528 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl")((IMPDecl && "ActOnFields - missing ObjCImplementationDecl"
) ? static_cast<void> (0) : __assert_fail ("IMPDecl && \"ActOnFields - missing ObjCImplementationDecl\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 17528, __PRETTY_FUNCTION__))
;
17529 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
17530 // Ivar declared in @implementation never belongs to the implementation.
17531 // Only it is in implementation's lexical context.
17532 ClsFields[I]->setLexicalDeclContext(IMPDecl);
17533 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
17534 IMPDecl->setIvarLBraceLoc(LBrac);
17535 IMPDecl->setIvarRBraceLoc(RBrac);
17536 } else if (ObjCCategoryDecl *CDecl =
17537 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17538 // case of ivars in class extension; all other cases have been
17539 // reported as errors elsewhere.
17540 // FIXME. Class extension does not have a LocEnd field.
17541 // CDecl->setLocEnd(RBrac);
17542 // Add ivar's to class extension's DeclContext.
17543 // Diagnose redeclaration of private ivars.
17544 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
17545 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17546 if (IDecl) {
17547 if (const ObjCIvarDecl *ClsIvar =
17548 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
17549 Diag(ClsFields[i]->getLocation(),
17550 diag::err_duplicate_ivar_declaration);
17551 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
17552 continue;
17553 }
17554 for (const auto *Ext : IDecl->known_extensions()) {
17555 if (const ObjCIvarDecl *ClsExtIvar
17556 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
17557 Diag(ClsFields[i]->getLocation(),
17558 diag::err_duplicate_ivar_declaration);
17559 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
17560 continue;
17561 }
17562 }
17563 }
17564 ClsFields[i]->setLexicalDeclContext(CDecl);
17565 CDecl->addDecl(ClsFields[i]);
17566 }
17567 CDecl->setIvarLBraceLoc(LBrac);
17568 CDecl->setIvarRBraceLoc(RBrac);
17569 }
17570 }
17571}
17572
17573/// Determine whether the given integral value is representable within
17574/// the given type T.
17575static bool isRepresentableIntegerValue(ASTContext &Context,
17576 llvm::APSInt &Value,
17577 QualType T) {
17578 assert((T->isIntegralType(Context) || T->isEnumeralType()) &&(((T->isIntegralType(Context) || T->isEnumeralType()) &&
"Integral type required!") ? static_cast<void> (0) : __assert_fail
("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 17579, __PRETTY_FUNCTION__))
17579 "Integral type required!")(((T->isIntegralType(Context) || T->isEnumeralType()) &&
"Integral type required!") ? static_cast<void> (0) : __assert_fail
("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 17579, __PRETTY_FUNCTION__))
;
17580 unsigned BitWidth = Context.getIntWidth(T);
17581
17582 if (Value.isUnsigned() || Value.isNonNegative()) {
17583 if (T->isSignedIntegerOrEnumerationType())
17584 --BitWidth;
17585 return Value.getActiveBits() <= BitWidth;
17586 }
17587 return Value.getMinSignedBits() <= BitWidth;
17588}
17589
17590// Given an integral type, return the next larger integral type
17591// (or a NULL type of no such type exists).
17592static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
17593 // FIXME: Int128/UInt128 support, which also needs to be introduced into
17594 // enum checking below.
17595 assert((T->isIntegralType(Context) ||(((T->isIntegralType(Context) || T->isEnumeralType()) &&
"Integral type required!") ? static_cast<void> (0) : __assert_fail
("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 17596, __PRETTY_FUNCTION__))
17596 T->isEnumeralType()) && "Integral type required!")(((T->isIntegralType(Context) || T->isEnumeralType()) &&
"Integral type required!") ? static_cast<void> (0) : __assert_fail
("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 17596, __PRETTY_FUNCTION__))
;
17597 const unsigned NumTypes = 4;
17598 QualType SignedIntegralTypes[NumTypes] = {
17599 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
17600 };
17601 QualType UnsignedIntegralTypes[NumTypes] = {
17602 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
17603 Context.UnsignedLongLongTy
17604 };
17605
17606 unsigned BitWidth = Context.getTypeSize(T);
17607 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
17608 : UnsignedIntegralTypes;
17609 for (unsigned I = 0; I != NumTypes; ++I)
17610 if (Context.getTypeSize(Types[I]) > BitWidth)
17611 return Types[I];
17612
17613 return QualType();
17614}
17615
17616EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
17617 EnumConstantDecl *LastEnumConst,
17618 SourceLocation IdLoc,
17619 IdentifierInfo *Id,
17620 Expr *Val) {
17621 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17622 llvm::APSInt EnumVal(IntWidth);
17623 QualType EltTy;
17624
17625 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
17626 Val = nullptr;
17627
17628 if (Val)
17629 Val = DefaultLvalueConversion(Val).get();
17630
17631 if (Val) {
17632 if (Enum->isDependentType() || Val->isTypeDependent())
17633 EltTy = Context.DependentTy;
17634 else {
17635 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
17636 // underlying type, but do allow it in all other contexts.
17637 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
17638 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
17639 // constant-expression in the enumerator-definition shall be a converted
17640 // constant expression of the underlying type.
17641 EltTy = Enum->getIntegerType();
17642 ExprResult Converted =
17643 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
17644 CCEK_Enumerator);
17645 if (Converted.isInvalid())
17646 Val = nullptr;
17647 else
17648 Val = Converted.get();
17649 } else if (!Val->isValueDependent() &&
17650 !(Val =
17651 VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
17652 .get())) {
17653 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
17654 } else {
17655 if (Enum->isComplete()) {
17656 EltTy = Enum->getIntegerType();
17657
17658 // In Obj-C and Microsoft mode, require the enumeration value to be
17659 // representable in the underlying type of the enumeration. In C++11,
17660 // we perform a non-narrowing conversion as part of converted constant
17661 // expression checking.
17662 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17663 if (Context.getTargetInfo()
17664 .getTriple()
17665 .isWindowsMSVCEnvironment()) {
17666 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
17667 } else {
17668 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
17669 }
17670 }
17671
17672 // Cast to the underlying type.
17673 Val = ImpCastExprToType(Val, EltTy,
17674 EltTy->isBooleanType() ? CK_IntegralToBoolean
17675 : CK_IntegralCast)
17676 .get();
17677 } else if (getLangOpts().CPlusPlus) {
17678 // C++11 [dcl.enum]p5:
17679 // If the underlying type is not fixed, the type of each enumerator
17680 // is the type of its initializing value:
17681 // - If an initializer is specified for an enumerator, the
17682 // initializing value has the same type as the expression.
17683 EltTy = Val->getType();
17684 } else {
17685 // C99 6.7.2.2p2:
17686 // The expression that defines the value of an enumeration constant
17687 // shall be an integer constant expression that has a value
17688 // representable as an int.
17689
17690 // Complain if the value is not representable in an int.
17691 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
17692 Diag(IdLoc, diag::ext_enum_value_not_int)
17693 << EnumVal.toString(10) << Val->getSourceRange()
17694 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
17695 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
17696 // Force the type of the expression to 'int'.
17697 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
17698 }
17699 EltTy = Val->getType();
17700 }
17701 }
17702 }
17703 }
17704
17705 if (!Val) {
17706 if (Enum->isDependentType())
17707 EltTy = Context.DependentTy;
17708 else if (!LastEnumConst) {
17709 // C++0x [dcl.enum]p5:
17710 // If the underlying type is not fixed, the type of each enumerator
17711 // is the type of its initializing value:
17712 // - If no initializer is specified for the first enumerator, the
17713 // initializing value has an unspecified integral type.
17714 //
17715 // GCC uses 'int' for its unspecified integral type, as does
17716 // C99 6.7.2.2p3.
17717 if (Enum->isFixed()) {
17718 EltTy = Enum->getIntegerType();
17719 }
17720 else {
17721 EltTy = Context.IntTy;
17722 }
17723 } else {
17724 // Assign the last value + 1.
17725 EnumVal = LastEnumConst->getInitVal();
17726 ++EnumVal;
17727 EltTy = LastEnumConst->getType();
17728
17729 // Check for overflow on increment.
17730 if (EnumVal < LastEnumConst->getInitVal()) {
17731 // C++0x [dcl.enum]p5:
17732 // If the underlying type is not fixed, the type of each enumerator
17733 // is the type of its initializing value:
17734 //
17735 // - Otherwise the type of the initializing value is the same as
17736 // the type of the initializing value of the preceding enumerator
17737 // unless the incremented value is not representable in that type,
17738 // in which case the type is an unspecified integral type
17739 // sufficient to contain the incremented value. If no such type
17740 // exists, the program is ill-formed.
17741 QualType T = getNextLargerIntegralType(Context, EltTy);
17742 if (T.isNull() || Enum->isFixed()) {
17743 // There is no integral type larger enough to represent this
17744 // value. Complain, then allow the value to wrap around.
17745 EnumVal = LastEnumConst->getInitVal();
17746 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
17747 ++EnumVal;
17748 if (Enum->isFixed())
17749 // When the underlying type is fixed, this is ill-formed.
17750 Diag(IdLoc, diag::err_enumerator_wrapped)
17751 << EnumVal.toString(10)
17752 << EltTy;
17753 else
17754 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
17755 << EnumVal.toString(10);
17756 } else {
17757 EltTy = T;
17758 }
17759
17760 // Retrieve the last enumerator's value, extent that type to the
17761 // type that is supposed to be large enough to represent the incremented
17762 // value, then increment.
17763 EnumVal = LastEnumConst->getInitVal();
17764 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17765 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
17766 ++EnumVal;
17767
17768 // If we're not in C++, diagnose the overflow of enumerator values,
17769 // which in C99 means that the enumerator value is not representable in
17770 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
17771 // permits enumerator values that are representable in some larger
17772 // integral type.
17773 if (!getLangOpts().CPlusPlus && !T.isNull())
17774 Diag(IdLoc, diag::warn_enum_value_overflow);
17775 } else if (!getLangOpts().CPlusPlus &&
17776 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17777 // Enforce C99 6.7.2.2p2 even when we compute the next value.
17778 Diag(IdLoc, diag::ext_enum_value_not_int)
17779 << EnumVal.toString(10) << 1;
17780 }
17781 }
17782 }
17783
17784 if (!EltTy->isDependentType()) {
17785 // Make the enumerator value match the signedness and size of the
17786 // enumerator's type.
17787 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
17788 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17789 }
17790
17791 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
17792 Val, EnumVal);
17793}
17794
17795Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
17796 SourceLocation IILoc) {
17797 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
17798 !getLangOpts().CPlusPlus)
17799 return SkipBodyInfo();
17800
17801 // We have an anonymous enum definition. Look up the first enumerator to
17802 // determine if we should merge the definition with an existing one and
17803 // skip the body.
17804 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
17805 forRedeclarationInCurContext());
17806 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
17807 if (!PrevECD)
17808 return SkipBodyInfo();
17809
17810 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
17811 NamedDecl *Hidden;
17812 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
17813 SkipBodyInfo Skip;
17814 Skip.Previous = Hidden;
17815 return Skip;
17816 }
17817
17818 return SkipBodyInfo();
17819}
17820
17821Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
17822 SourceLocation IdLoc, IdentifierInfo *Id,
17823 const ParsedAttributesView &Attrs,
17824 SourceLocation EqualLoc, Expr *Val) {
17825 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
17826 EnumConstantDecl *LastEnumConst =
17827 cast_or_null<EnumConstantDecl>(lastEnumConst);
17828
17829 // The scope passed in may not be a decl scope. Zip up the scope tree until
17830 // we find one that is.
17831 S = getNonFieldDeclScope(S);
17832
17833 // Verify that there isn't already something declared with this name in this
17834 // scope.
17835 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
17836 LookupName(R, S);
17837 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
17838
17839 if (PrevDecl && PrevDecl->isTemplateParameter()) {
17840 // Maybe we will complain about the shadowed template parameter.
17841 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
17842 // Just pretend that we didn't see the previous declaration.
17843 PrevDecl = nullptr;
17844 }
17845
17846 // C++ [class.mem]p15:
17847 // If T is the name of a class, then each of the following shall have a name
17848 // different from T:
17849 // - every enumerator of every member of class T that is an unscoped
17850 // enumerated type
17851 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
17852 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
17853 DeclarationNameInfo(Id, IdLoc));
17854
17855 EnumConstantDecl *New =
17856 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
17857 if (!New)
17858 return nullptr;
17859
17860 if (PrevDecl) {
17861 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
17862 // Check for other kinds of shadowing not already handled.
17863 CheckShadow(New, PrevDecl, R);
17864 }
17865
17866 // When in C++, we may get a TagDecl with the same name; in this case the
17867 // enum constant will 'hide' the tag.
17868 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&(((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
"Received TagDecl when not in C++!") ? static_cast<void>
(0) : __assert_fail ("(getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && \"Received TagDecl when not in C++!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 17869, __PRETTY_FUNCTION__))
17869 "Received TagDecl when not in C++!")(((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
"Received TagDecl when not in C++!") ? static_cast<void>
(0) : __assert_fail ("(getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && \"Received TagDecl when not in C++!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 17869, __PRETTY_FUNCTION__))
;
17870 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
17871 if (isa<EnumConstantDecl>(PrevDecl))
17872 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
17873 else
17874 Diag(IdLoc, diag::err_redefinition) << Id;
17875 notePreviousDefinition(PrevDecl, IdLoc);
17876 return nullptr;
17877 }
17878 }
17879
17880 // Process attributes.
17881 ProcessDeclAttributeList(S, New, Attrs);
17882 AddPragmaAttributes(S, New);
17883
17884 // Register this decl in the current scope stack.
17885 New->setAccess(TheEnumDecl->getAccess());
17886 PushOnScopeChains(New, S);
17887
17888 ActOnDocumentableDecl(New);
17889
17890 return New;
17891}
17892
17893// Returns true when the enum initial expression does not trigger the
17894// duplicate enum warning. A few common cases are exempted as follows:
17895// Element2 = Element1
17896// Element2 = Element1 + 1
17897// Element2 = Element1 - 1
17898// Where Element2 and Element1 are from the same enum.
17899static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
17900 Expr *InitExpr = ECD->getInitExpr();
17901 if (!InitExpr)
17902 return true;
17903 InitExpr = InitExpr->IgnoreImpCasts();
17904
17905 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
17906 if (!BO->isAdditiveOp())
17907 return true;
17908 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
17909 if (!IL)
17910 return true;
17911 if (IL->getValue() != 1)
17912 return true;
17913
17914 InitExpr = BO->getLHS();
17915 }
17916
17917 // This checks if the elements are from the same enum.
17918 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
17919 if (!DRE)
17920 return true;
17921
17922 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
17923 if (!EnumConstant)
17924 return true;
17925
17926 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
17927 Enum)
17928 return true;
17929
17930 return false;
17931}
17932
17933// Emits a warning when an element is implicitly set a value that
17934// a previous element has already been set to.
17935static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
17936 EnumDecl *Enum, QualType EnumType) {
17937 // Avoid anonymous enums
17938 if (!Enum->getIdentifier())
17939 return;
17940
17941 // Only check for small enums.
17942 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
17943 return;
17944
17945 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
17946 return;
17947
17948 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
17949 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
17950
17951 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
17952
17953 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
17954 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
17955
17956 // Use int64_t as a key to avoid needing special handling for map keys.
17957 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
17958 llvm::APSInt Val = D->getInitVal();
17959 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
17960 };
17961
17962 DuplicatesVector DupVector;
17963 ValueToVectorMap EnumMap;
17964
17965 // Populate the EnumMap with all values represented by enum constants without
17966 // an initializer.
17967 for (auto *Element : Elements) {
17968 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
17969
17970 // Null EnumConstantDecl means a previous diagnostic has been emitted for
17971 // this constant. Skip this enum since it may be ill-formed.
17972 if (!ECD) {
17973 return;
17974 }
17975
17976 // Constants with initalizers are handled in the next loop.
17977 if (ECD->getInitExpr())
17978 continue;
17979
17980 // Duplicate values are handled in the next loop.
17981 EnumMap.insert({EnumConstantToKey(ECD), ECD});
17982 }
17983
17984 if (EnumMap.size() == 0)
17985 return;
17986
17987 // Create vectors for any values that has duplicates.
17988 for (auto *Element : Elements) {
17989 // The last loop returned if any constant was null.
17990 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
17991 if (!ValidDuplicateEnum(ECD, Enum))
17992 continue;
17993
17994 auto Iter = EnumMap.find(EnumConstantToKey(ECD));
17995 if (Iter == EnumMap.end())
17996 continue;
17997
17998 DeclOrVector& Entry = Iter->second;
17999 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
18000 // Ensure constants are different.
18001 if (D == ECD)
18002 continue;
18003
18004 // Create new vector and push values onto it.
18005 auto Vec = std::make_unique<ECDVector>();
18006 Vec->push_back(D);
18007 Vec->push_back(ECD);
18008
18009 // Update entry to point to the duplicates vector.
18010 Entry = Vec.get();
18011
18012 // Store the vector somewhere we can consult later for quick emission of
18013 // diagnostics.
18014 DupVector.emplace_back(std::move(Vec));
18015 continue;
18016 }
18017
18018 ECDVector *Vec = Entry.get<ECDVector*>();
18019 // Make sure constants are not added more than once.
18020 if (*Vec->begin() == ECD)
18021 continue;
18022
18023 Vec->push_back(ECD);
18024 }
18025
18026 // Emit diagnostics.
18027 for (const auto &Vec : DupVector) {
18028 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.")((Vec->size() > 1 && "ECDVector should have at least 2 elements."
) ? static_cast<void> (0) : __assert_fail ("Vec->size() > 1 && \"ECDVector should have at least 2 elements.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 18028, __PRETTY_FUNCTION__))
;
18029
18030 // Emit warning for one enum constant.
18031 auto *FirstECD = Vec->front();
18032 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
18033 << FirstECD << FirstECD->getInitVal().toString(10)
18034 << FirstECD->getSourceRange();
18035
18036 // Emit one note for each of the remaining enum constants with
18037 // the same value.
18038 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
18039 S.Diag(ECD->getLocation(), diag::note_duplicate_element)
18040 << ECD << ECD->getInitVal().toString(10)
18041 << ECD->getSourceRange();
18042 }
18043}
18044
18045bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
18046 bool AllowMask) const {
18047 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum")((ED->isClosedFlag() && "looking for value in non-flag or open enum"
) ? static_cast<void> (0) : __assert_fail ("ED->isClosedFlag() && \"looking for value in non-flag or open enum\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 18047, __PRETTY_FUNCTION__))
;
18048 assert(ED->isCompleteDefinition() && "expected enum definition")((ED->isCompleteDefinition() && "expected enum definition"
) ? static_cast<void> (0) : __assert_fail ("ED->isCompleteDefinition() && \"expected enum definition\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 18048, __PRETTY_FUNCTION__))
;
18049
18050 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
18051 llvm::APInt &FlagBits = R.first->second;
18052
18053 if (R.second) {
18054 for (auto *E : ED->enumerators()) {
18055 const auto &EVal = E->getInitVal();
18056 // Only single-bit enumerators introduce new flag values.
18057 if (EVal.isPowerOf2())
18058 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
18059 }
18060 }
18061
18062 // A value is in a flag enum if either its bits are a subset of the enum's
18063 // flag bits (the first condition) or we are allowing masks and the same is
18064 // true of its complement (the second condition). When masks are allowed, we
18065 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
18066 //
18067 // While it's true that any value could be used as a mask, the assumption is
18068 // that a mask will have all of the insignificant bits set. Anything else is
18069 // likely a logic error.
18070 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
18071 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
18072}
18073
18074void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
18075 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
18076 const ParsedAttributesView &Attrs) {
18077 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
18078 QualType EnumType = Context.getTypeDeclType(Enum);
18079
18080 ProcessDeclAttributeList(S, Enum, Attrs);
18081
18082 if (Enum->isDependentType()) {
18083 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18084 EnumConstantDecl *ECD =
18085 cast_or_null<EnumConstantDecl>(Elements[i]);
18086 if (!ECD) continue;
18087
18088 ECD->setType(EnumType);
18089 }
18090
18091 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
18092 return;
18093 }
18094
18095 // TODO: If the result value doesn't fit in an int, it must be a long or long
18096 // long value. ISO C does not support this, but GCC does as an extension,
18097 // emit a warning.
18098 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18099 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
18100 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
18101
18102 // Verify that all the values are okay, compute the size of the values, and
18103 // reverse the list.
18104 unsigned NumNegativeBits = 0;
18105 unsigned NumPositiveBits = 0;
18106
18107 // Keep track of whether all elements have type int.
18108 bool AllElementsInt = true;
18109
18110 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18111 EnumConstantDecl *ECD =
18112 cast_or_null<EnumConstantDecl>(Elements[i]);
18113 if (!ECD) continue; // Already issued a diagnostic.
18114
18115 const llvm::APSInt &InitVal = ECD->getInitVal();
18116
18117 // Keep track of the size of positive and negative values.
18118 if (InitVal.isUnsigned() || InitVal.isNonNegative())
18119 NumPositiveBits = std::max(NumPositiveBits,
18120 (unsigned)InitVal.getActiveBits());
18121 else
18122 NumNegativeBits = std::max(NumNegativeBits,
18123 (unsigned)InitVal.getMinSignedBits());
18124
18125 // Keep track of whether every enum element has type int (very common).
18126 if (AllElementsInt)
18127 AllElementsInt = ECD->getType() == Context.IntTy;
18128 }
18129
18130 // Figure out the type that should be used for this enum.
18131 QualType BestType;
18132 unsigned BestWidth;
18133
18134 // C++0x N3000 [conv.prom]p3:
18135 // An rvalue of an unscoped enumeration type whose underlying
18136 // type is not fixed can be converted to an rvalue of the first
18137 // of the following types that can represent all the values of
18138 // the enumeration: int, unsigned int, long int, unsigned long
18139 // int, long long int, or unsigned long long int.
18140 // C99 6.4.4.3p2:
18141 // An identifier declared as an enumeration constant has type int.
18142 // The C99 rule is modified by a gcc extension
18143 QualType BestPromotionType;
18144
18145 bool Packed = Enum->hasAttr<PackedAttr>();
18146 // -fshort-enums is the equivalent to specifying the packed attribute on all
18147 // enum definitions.
18148 if (LangOpts.ShortEnums)
18149 Packed = true;
18150
18151 // If the enum already has a type because it is fixed or dictated by the
18152 // target, promote that type instead of analyzing the enumerators.
18153 if (Enum->isComplete()) {
18154 BestType = Enum->getIntegerType();
18155 if (BestType->isPromotableIntegerType())
18156 BestPromotionType = Context.getPromotedIntegerType(BestType);
18157 else
18158 BestPromotionType = BestType;
18159
18160 BestWidth = Context.getIntWidth(BestType);
18161 }
18162 else if (NumNegativeBits) {
18163 // If there is a negative value, figure out the smallest integer type (of
18164 // int/long/longlong) that fits.
18165 // If it's packed, check also if it fits a char or a short.
18166 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
18167 BestType = Context.SignedCharTy;
18168 BestWidth = CharWidth;
18169 } else if (Packed && NumNegativeBits <= ShortWidth &&
18170 NumPositiveBits < ShortWidth) {
18171 BestType = Context.ShortTy;
18172 BestWidth = ShortWidth;
18173 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
18174 BestType = Context.IntTy;
18175 BestWidth = IntWidth;
18176 } else {
18177 BestWidth = Context.getTargetInfo().getLongWidth();
18178
18179 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
18180 BestType = Context.LongTy;
18181 } else {
18182 BestWidth = Context.getTargetInfo().getLongLongWidth();
18183
18184 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
18185 Diag(Enum->getLocation(), diag::ext_enum_too_large);
18186 BestType = Context.LongLongTy;
18187 }
18188 }
18189 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
18190 } else {
18191 // If there is no negative value, figure out the smallest type that fits
18192 // all of the enumerator values.
18193 // If it's packed, check also if it fits a char or a short.
18194 if (Packed && NumPositiveBits <= CharWidth) {
18195 BestType = Context.UnsignedCharTy;
18196 BestPromotionType = Context.IntTy;
18197 BestWidth = CharWidth;
18198 } else if (Packed && NumPositiveBits <= ShortWidth) {
18199 BestType = Context.UnsignedShortTy;
18200 BestPromotionType = Context.IntTy;
18201 BestWidth = ShortWidth;
18202 } else if (NumPositiveBits <= IntWidth) {
18203 BestType = Context.UnsignedIntTy;
18204 BestWidth = IntWidth;
18205 BestPromotionType
18206 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18207 ? Context.UnsignedIntTy : Context.IntTy;
18208 } else if (NumPositiveBits <=
18209 (BestWidth = Context.getTargetInfo().getLongWidth())) {
18210 BestType = Context.UnsignedLongTy;
18211 BestPromotionType
18212 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18213 ? Context.UnsignedLongTy : Context.LongTy;
18214 } else {
18215 BestWidth = Context.getTargetInfo().getLongLongWidth();
18216 assert(NumPositiveBits <= BestWidth &&((NumPositiveBits <= BestWidth && "How could an initializer get larger than ULL?"
) ? static_cast<void> (0) : __assert_fail ("NumPositiveBits <= BestWidth && \"How could an initializer get larger than ULL?\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 18217, __PRETTY_FUNCTION__))
18217 "How could an initializer get larger than ULL?")((NumPositiveBits <= BestWidth && "How could an initializer get larger than ULL?"
) ? static_cast<void> (0) : __assert_fail ("NumPositiveBits <= BestWidth && \"How could an initializer get larger than ULL?\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 18217, __PRETTY_FUNCTION__))
;
18218 BestType = Context.UnsignedLongLongTy;
18219 BestPromotionType
18220 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18221 ? Context.UnsignedLongLongTy : Context.LongLongTy;
18222 }
18223 }
18224
18225 // Loop over all of the enumerator constants, changing their types to match
18226 // the type of the enum if needed.
18227 for (auto *D : Elements) {
18228 auto *ECD = cast_or_null<EnumConstantDecl>(D);
18229 if (!ECD) continue; // Already issued a diagnostic.
18230
18231 // Standard C says the enumerators have int type, but we allow, as an
18232 // extension, the enumerators to be larger than int size. If each
18233 // enumerator value fits in an int, type it as an int, otherwise type it the
18234 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
18235 // that X has type 'int', not 'unsigned'.
18236
18237 // Determine whether the value fits into an int.
18238 llvm::APSInt InitVal = ECD->getInitVal();
18239
18240 // If it fits into an integer type, force it. Otherwise force it to match
18241 // the enum decl type.
18242 QualType NewTy;
18243 unsigned NewWidth;
18244 bool NewSign;
18245 if (!getLangOpts().CPlusPlus &&
18246 !Enum->isFixed() &&
18247 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
18248 NewTy = Context.IntTy;
18249 NewWidth = IntWidth;
18250 NewSign = true;
18251 } else if (ECD->getType() == BestType) {
18252 // Already the right type!
18253 if (getLangOpts().CPlusPlus)
18254 // C++ [dcl.enum]p4: Following the closing brace of an
18255 // enum-specifier, each enumerator has the type of its
18256 // enumeration.
18257 ECD->setType(EnumType);
18258 continue;
18259 } else {
18260 NewTy = BestType;
18261 NewWidth = BestWidth;
18262 NewSign = BestType->isSignedIntegerOrEnumerationType();
18263 }
18264
18265 // Adjust the APSInt value.
18266 InitVal = InitVal.extOrTrunc(NewWidth);
18267 InitVal.setIsSigned(NewSign);
18268 ECD->setInitVal(InitVal);
18269
18270 // Adjust the Expr initializer and type.
18271 if (ECD->getInitExpr() &&
18272 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
18273 ECD->setInitExpr(ImplicitCastExpr::Create(
18274 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
18275 /*base paths*/ nullptr, VK_RValue, FPOptionsOverride()));
18276 if (getLangOpts().CPlusPlus)
18277 // C++ [dcl.enum]p4: Following the closing brace of an
18278 // enum-specifier, each enumerator has the type of its
18279 // enumeration.
18280 ECD->setType(EnumType);
18281 else
18282 ECD->setType(NewTy);
18283 }
18284
18285 Enum->completeDefinition(BestType, BestPromotionType,
18286 NumPositiveBits, NumNegativeBits);
18287
18288 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
18289
18290 if (Enum->isClosedFlag()) {
18291 for (Decl *D : Elements) {
18292 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
18293 if (!ECD) continue; // Already issued a diagnostic.
18294
18295 llvm::APSInt InitVal = ECD->getInitVal();
18296 if (InitVal != 0 && !InitVal.isPowerOf2() &&
18297 !IsValueInFlagEnum(Enum, InitVal, true))
18298 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
18299 << ECD << Enum;
18300 }
18301 }
18302
18303 // Now that the enum type is defined, ensure it's not been underaligned.
18304 if (Enum->hasAttrs())
18305 CheckAlignasUnderalignment(Enum);
18306}
18307
18308Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
18309 SourceLocation StartLoc,
18310 SourceLocation EndLoc) {
18311 StringLiteral *AsmString = cast<StringLiteral>(expr);
18312
18313 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
18314 AsmString, StartLoc,
18315 EndLoc);
18316 CurContext->addDecl(New);
18317 return New;
18318}
18319
18320void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
18321 IdentifierInfo* AliasName,
18322 SourceLocation PragmaLoc,
18323 SourceLocation NameLoc,
18324 SourceLocation AliasNameLoc) {
18325 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
18326 LookupOrdinaryName);
18327 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
18328 AttributeCommonInfo::AS_Pragma);
18329 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
18330 Context, AliasName->getName(), /*LiteralLabel=*/true, Info);
18331
18332 // If a declaration that:
18333 // 1) declares a function or a variable
18334 // 2) has external linkage
18335 // already exists, add a label attribute to it.
18336 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18337 if (isDeclExternC(PrevDecl))
18338 PrevDecl->addAttr(Attr);
18339 else
18340 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
18341 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
18342 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
18343 } else
18344 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
18345}
18346
18347void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
18348 SourceLocation PragmaLoc,
18349 SourceLocation NameLoc) {
18350 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
18351
18352 if (PrevDecl) {
18353 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
18354 } else {
18355 (void)WeakUndeclaredIdentifiers.insert(
18356 std::pair<IdentifierInfo*,WeakInfo>
18357 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
18358 }
18359}
18360
18361void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
18362 IdentifierInfo* AliasName,
18363 SourceLocation PragmaLoc,
18364 SourceLocation NameLoc,
18365 SourceLocation AliasNameLoc) {
18366 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
18367 LookupOrdinaryName);
18368 WeakInfo W = WeakInfo(Name, NameLoc);
18369
18370 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18371 if (!PrevDecl->hasAttr<AliasAttr>())
18372 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
18373 DeclApplyPragmaWeak(TUScope, ND, W);
18374 } else {
18375 (void)WeakUndeclaredIdentifiers.insert(
18376 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
18377 }
18378}
18379
18380Decl *Sema::getObjCDeclContext() const {
18381 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
18382}
18383
18384Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
18385 bool Final) {
18386 assert(FD && "Expected non-null FunctionDecl")((FD && "Expected non-null FunctionDecl") ? static_cast
<void> (0) : __assert_fail ("FD && \"Expected non-null FunctionDecl\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaDecl.cpp"
, 18386, __PRETTY_FUNCTION__))
;
18387
18388 // SYCL functions can be template, so we check if they have appropriate
18389 // attribute prior to checking if it is a template.
18390 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
18391 return FunctionEmissionStatus::Emitted;
18392
18393 // Templates are emitted when they're instantiated.
18394 if (FD->isDependentContext())
18395 return FunctionEmissionStatus::TemplateDiscarded;
18396
18397 // Check whether this function is an externally visible definition.
18398 auto IsEmittedForExternalSymbol = [this, FD]() {
18399 // We have to check the GVA linkage of the function's *definition* -- if we
18400 // only have a declaration, we don't know whether or not the function will
18401 // be emitted, because (say) the definition could include "inline".
18402 FunctionDecl *Def = FD->getDefinition();
18403
18404 return Def && !isDiscardableGVALinkage(
18405 getASTContext().GetGVALinkageForFunction(Def));
18406 };
18407
18408 if (LangOpts.OpenMPIsDevice) {
18409 // In OpenMP device mode we will not emit host only functions, or functions
18410 // we don't need due to their linkage.
18411 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18412 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18413 // DevTy may be changed later by
18414 // #pragma omp declare target to(*) device_type(*).
18415 // Therefore DevTyhaving no value does not imply host. The emission status
18416 // will be checked again at the end of compilation unit with Final = true.
18417 if (DevTy.hasValue())
18418 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
18419 return FunctionEmissionStatus::OMPDiscarded;
18420 // If we have an explicit value for the device type, or we are in a target
18421 // declare context, we need to emit all extern and used symbols.
18422 if (isInOpenMPDeclareTargetContext() || DevTy.hasValue())
18423 if (IsEmittedForExternalSymbol())
18424 return FunctionEmissionStatus::Emitted;
18425 // Device mode only emits what it must, if it wasn't tagged yet and needed,
18426 // we'll omit it.
18427 if (Final)
18428 return FunctionEmissionStatus::OMPDiscarded;
18429 } else if (LangOpts.OpenMP > 45) {
18430 // In OpenMP host compilation prior to 5.0 everything was an emitted host
18431 // function. In 5.0, no_host was introduced which might cause a function to
18432 // be ommitted.
18433 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18434 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18435 if (DevTy.hasValue())
18436 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
18437 return FunctionEmissionStatus::OMPDiscarded;
18438 }
18439
18440 if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
18441 return FunctionEmissionStatus::Emitted;
18442
18443 if (LangOpts.CUDA) {
18444 // When compiling for device, host functions are never emitted. Similarly,
18445 // when compiling for host, device and global functions are never emitted.
18446 // (Technically, we do emit a host-side stub for global functions, but this
18447 // doesn't count for our purposes here.)
18448 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
18449 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
18450 return FunctionEmissionStatus::CUDADiscarded;
18451 if (!LangOpts.CUDAIsDevice &&
18452 (T == Sema::CFT_Device || T == Sema::CFT_Global))
18453 return FunctionEmissionStatus::CUDADiscarded;
18454
18455 if (IsEmittedForExternalSymbol())
18456 return FunctionEmissionStatus::Emitted;
18457 }
18458
18459 // Otherwise, the function is known-emitted if it's in our set of
18460 // known-emitted functions.
18461 return FunctionEmissionStatus::Unknown;
18462}
18463
18464bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
18465 // Host-side references to a __global__ function refer to the stub, so the
18466 // function itself is never emitted and therefore should not be marked.
18467 // If we have host fn calls kernel fn calls host+device, the HD function
18468 // does not get instantiated on the host. We model this by omitting at the
18469 // call to the kernel from the callgraph. This ensures that, when compiling
18470 // for host, only HD functions actually called from the host get marked as
18471 // known-emitted.
18472 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
18473 IdentifyCUDATarget(Callee) == CFT_Global;
18474}

/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Sema/DeclSpec.h

1//===--- DeclSpec.h - Parsed declaration specifiers -------------*- 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/// \file
10/// This file defines the classes used to store parsed information about
11/// declaration-specifiers and declarators.
12///
13/// \verbatim
14/// static const int volatile x, *y, *(*(*z)[10])(const void *x);
15/// ------------------------- - -- ---------------------------
16/// declaration-specifiers \ | /
17/// declarators
18/// \endverbatim
19///
20//===----------------------------------------------------------------------===//
21
22#ifndef LLVM_CLANG_SEMA_DECLSPEC_H
23#define LLVM_CLANG_SEMA_DECLSPEC_H
24
25#include "clang/AST/DeclCXX.h"
26#include "clang/AST/DeclObjCCommon.h"
27#include "clang/AST/NestedNameSpecifier.h"
28#include "clang/Basic/ExceptionSpecificationType.h"
29#include "clang/Basic/Lambda.h"
30#include "clang/Basic/OperatorKinds.h"
31#include "clang/Basic/Specifiers.h"
32#include "clang/Lex/Token.h"
33#include "clang/Sema/Ownership.h"
34#include "clang/Sema/ParsedAttr.h"
35#include "llvm/ADT/SmallVector.h"
36#include "llvm/Support/Compiler.h"
37#include "llvm/Support/ErrorHandling.h"
38
39namespace clang {
40 class ASTContext;
41 class CXXRecordDecl;
42 class TypeLoc;
43 class LangOptions;
44 class IdentifierInfo;
45 class NamespaceAliasDecl;
46 class NamespaceDecl;
47 class ObjCDeclSpec;
48 class Sema;
49 class Declarator;
50 struct TemplateIdAnnotation;
51
52/// Represents a C++ nested-name-specifier or a global scope specifier.
53///
54/// These can be in 3 states:
55/// 1) Not present, identified by isEmpty()
56/// 2) Present, identified by isNotEmpty()
57/// 2.a) Valid, identified by isValid()
58/// 2.b) Invalid, identified by isInvalid().
59///
60/// isSet() is deprecated because it mostly corresponded to "valid" but was
61/// often used as if it meant "present".
62///
63/// The actual scope is described by getScopeRep().
64class CXXScopeSpec {
65 SourceRange Range;
66 NestedNameSpecifierLocBuilder Builder;
67
68public:
69 SourceRange getRange() const { return Range; }
70 void setRange(SourceRange R) { Range = R; }
71 void setBeginLoc(SourceLocation Loc) { Range.setBegin(Loc); }
72 void setEndLoc(SourceLocation Loc) { Range.setEnd(Loc); }
73 SourceLocation getBeginLoc() const { return Range.getBegin(); }
74 SourceLocation getEndLoc() const { return Range.getEnd(); }
75
76 /// Retrieve the representation of the nested-name-specifier.
77 NestedNameSpecifier *getScopeRep() const {
78 return Builder.getRepresentation();
79 }
80
81 /// Extend the current nested-name-specifier by another
82 /// nested-name-specifier component of the form 'type::'.
83 ///
84 /// \param Context The AST context in which this nested-name-specifier
85 /// resides.
86 ///
87 /// \param TemplateKWLoc The location of the 'template' keyword, if present.
88 ///
89 /// \param TL The TypeLoc that describes the type preceding the '::'.
90 ///
91 /// \param ColonColonLoc The location of the trailing '::'.
92 void Extend(ASTContext &Context, SourceLocation TemplateKWLoc, TypeLoc TL,
93 SourceLocation ColonColonLoc);
94
95 /// Extend the current nested-name-specifier by another
96 /// nested-name-specifier component of the form 'identifier::'.
97 ///
98 /// \param Context The AST context in which this nested-name-specifier
99 /// resides.
100 ///
101 /// \param Identifier The identifier.
102 ///
103 /// \param IdentifierLoc The location of the identifier.
104 ///
105 /// \param ColonColonLoc The location of the trailing '::'.
106 void Extend(ASTContext &Context, IdentifierInfo *Identifier,
107 SourceLocation IdentifierLoc, SourceLocation ColonColonLoc);
108
109 /// Extend the current nested-name-specifier by another
110 /// nested-name-specifier component of the form 'namespace::'.
111 ///
112 /// \param Context The AST context in which this nested-name-specifier
113 /// resides.
114 ///
115 /// \param Namespace The namespace.
116 ///
117 /// \param NamespaceLoc The location of the namespace name.
118 ///
119 /// \param ColonColonLoc The location of the trailing '::'.
120 void Extend(ASTContext &Context, NamespaceDecl *Namespace,
121 SourceLocation NamespaceLoc, SourceLocation ColonColonLoc);
122
123 /// Extend the current nested-name-specifier by another
124 /// nested-name-specifier component of the form 'namespace-alias::'.
125 ///
126 /// \param Context The AST context in which this nested-name-specifier
127 /// resides.
128 ///
129 /// \param Alias The namespace alias.
130 ///
131 /// \param AliasLoc The location of the namespace alias
132 /// name.
133 ///
134 /// \param ColonColonLoc The location of the trailing '::'.
135 void Extend(ASTContext &Context, NamespaceAliasDecl *Alias,
136 SourceLocation AliasLoc, SourceLocation ColonColonLoc);
137
138 /// Turn this (empty) nested-name-specifier into the global
139 /// nested-name-specifier '::'.
140 void MakeGlobal(ASTContext &Context, SourceLocation ColonColonLoc);
141
142 /// Turns this (empty) nested-name-specifier into '__super'
143 /// nested-name-specifier.
144 ///
145 /// \param Context The AST context in which this nested-name-specifier
146 /// resides.
147 ///
148 /// \param RD The declaration of the class in which nested-name-specifier
149 /// appeared.
150 ///
151 /// \param SuperLoc The location of the '__super' keyword.
152 /// name.
153 ///
154 /// \param ColonColonLoc The location of the trailing '::'.
155 void MakeSuper(ASTContext &Context, CXXRecordDecl *RD,
156 SourceLocation SuperLoc, SourceLocation ColonColonLoc);
157
158 /// Make a new nested-name-specifier from incomplete source-location
159 /// information.
160 ///
161 /// FIXME: This routine should be used very, very rarely, in cases where we
162 /// need to synthesize a nested-name-specifier. Most code should instead use
163 /// \c Adopt() with a proper \c NestedNameSpecifierLoc.
164 void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier,
165 SourceRange R);
166
167 /// Adopt an existing nested-name-specifier (with source-range
168 /// information).
169 void Adopt(NestedNameSpecifierLoc Other);
170
171 /// Retrieve a nested-name-specifier with location information, copied
172 /// into the given AST context.
173 ///
174 /// \param Context The context into which this nested-name-specifier will be
175 /// copied.
176 NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const;
177
178 /// Retrieve the location of the name in the last qualifier
179 /// in this nested name specifier.
180 ///
181 /// For example, the location of \c bar
182 /// in
183 /// \verbatim
184 /// \::foo::bar<0>::
185 /// ^~~
186 /// \endverbatim
187 SourceLocation getLastQualifierNameLoc() const;
188
189 /// No scope specifier.
190 bool isEmpty() const { return Range.isInvalid() && getScopeRep() == nullptr; }
191 /// A scope specifier is present, but may be valid or invalid.
192 bool isNotEmpty() const { return !isEmpty(); }
193
194 /// An error occurred during parsing of the scope specifier.
195 bool isInvalid() const { return Range.isValid() && getScopeRep() == nullptr; }
196 /// A scope specifier is present, and it refers to a real scope.
197 bool isValid() const { return getScopeRep() != nullptr; }
198
199 /// Indicate that this nested-name-specifier is invalid.
200 void SetInvalid(SourceRange R) {
201 assert(R.isValid() && "Must have a valid source range")((R.isValid() && "Must have a valid source range") ? static_cast
<void> (0) : __assert_fail ("R.isValid() && \"Must have a valid source range\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Sema/DeclSpec.h"
, 201, __PRETTY_FUNCTION__))
;
202 if (Range.getBegin().isInvalid())
203 Range.setBegin(R.getBegin());
204 Range.setEnd(R.getEnd());
205 Builder.Clear();
206 }
207
208 /// Deprecated. Some call sites intend isNotEmpty() while others intend
209 /// isValid().
210 bool isSet() const { return getScopeRep() != nullptr; }
211
212 void clear() {
213 Range = SourceRange();
214 Builder.Clear();
215 }
216
217 /// Retrieve the data associated with the source-location information.
218 char *location_data() const { return Builder.getBuffer().first; }
219
220 /// Retrieve the size of the data associated with source-location
221 /// information.
222 unsigned location_size() const { return Builder.getBuffer().second; }
223};
224
225/// Captures information about "declaration specifiers".
226///
227/// "Declaration specifiers" encompasses storage-class-specifiers,
228/// type-specifiers, type-qualifiers, and function-specifiers.
229class DeclSpec {
230public:
231 /// storage-class-specifier
232 /// \note The order of these enumerators is important for diagnostics.
233 enum SCS {
234 SCS_unspecified = 0,
235 SCS_typedef,
236 SCS_extern,
237 SCS_static,
238 SCS_auto,
239 SCS_register,
240 SCS_private_extern,
241 SCS_mutable
242 };
243
244 // Import thread storage class specifier enumeration and constants.
245 // These can be combined with SCS_extern and SCS_static.
246 typedef ThreadStorageClassSpecifier TSCS;
247 static const TSCS TSCS_unspecified = clang::TSCS_unspecified;
248 static const TSCS TSCS___thread = clang::TSCS___thread;
249 static const TSCS TSCS_thread_local = clang::TSCS_thread_local;
250 static const TSCS TSCS__Thread_local = clang::TSCS__Thread_local;
251
252 enum TSC {
253 TSC_unspecified,
254 TSC_imaginary,
255 TSC_complex
256 };
257
258 // Import type specifier type enumeration and constants.
259 typedef TypeSpecifierType TST;
260 static const TST TST_unspecified = clang::TST_unspecified;
261 static const TST TST_void = clang::TST_void;
262 static const TST TST_char = clang::TST_char;
263 static const TST TST_wchar = clang::TST_wchar;
264 static const TST TST_char8 = clang::TST_char8;
265 static const TST TST_char16 = clang::TST_char16;
266 static const TST TST_char32 = clang::TST_char32;
267 static const TST TST_int = clang::TST_int;
268 static const TST TST_int128 = clang::TST_int128;
269 static const TST TST_extint = clang::TST_extint;
270 static const TST TST_half = clang::TST_half;
271 static const TST TST_BFloat16 = clang::TST_BFloat16;
272 static const TST TST_float = clang::TST_float;
273 static const TST TST_double = clang::TST_double;
274 static const TST TST_float16 = clang::TST_Float16;
275 static const TST TST_accum = clang::TST_Accum;
276 static const TST TST_fract = clang::TST_Fract;
277 static const TST TST_float128 = clang::TST_float128;
278 static const TST TST_bool = clang::TST_bool;
279 static const TST TST_decimal32 = clang::TST_decimal32;
280 static const TST TST_decimal64 = clang::TST_decimal64;
281 static const TST TST_decimal128 = clang::TST_decimal128;
282 static const TST TST_enum = clang::TST_enum;
283 static const TST TST_union = clang::TST_union;
284 static const TST TST_struct = clang::TST_struct;
285 static const TST TST_interface = clang::TST_interface;
286 static const TST TST_class = clang::TST_class;
287 static const TST TST_typename = clang::TST_typename;
288 static const TST TST_typeofType = clang::TST_typeofType;
289 static const TST TST_typeofExpr = clang::TST_typeofExpr;
290 static const TST TST_decltype = clang::TST_decltype;
291 static const TST TST_decltype_auto = clang::TST_decltype_auto;
292 static const TST TST_underlyingType = clang::TST_underlyingType;
293 static const TST TST_auto = clang::TST_auto;
294 static const TST TST_auto_type = clang::TST_auto_type;
295 static const TST TST_unknown_anytype = clang::TST_unknown_anytype;
296 static const TST TST_atomic = clang::TST_atomic;
297#define GENERIC_IMAGE_TYPE(ImgType, Id) \
298 static const TST TST_##ImgType##_t = clang::TST_##ImgType##_t;
299#include "clang/Basic/OpenCLImageTypes.def"
300 static const TST TST_error = clang::TST_error;
301
302 // type-qualifiers
303 enum TQ { // NOTE: These flags must be kept in sync with Qualifiers::TQ.
304 TQ_unspecified = 0,
305 TQ_const = 1,
306 TQ_restrict = 2,
307 TQ_volatile = 4,
308 TQ_unaligned = 8,
309 // This has no corresponding Qualifiers::TQ value, because it's not treated
310 // as a qualifier in our type system.
311 TQ_atomic = 16
312 };
313
314 /// ParsedSpecifiers - Flags to query which specifiers were applied. This is
315 /// returned by getParsedSpecifiers.
316 enum ParsedSpecifiers {
317 PQ_None = 0,
318 PQ_StorageClassSpecifier = 1,
319 PQ_TypeSpecifier = 2,
320 PQ_TypeQualifier = 4,
321 PQ_FunctionSpecifier = 8
322 // FIXME: Attributes should be included here.
323 };
324
325private:
326 // storage-class-specifier
327 /*SCS*/unsigned StorageClassSpec : 3;
328 /*TSCS*/unsigned ThreadStorageClassSpec : 2;
329 unsigned SCS_extern_in_linkage_spec : 1;
330
331 // type-specifier
332 /*TypeSpecifierWidth*/ unsigned TypeSpecWidth : 2;
333 /*TSC*/unsigned TypeSpecComplex : 2;
334 /*TSS*/unsigned TypeSpecSign : 2;
335 /*TST*/unsigned TypeSpecType : 6;
336 unsigned TypeAltiVecVector : 1;
337 unsigned TypeAltiVecPixel : 1;
338 unsigned TypeAltiVecBool : 1;
339 unsigned TypeSpecOwned : 1;
340 unsigned TypeSpecPipe : 1;
341 unsigned TypeSpecSat : 1;
342 unsigned ConstrainedAuto : 1;
343
344 // type-qualifiers
345 unsigned TypeQualifiers : 5; // Bitwise OR of TQ.
346
347 // function-specifier
348 unsigned FS_inline_specified : 1;
349 unsigned FS_forceinline_specified: 1;
350 unsigned FS_virtual_specified : 1;
351 unsigned FS_noreturn_specified : 1;
352
353 // friend-specifier
354 unsigned Friend_specified : 1;
355
356 // constexpr-specifier
357 unsigned ConstexprSpecifier : 2;
358
359 union {
360 UnionParsedType TypeRep;
361 Decl *DeclRep;
362 Expr *ExprRep;
363 TemplateIdAnnotation *TemplateIdRep;
364 };
365
366 /// ExplicitSpecifier - Store information about explicit spicifer.
367 ExplicitSpecifier FS_explicit_specifier;
368
369 // attributes.
370 ParsedAttributes Attrs;
371
372 // Scope specifier for the type spec, if applicable.
373 CXXScopeSpec TypeScope;
374
375 // SourceLocation info. These are null if the item wasn't specified or if
376 // the setting was synthesized.
377 SourceRange Range;
378
379 SourceLocation StorageClassSpecLoc, ThreadStorageClassSpecLoc;
380 SourceRange TSWRange;
381 SourceLocation TSCLoc, TSSLoc, TSTLoc, AltiVecLoc, TSSatLoc;
382 /// TSTNameLoc - If TypeSpecType is any of class, enum, struct, union,
383 /// typename, then this is the location of the named type (if present);
384 /// otherwise, it is the same as TSTLoc. Hence, the pair TSTLoc and
385 /// TSTNameLoc provides source range info for tag types.
386 SourceLocation TSTNameLoc;
387 SourceRange TypeofParensRange;
388 SourceLocation TQ_constLoc, TQ_restrictLoc, TQ_volatileLoc, TQ_atomicLoc,
389 TQ_unalignedLoc;
390 SourceLocation FS_inlineLoc, FS_virtualLoc, FS_explicitLoc, FS_noreturnLoc;
391 SourceLocation FS_explicitCloseParenLoc;
392 SourceLocation FS_forceinlineLoc;
393 SourceLocation FriendLoc, ModulePrivateLoc, ConstexprLoc;
394 SourceLocation TQ_pipeLoc;
395
396 WrittenBuiltinSpecs writtenBS;
397 void SaveWrittenBuiltinSpecs();
398
399 ObjCDeclSpec *ObjCQualifiers;
400
401 static bool isTypeRep(TST T) {
402 return (T == TST_typename || T == TST_typeofType ||
403 T == TST_underlyingType || T == TST_atomic);
404 }
405 static bool isExprRep(TST T) {
406 return (T == TST_typeofExpr || T == TST_decltype || T == TST_extint);
407 }
408 static bool isTemplateIdRep(TST T) {
409 return (T == TST_auto || T == TST_decltype_auto);
410 }
411
412 DeclSpec(const DeclSpec &) = delete;
413 void operator=(const DeclSpec &) = delete;
414public:
415 static bool isDeclRep(TST T) {
416 return (T == TST_enum || T == TST_struct ||
417 T == TST_interface || T == TST_union ||
418 T == TST_class);
419 }
420
421 DeclSpec(AttributeFactory &attrFactory)
422 : StorageClassSpec(SCS_unspecified),
423 ThreadStorageClassSpec(TSCS_unspecified),
424 SCS_extern_in_linkage_spec(false),
425 TypeSpecWidth(static_cast<unsigned>(TypeSpecifierWidth::Unspecified)),
426 TypeSpecComplex(TSC_unspecified),
427 TypeSpecSign(static_cast<unsigned>(TypeSpecifierSign::Unspecified)),
428 TypeSpecType(TST_unspecified), TypeAltiVecVector(false),
429 TypeAltiVecPixel(false), TypeAltiVecBool(false), TypeSpecOwned(false),
430 TypeSpecPipe(false), TypeSpecSat(false), ConstrainedAuto(false),
431 TypeQualifiers(TQ_unspecified), FS_inline_specified(false),
432 FS_forceinline_specified(false), FS_virtual_specified(false),
433 FS_noreturn_specified(false), Friend_specified(false),
434 ConstexprSpecifier(
435 static_cast<unsigned>(ConstexprSpecKind::Unspecified)),
436 FS_explicit_specifier(), Attrs(attrFactory), writtenBS(),
437 ObjCQualifiers(nullptr) {}
438
439 // storage-class-specifier
440 SCS getStorageClassSpec() const { return (SCS)StorageClassSpec; }
441 TSCS getThreadStorageClassSpec() const {
442 return (TSCS)ThreadStorageClassSpec;
443 }
444 bool isExternInLinkageSpec() const { return SCS_extern_in_linkage_spec; }
445 void setExternInLinkageSpec(bool Value) {
446 SCS_extern_in_linkage_spec = Value;
447 }
448
449 SourceLocation getStorageClassSpecLoc() const { return StorageClassSpecLoc; }
450 SourceLocation getThreadStorageClassSpecLoc() const {
451 return ThreadStorageClassSpecLoc;
452 }
453
454 void ClearStorageClassSpecs() {
455 StorageClassSpec = DeclSpec::SCS_unspecified;
456 ThreadStorageClassSpec = DeclSpec::TSCS_unspecified;
457 SCS_extern_in_linkage_spec = false;
458 StorageClassSpecLoc = SourceLocation();
459 ThreadStorageClassSpecLoc = SourceLocation();
460 }
461
462 void ClearTypeSpecType() {
463 TypeSpecType = DeclSpec::TST_unspecified;
464 TypeSpecOwned = false;
465 TSTLoc = SourceLocation();
466 }
467
468 // type-specifier
469 TypeSpecifierWidth getTypeSpecWidth() const {
470 return static_cast<TypeSpecifierWidth>(TypeSpecWidth);
471 }
472 TSC getTypeSpecComplex() const { return (TSC)TypeSpecComplex; }
473 TypeSpecifierSign getTypeSpecSign() const {
474 return static_cast<TypeSpecifierSign>(TypeSpecSign);
475 }
476 TST getTypeSpecType() const { return (TST)TypeSpecType; }
477 bool isTypeAltiVecVector() const { return TypeAltiVecVector; }
478 bool isTypeAltiVecPixel() const { return TypeAltiVecPixel; }
479 bool isTypeAltiVecBool() const { return TypeAltiVecBool; }
480 bool isTypeSpecOwned() const { return TypeSpecOwned; }
481 bool isTypeRep() const { return isTypeRep((TST) TypeSpecType); }
482 bool isTypeSpecPipe() const { return TypeSpecPipe; }
483 bool isTypeSpecSat() const { return TypeSpecSat; }
484 bool isConstrainedAuto() const { return ConstrainedAuto; }
485
486 ParsedType getRepAsType() const {
487 assert(isTypeRep((TST) TypeSpecType) && "DeclSpec does not store a type")((isTypeRep((TST) TypeSpecType) && "DeclSpec does not store a type"
) ? static_cast<void> (0) : __assert_fail ("isTypeRep((TST) TypeSpecType) && \"DeclSpec does not store a type\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Sema/DeclSpec.h"
, 487, __PRETTY_FUNCTION__))
;
488 return TypeRep;
489 }
490 Decl *getRepAsDecl() const {
491 assert(isDeclRep((TST) TypeSpecType) && "DeclSpec does not store a decl")((isDeclRep((TST) TypeSpecType) && "DeclSpec does not store a decl"
) ? static_cast<void> (0) : __assert_fail ("isDeclRep((TST) TypeSpecType) && \"DeclSpec does not store a decl\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Sema/DeclSpec.h"
, 491, __PRETTY_FUNCTION__))
;
492 return DeclRep;
493 }
494 Expr *getRepAsExpr() const {
495 assert(isExprRep((TST) TypeSpecType) && "DeclSpec does not store an expr")((isExprRep((TST) TypeSpecType) && "DeclSpec does not store an expr"
) ? static_cast<void> (0) : __assert_fail ("isExprRep((TST) TypeSpecType) && \"DeclSpec does not store an expr\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Sema/DeclSpec.h"
, 495, __PRETTY_FUNCTION__))
;
496 return ExprRep;
497 }
498 TemplateIdAnnotation *getRepAsTemplateId() const {
499 assert(isTemplateIdRep((TST) TypeSpecType) &&((isTemplateIdRep((TST) TypeSpecType) && "DeclSpec does not store a template id"
) ? static_cast<void> (0) : __assert_fail ("isTemplateIdRep((TST) TypeSpecType) && \"DeclSpec does not store a template id\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Sema/DeclSpec.h"
, 500, __PRETTY_FUNCTION__))
500 "DeclSpec does not store a template id")((isTemplateIdRep((TST) TypeSpecType) && "DeclSpec does not store a template id"
) ? static_cast<void> (0) : __assert_fail ("isTemplateIdRep((TST) TypeSpecType) && \"DeclSpec does not store a template id\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Sema/DeclSpec.h"
, 500, __PRETTY_FUNCTION__))
;
501 return TemplateIdRep;
502 }
503 CXXScopeSpec &getTypeSpecScope() { return TypeScope; }
504 const CXXScopeSpec &getTypeSpecScope() const { return TypeScope; }
505
506 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) { return Range; }
507 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getBegin(); }
508 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getEnd(); }
509
510 SourceLocation getTypeSpecWidthLoc() const { return TSWRange.getBegin(); }
511 SourceRange getTypeSpecWidthRange() const { return TSWRange; }
512 SourceLocation getTypeSpecComplexLoc() const { return TSCLoc; }
513 SourceLocation getTypeSpecSignLoc() const { return TSSLoc; }
514 SourceLocation getTypeSpecTypeLoc() const { return TSTLoc; }
515 SourceLocation getAltiVecLoc() const { return AltiVecLoc; }
516 SourceLocation getTypeSpecSatLoc() const { return TSSatLoc; }
517
518 SourceLocation getTypeSpecTypeNameLoc() const {
519 assert(isDeclRep((TST) TypeSpecType) || TypeSpecType == TST_typename)((isDeclRep((TST) TypeSpecType) || TypeSpecType == TST_typename
) ? static_cast<void> (0) : __assert_fail ("isDeclRep((TST) TypeSpecType) || TypeSpecType == TST_typename"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Sema/DeclSpec.h"
, 519, __PRETTY_FUNCTION__))
;
520 return TSTNameLoc;
521 }
522
523 SourceRange getTypeofParensRange() const { return TypeofParensRange; }
524 void setTypeofParensRange(SourceRange range) { TypeofParensRange = range; }
525
526 bool hasAutoTypeSpec() const {
527 return (TypeSpecType == TST_auto || TypeSpecType == TST_auto_type ||
528 TypeSpecType == TST_decltype_auto);
529 }
530
531 bool hasTagDefinition() const;
532
533 /// Turn a type-specifier-type into a string like "_Bool" or "union".
534 static const char *getSpecifierName(DeclSpec::TST T,
535 const PrintingPolicy &Policy);
536 static const char *getSpecifierName(DeclSpec::TQ Q);
537 static const char *getSpecifierName(TypeSpecifierSign S);
538 static const char *getSpecifierName(DeclSpec::TSC C);
539 static const char *getSpecifierName(TypeSpecifierWidth W);
540 static const char *getSpecifierName(DeclSpec::SCS S);
541 static const char *getSpecifierName(DeclSpec::TSCS S);
542 static const char *getSpecifierName(ConstexprSpecKind C);
543
544 // type-qualifiers
545
546 /// getTypeQualifiers - Return a set of TQs.
547 unsigned getTypeQualifiers() const { return TypeQualifiers; }
548 SourceLocation getConstSpecLoc() const { return TQ_constLoc; }
549 SourceLocation getRestrictSpecLoc() const { return TQ_restrictLoc; }
550 SourceLocation getVolatileSpecLoc() const { return TQ_volatileLoc; }
551 SourceLocation getAtomicSpecLoc() const { return TQ_atomicLoc; }
552 SourceLocation getUnalignedSpecLoc() const { return TQ_unalignedLoc; }
553 SourceLocation getPipeLoc() const { return TQ_pipeLoc; }
554
555 /// Clear out all of the type qualifiers.
556 void ClearTypeQualifiers() {
557 TypeQualifiers = 0;
558 TQ_constLoc = SourceLocation();
559 TQ_restrictLoc = SourceLocation();
560 TQ_volatileLoc = SourceLocation();
561 TQ_atomicLoc = SourceLocation();
562 TQ_unalignedLoc = SourceLocation();
563 TQ_pipeLoc = SourceLocation();
564 }
565
566 // function-specifier
567 bool isInlineSpecified() const {
568 return FS_inline_specified | FS_forceinline_specified;
569 }
570 SourceLocation getInlineSpecLoc() const {
571 return FS_inline_specified ? FS_inlineLoc : FS_forceinlineLoc;
572 }
573
574 ExplicitSpecifier getExplicitSpecifier() const {
575 return FS_explicit_specifier;
576 }
577
578 bool isVirtualSpecified() const { return FS_virtual_specified; }
579 SourceLocation getVirtualSpecLoc() const { return FS_virtualLoc; }
580
581 bool hasExplicitSpecifier() const {
582 return FS_explicit_specifier.isSpecified();
583 }
584 SourceLocation getExplicitSpecLoc() const { return FS_explicitLoc; }
585 SourceRange getExplicitSpecRange() const {
586 return FS_explicit_specifier.getExpr()
587 ? SourceRange(FS_explicitLoc, FS_explicitCloseParenLoc)
588 : SourceRange(FS_explicitLoc);
589 }
590
591 bool isNoreturnSpecified() const { return FS_noreturn_specified; }
592 SourceLocation getNoreturnSpecLoc() const { return FS_noreturnLoc; }
593
594 void ClearFunctionSpecs() {
595 FS_inline_specified = false;
596 FS_inlineLoc = SourceLocation();
597 FS_forceinline_specified = false;
598 FS_forceinlineLoc = SourceLocation();
599 FS_virtual_specified = false;
600 FS_virtualLoc = SourceLocation();
601 FS_explicit_specifier = ExplicitSpecifier();
602 FS_explicitLoc = SourceLocation();
603 FS_explicitCloseParenLoc = SourceLocation();
604 FS_noreturn_specified = false;
605 FS_noreturnLoc = SourceLocation();
606 }
607
608 /// This method calls the passed in handler on each CVRU qual being
609 /// set.
610 /// Handle - a handler to be invoked.
611 void forEachCVRUQualifier(
612 llvm::function_ref<void(TQ, StringRef, SourceLocation)> Handle);
613
614 /// This method calls the passed in handler on each qual being
615 /// set.
616 /// Handle - a handler to be invoked.
617 void forEachQualifier(
618 llvm::function_ref<void(TQ, StringRef, SourceLocation)> Handle);
619
620 /// Return true if any type-specifier has been found.
621 bool hasTypeSpecifier() const {
622 return getTypeSpecType() != DeclSpec::TST_unspecified ||
623 getTypeSpecWidth() != TypeSpecifierWidth::Unspecified ||
624 getTypeSpecComplex() != DeclSpec::TSC_unspecified ||
625 getTypeSpecSign() != TypeSpecifierSign::Unspecified;
626 }
627
628 /// Return a bitmask of which flavors of specifiers this
629 /// DeclSpec includes.
630 unsigned getParsedSpecifiers() const;
631
632 /// isEmpty - Return true if this declaration specifier is completely empty:
633 /// no tokens were parsed in the production of it.
634 bool isEmpty() const {
635 return getParsedSpecifiers() == DeclSpec::PQ_None;
636 }
637
638 void SetRangeStart(SourceLocation Loc) { Range.setBegin(Loc); }
639 void SetRangeEnd(SourceLocation Loc) { Range.setEnd(Loc); }
640
641 /// These methods set the specified attribute of the DeclSpec and
642 /// return false if there was no error. If an error occurs (for
643 /// example, if we tried to set "auto" on a spec with "extern"
644 /// already set), they return true and set PrevSpec and DiagID
645 /// such that
646 /// Diag(Loc, DiagID) << PrevSpec;
647 /// will yield a useful result.
648 ///
649 /// TODO: use a more general approach that still allows these
650 /// diagnostics to be ignored when desired.
651 bool SetStorageClassSpec(Sema &S, SCS SC, SourceLocation Loc,
652 const char *&PrevSpec, unsigned &DiagID,
653 const PrintingPolicy &Policy);
654 bool SetStorageClassSpecThread(TSCS TSC, SourceLocation Loc,
655 const char *&PrevSpec, unsigned &DiagID);
656 bool SetTypeSpecWidth(TypeSpecifierWidth W, SourceLocation Loc,
657 const char *&PrevSpec, unsigned &DiagID,
658 const PrintingPolicy &Policy);
659 bool SetTypeSpecComplex(TSC C, SourceLocation Loc, const char *&PrevSpec,
660 unsigned &DiagID);
661 bool SetTypeSpecSign(TypeSpecifierSign S, SourceLocation Loc,
662 const char *&PrevSpec, unsigned &DiagID);
663 bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
664 unsigned &DiagID, const PrintingPolicy &Policy);
665 bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
666 unsigned &DiagID, ParsedType Rep,
667 const PrintingPolicy &Policy);
668 bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
669 unsigned &DiagID, TypeResult Rep,
670 const PrintingPolicy &Policy) {
671 if (Rep.isInvalid())
672 return SetTypeSpecError();
673 return SetTypeSpecType(T, Loc, PrevSpec, DiagID, Rep.get(), Policy);
674 }
675 bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
676 unsigned &DiagID, Decl *Rep, bool Owned,
677 const PrintingPolicy &Policy);
678 bool SetTypeSpecType(TST T, SourceLocation TagKwLoc,
679 SourceLocation TagNameLoc, const char *&PrevSpec,
680 unsigned &DiagID, ParsedType Rep,
681 const PrintingPolicy &Policy);
682 bool SetTypeSpecType(TST T, SourceLocation TagKwLoc,
683 SourceLocation TagNameLoc, const char *&PrevSpec,
684 unsigned &DiagID, Decl *Rep, bool Owned,
685 const PrintingPolicy &Policy);
686 bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
687 unsigned &DiagID, TemplateIdAnnotation *Rep,
688 const PrintingPolicy &Policy);
689
690 bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
691 unsigned &DiagID, Expr *Rep,
692 const PrintingPolicy &policy);
693 bool SetTypeAltiVecVector(bool isAltiVecVector, SourceLocation Loc,
694 const char *&PrevSpec, unsigned &DiagID,
695 const PrintingPolicy &Policy);
696 bool SetTypeAltiVecPixel(bool isAltiVecPixel, SourceLocation Loc,
697 const char *&PrevSpec, unsigned &DiagID,
698 const PrintingPolicy &Policy);
699 bool SetTypeAltiVecBool(bool isAltiVecBool, SourceLocation Loc,
700 const char *&PrevSpec, unsigned &DiagID,
701 const PrintingPolicy &Policy);
702 bool SetTypePipe(bool isPipe, SourceLocation Loc,
703 const char *&PrevSpec, unsigned &DiagID,
704 const PrintingPolicy &Policy);
705 bool SetExtIntType(SourceLocation KWLoc, Expr *BitWidth,
706 const char *&PrevSpec, unsigned &DiagID,
707 const PrintingPolicy &Policy);
708 bool SetTypeSpecSat(SourceLocation Loc, const char *&PrevSpec,
709 unsigned &DiagID);
710 bool SetTypeSpecError();
711 void UpdateDeclRep(Decl *Rep) {
712 assert(isDeclRep((TST) TypeSpecType))((isDeclRep((TST) TypeSpecType)) ? static_cast<void> (0
) : __assert_fail ("isDeclRep((TST) TypeSpecType)", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Sema/DeclSpec.h"
, 712, __PRETTY_FUNCTION__))
;
713 DeclRep = Rep;
714 }
715 void UpdateTypeRep(ParsedType Rep) {
716 assert(isTypeRep((TST) TypeSpecType))((isTypeRep((TST) TypeSpecType)) ? static_cast<void> (0
) : __assert_fail ("isTypeRep((TST) TypeSpecType)", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Sema/DeclSpec.h"
, 716, __PRETTY_FUNCTION__))
;
717 TypeRep = Rep;
718 }
719 void UpdateExprRep(Expr *Rep) {
720 assert(isExprRep((TST) TypeSpecType))((isExprRep((TST) TypeSpecType)) ? static_cast<void> (0
) : __assert_fail ("isExprRep((TST) TypeSpecType)", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Sema/DeclSpec.h"
, 720, __PRETTY_FUNCTION__))
;
721 ExprRep = Rep;
722 }
723
724 bool SetTypeQual(TQ T, SourceLocation Loc);
725
726 bool SetTypeQual(TQ T, SourceLocation Loc, const char *&PrevSpec,
727 unsigned &DiagID, const LangOptions &Lang);
728
729 bool setFunctionSpecInline(SourceLocation Loc, const char *&PrevSpec,
730 unsigned &DiagID);
731 bool setFunctionSpecForceInline(SourceLocation Loc, const char *&PrevSpec,
732 unsigned &DiagID);
733 bool setFunctionSpecVirtual(SourceLocation Loc, const char *&PrevSpec,
734 unsigned &DiagID);
735 bool setFunctionSpecExplicit(SourceLocation Loc, const char *&PrevSpec,
736 unsigned &DiagID, ExplicitSpecifier ExplicitSpec,
737 SourceLocation CloseParenLoc);
738 bool setFunctionSpecNoreturn(SourceLocation Loc, const char *&PrevSpec,
739 unsigned &DiagID);
740
741 bool SetFriendSpec(SourceLocation Loc, const char *&PrevSpec,
742 unsigned &DiagID);
743 bool setModulePrivateSpec(SourceLocation Loc, const char *&PrevSpec,
744 unsigned &DiagID);
745 bool SetConstexprSpec(ConstexprSpecKind ConstexprKind, SourceLocation Loc,
746 const char *&PrevSpec, unsigned &DiagID);
747
748 bool isFriendSpecified() const { return Friend_specified; }
749 SourceLocation getFriendSpecLoc() const { return FriendLoc; }
750
751 bool isModulePrivateSpecified() const { return ModulePrivateLoc.isValid(); }
752 SourceLocation getModulePrivateSpecLoc() const { return ModulePrivateLoc; }
753
754 ConstexprSpecKind getConstexprSpecifier() const {
755 return ConstexprSpecKind(ConstexprSpecifier);
756 }
757
758 SourceLocation getConstexprSpecLoc() const { return ConstexprLoc; }
759 bool hasConstexprSpecifier() const {
760 return getConstexprSpecifier() != ConstexprSpecKind::Unspecified;
761 }
762
763 void ClearConstexprSpec() {
764 ConstexprSpecifier = static_cast<unsigned>(ConstexprSpecKind::Unspecified);
765 ConstexprLoc = SourceLocation();
766 }
767
768 AttributePool &getAttributePool() const {
769 return Attrs.getPool();
770 }
771
772 /// Concatenates two attribute lists.
773 ///
774 /// The GCC attribute syntax allows for the following:
775 ///
776 /// \code
777 /// short __attribute__(( unused, deprecated ))
778 /// int __attribute__(( may_alias, aligned(16) )) var;
779 /// \endcode
780 ///
781 /// This declares 4 attributes using 2 lists. The following syntax is
782 /// also allowed and equivalent to the previous declaration.
783 ///
784 /// \code
785 /// short __attribute__((unused)) __attribute__((deprecated))
786 /// int __attribute__((may_alias)) __attribute__((aligned(16))) var;
787 /// \endcode
788 ///
789 void addAttributes(ParsedAttributesView &AL) {
790 Attrs.addAll(AL.begin(), AL.end());
791 }
792
793 bool hasAttributes() const { return !Attrs.empty(); }
794
795 ParsedAttributes &getAttributes() { return Attrs; }
796 const ParsedAttributes &getAttributes() const { return Attrs; }
797
798 void takeAttributesFrom(ParsedAttributes &attrs) {
799 Attrs.takeAllFrom(attrs);
800 }
801
802 /// Finish - This does final analysis of the declspec, issuing diagnostics for
803 /// things like "_Imaginary" (lacking an FP type). After calling this method,
804 /// DeclSpec is guaranteed self-consistent, even if an error occurred.
805 void Finish(Sema &S, const PrintingPolicy &Policy);
806
807 const WrittenBuiltinSpecs& getWrittenBuiltinSpecs() const {
808 return writtenBS;
809 }
810
811 ObjCDeclSpec *getObjCQualifiers() const { return ObjCQualifiers; }
812 void setObjCQualifiers(ObjCDeclSpec *quals) { ObjCQualifiers = quals; }
813
814 /// Checks if this DeclSpec can stand alone, without a Declarator.
815 ///
816 /// Only tag declspecs can stand alone.
817 bool isMissingDeclaratorOk();
818};
819
820/// Captures information about "declaration specifiers" specific to
821/// Objective-C.
822class ObjCDeclSpec {
823public:
824 /// ObjCDeclQualifier - Qualifier used on types in method
825 /// declarations. Not all combinations are sensible. Parameters
826 /// can be one of { in, out, inout } with one of { bycopy, byref }.
827 /// Returns can either be { oneway } or not.
828 ///
829 /// This should be kept in sync with Decl::ObjCDeclQualifier.
830 enum ObjCDeclQualifier {
831 DQ_None = 0x0,
832 DQ_In = 0x1,
833 DQ_Inout = 0x2,
834 DQ_Out = 0x4,
835 DQ_Bycopy = 0x8,
836 DQ_Byref = 0x10,
837 DQ_Oneway = 0x20,
838 DQ_CSNullability = 0x40
839 };
840
841 ObjCDeclSpec()
842 : objcDeclQualifier(DQ_None),
843 PropertyAttributes(ObjCPropertyAttribute::kind_noattr), Nullability(0),
844 GetterName(nullptr), SetterName(nullptr) {}
845
846 ObjCDeclQualifier getObjCDeclQualifier() const {
847 return (ObjCDeclQualifier)objcDeclQualifier;
848 }
849 void setObjCDeclQualifier(ObjCDeclQualifier DQVal) {
850 objcDeclQualifier = (ObjCDeclQualifier) (objcDeclQualifier | DQVal);
851 }
852 void clearObjCDeclQualifier(ObjCDeclQualifier DQVal) {
853 objcDeclQualifier = (ObjCDeclQualifier) (objcDeclQualifier & ~DQVal);
854 }
855
856 ObjCPropertyAttribute::Kind getPropertyAttributes() const {
857 return ObjCPropertyAttribute::Kind(PropertyAttributes);
858 }
859 void setPropertyAttributes(ObjCPropertyAttribute::Kind PRVal) {
860 PropertyAttributes =
861 (ObjCPropertyAttribute::Kind)(PropertyAttributes | PRVal);
862 }
863
864 NullabilityKind getNullability() const {
865 assert(((((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes
() & ObjCPropertyAttribute::kind_nullability)) &&
"Objective-C declspec doesn't have nullability") ? static_cast
<void> (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) && \"Objective-C declspec doesn't have nullability\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Sema/DeclSpec.h"
, 868, __PRETTY_FUNCTION__))
866 ((getObjCDeclQualifier() & DQ_CSNullability) ||((((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes
() & ObjCPropertyAttribute::kind_nullability)) &&
"Objective-C declspec doesn't have nullability") ? static_cast
<void> (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) && \"Objective-C declspec doesn't have nullability\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Sema/DeclSpec.h"
, 868, __PRETTY_FUNCTION__))
867 (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) &&((((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes
() & ObjCPropertyAttribute::kind_nullability)) &&
"Objective-C declspec doesn't have nullability") ? static_cast
<void> (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) && \"Objective-C declspec doesn't have nullability\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Sema/DeclSpec.h"
, 868, __PRETTY_FUNCTION__))
868 "Objective-C declspec doesn't have nullability")((((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes
() & ObjCPropertyAttribute::kind_nullability)) &&
"Objective-C declspec doesn't have nullability") ? static_cast
<void> (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) && \"Objective-C declspec doesn't have nullability\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Sema/DeclSpec.h"
, 868, __PRETTY_FUNCTION__))
;
869 return static_cast<NullabilityKind>(Nullability);
870 }
871
872 SourceLocation getNullabilityLoc() const {
873 assert(((((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes
() & ObjCPropertyAttribute::kind_nullability)) &&
"Objective-C declspec doesn't have nullability") ? static_cast
<void> (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) && \"Objective-C declspec doesn't have nullability\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Sema/DeclSpec.h"
, 876, __PRETTY_FUNCTION__))
874 ((getObjCDeclQualifier() & DQ_CSNullability) ||((((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes
() & ObjCPropertyAttribute::kind_nullability)) &&
"Objective-C declspec doesn't have nullability") ? static_cast
<void> (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) && \"Objective-C declspec doesn't have nullability\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Sema/DeclSpec.h"
, 876, __PRETTY_FUNCTION__))
875 (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) &&((((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes
() & ObjCPropertyAttribute::kind_nullability)) &&
"Objective-C declspec doesn't have nullability") ? static_cast
<void> (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) && \"Objective-C declspec doesn't have nullability\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Sema/DeclSpec.h"
, 876, __PRETTY_FUNCTION__))
876 "Objective-C declspec doesn't have nullability")((((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes
() & ObjCPropertyAttribute::kind_nullability)) &&
"Objective-C declspec doesn't have nullability") ? static_cast
<void> (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) && \"Objective-C declspec doesn't have nullability\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Sema/DeclSpec.h"
, 876, __PRETTY_FUNCTION__))
;
877 return NullabilityLoc;
878 }
879
880 void setNullability(SourceLocation loc, NullabilityKind kind) {
881 assert(((((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes
() & ObjCPropertyAttribute::kind_nullability)) &&
"Set the nullability declspec or property attribute first") ?
static_cast<void> (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) && \"Set the nullability declspec or property attribute first\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Sema/DeclSpec.h"
, 884, __PRETTY_FUNCTION__))
882 ((getObjCDeclQualifier() & DQ_CSNullability) ||((((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes
() & ObjCPropertyAttribute::kind_nullability)) &&
"Set the nullability declspec or property attribute first") ?
static_cast<void> (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) && \"Set the nullability declspec or property attribute first\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Sema/DeclSpec.h"
, 884, __PRETTY_FUNCTION__))
883 (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) &&((((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes
() & ObjCPropertyAttribute::kind_nullability)) &&
"Set the nullability declspec or property attribute first") ?
static_cast<void> (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) && \"Set the nullability declspec or property attribute first\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Sema/DeclSpec.h"
, 884, __PRETTY_FUNCTION__))
884 "Set the nullability declspec or property attribute first")((((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes
() & ObjCPropertyAttribute::kind_nullability)) &&
"Set the nullability declspec or property attribute first") ?
static_cast<void> (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) && \"Set the nullability declspec or property attribute first\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Sema/DeclSpec.h"
, 884, __PRETTY_FUNCTION__))
;
885 Nullability = static_cast<unsigned>(kind);
886 NullabilityLoc = loc;
887 }
888
889 const IdentifierInfo *getGetterName() const { return GetterName; }
890 IdentifierInfo *getGetterName() { return GetterName; }
891 SourceLocation getGetterNameLoc() const { return GetterNameLoc; }
892 void setGetterName(IdentifierInfo *name, SourceLocation loc) {
893 GetterName = name;
894 GetterNameLoc = loc;
895 }
896
897 const IdentifierInfo *getSetterName() const { return SetterName; }
898 IdentifierInfo *getSetterName() { return SetterName; }
899 SourceLocation getSetterNameLoc() const { return SetterNameLoc; }
900 void setSetterName(IdentifierInfo *name, SourceLocation loc) {
901 SetterName = name;
902 SetterNameLoc = loc;
903 }
904
905private:
906 // FIXME: These two are unrelated and mutually exclusive. So perhaps
907 // we can put them in a union to reflect their mutual exclusivity
908 // (space saving is negligible).
909 unsigned objcDeclQualifier : 7;
910
911 // NOTE: VC++ treats enums as signed, avoid using ObjCPropertyAttribute::Kind
912 unsigned PropertyAttributes : NumObjCPropertyAttrsBits;
913
914 unsigned Nullability : 2;
915
916 SourceLocation NullabilityLoc;
917
918 IdentifierInfo *GetterName; // getter name or NULL if no getter
919 IdentifierInfo *SetterName; // setter name or NULL if no setter
920 SourceLocation GetterNameLoc; // location of the getter attribute's value
921 SourceLocation SetterNameLoc; // location of the setter attribute's value
922
923};
924
925/// Describes the kind of unqualified-id parsed.
926enum class UnqualifiedIdKind {
927 /// An identifier.
928 IK_Identifier,
929 /// An overloaded operator name, e.g., operator+.
930 IK_OperatorFunctionId,
931 /// A conversion function name, e.g., operator int.
932 IK_ConversionFunctionId,
933 /// A user-defined literal name, e.g., operator "" _i.
934 IK_LiteralOperatorId,
935 /// A constructor name.
936 IK_ConstructorName,
937 /// A constructor named via a template-id.
938 IK_ConstructorTemplateId,
939 /// A destructor name.
940 IK_DestructorName,
941 /// A template-id, e.g., f<int>.
942 IK_TemplateId,
943 /// An implicit 'self' parameter
944 IK_ImplicitSelfParam,
945 /// A deduction-guide name (a template-name)
946 IK_DeductionGuideName
947};
948
949/// Represents a C++ unqualified-id that has been parsed.
950class UnqualifiedId {
951private:
952 UnqualifiedId(const UnqualifiedId &Other) = delete;
953 const UnqualifiedId &operator=(const UnqualifiedId &) = delete;
954
955public:
956 /// Describes the kind of unqualified-id parsed.
957 UnqualifiedIdKind Kind;
958
959 struct OFI {
960 /// The kind of overloaded operator.
961 OverloadedOperatorKind Operator;
962
963 /// The source locations of the individual tokens that name
964 /// the operator, e.g., the "new", "[", and "]" tokens in
965 /// operator new [].
966 ///
967 /// Different operators have different numbers of tokens in their name,
968 /// up to three. Any remaining source locations in this array will be
969 /// set to an invalid value for operators with fewer than three tokens.
970 SourceLocation SymbolLocations[3];
971 };
972
973 /// Anonymous union that holds extra data associated with the
974 /// parsed unqualified-id.
975 union {
976 /// When Kind == IK_Identifier, the parsed identifier, or when
977 /// Kind == IK_UserLiteralId, the identifier suffix.
978 IdentifierInfo *Identifier;
979
980 /// When Kind == IK_OperatorFunctionId, the overloaded operator
981 /// that we parsed.
982 struct OFI OperatorFunctionId;
983
984 /// When Kind == IK_ConversionFunctionId, the type that the
985 /// conversion function names.
986 UnionParsedType ConversionFunctionId;
987
988 /// When Kind == IK_ConstructorName, the class-name of the type
989 /// whose constructor is being referenced.
990 UnionParsedType ConstructorName;
991
992 /// When Kind == IK_DestructorName, the type referred to by the
993 /// class-name.
994 UnionParsedType DestructorName;
995
996 /// When Kind == IK_DeductionGuideName, the parsed template-name.
997 UnionParsedTemplateTy TemplateName;
998
999 /// When Kind == IK_TemplateId or IK_ConstructorTemplateId,
1000 /// the template-id annotation that contains the template name and
1001 /// template arguments.
1002 TemplateIdAnnotation *TemplateId;
1003 };
1004
1005 /// The location of the first token that describes this unqualified-id,
1006 /// which will be the location of the identifier, "operator" keyword,
1007 /// tilde (for a destructor), or the template name of a template-id.
1008 SourceLocation StartLocation;
1009
1010 /// The location of the last token that describes this unqualified-id.
1011 SourceLocation EndLocation;
1012
1013 UnqualifiedId()
1014 : Kind(UnqualifiedIdKind::IK_Identifier), Identifier(nullptr) {}
1015
1016 /// Clear out this unqualified-id, setting it to default (invalid)
1017 /// state.
1018 void clear() {
1019 Kind = UnqualifiedIdKind::IK_Identifier;
1020 Identifier = nullptr;
1021 StartLocation = SourceLocation();
1022 EndLocation = SourceLocation();
1023 }
1024
1025 /// Determine whether this unqualified-id refers to a valid name.
1026 bool isValid() const { return StartLocation.isValid(); }
1027
1028 /// Determine whether this unqualified-id refers to an invalid name.
1029 bool isInvalid() const { return !isValid(); }
1030
1031 /// Determine what kind of name we have.
1032 UnqualifiedIdKind getKind() const { return Kind; }
1033
1034 /// Specify that this unqualified-id was parsed as an identifier.
1035 ///
1036 /// \param Id the parsed identifier.
1037 /// \param IdLoc the location of the parsed identifier.
1038 void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc) {
1039 Kind = UnqualifiedIdKind::IK_Identifier;
1040 Identifier = const_cast<IdentifierInfo *>(Id);
1041 StartLocation = EndLocation = IdLoc;
1042 }
1043
1044 /// Specify that this unqualified-id was parsed as an
1045 /// operator-function-id.
1046 ///
1047 /// \param OperatorLoc the location of the 'operator' keyword.
1048 ///
1049 /// \param Op the overloaded operator.
1050 ///
1051 /// \param SymbolLocations the locations of the individual operator symbols
1052 /// in the operator.
1053 void setOperatorFunctionId(SourceLocation OperatorLoc,
1054 OverloadedOperatorKind Op,
1055 SourceLocation SymbolLocations[3]);
1056
1057 /// Specify that this unqualified-id was parsed as a
1058 /// conversion-function-id.
1059 ///
1060 /// \param OperatorLoc the location of the 'operator' keyword.
1061 ///
1062 /// \param Ty the type to which this conversion function is converting.
1063 ///
1064 /// \param EndLoc the location of the last token that makes up the type name.
1065 void setConversionFunctionId(SourceLocation OperatorLoc,
1066 ParsedType Ty,
1067 SourceLocation EndLoc) {
1068 Kind = UnqualifiedIdKind::IK_ConversionFunctionId;
1069 StartLocation = OperatorLoc;
1070 EndLocation = EndLoc;
1071 ConversionFunctionId = Ty;
1072 }
1073
1074 /// Specific that this unqualified-id was parsed as a
1075 /// literal-operator-id.
1076 ///
1077 /// \param Id the parsed identifier.
1078 ///
1079 /// \param OpLoc the location of the 'operator' keyword.
1080 ///
1081 /// \param IdLoc the location of the identifier.
1082 void setLiteralOperatorId(const IdentifierInfo *Id, SourceLocation OpLoc,
1083 SourceLocation IdLoc) {
1084 Kind = UnqualifiedIdKind::IK_LiteralOperatorId;
1085 Identifier = const_cast<IdentifierInfo *>(Id);
1086 StartLocation = OpLoc;
1087 EndLocation = IdLoc;
1088 }
1089
1090 /// Specify that this unqualified-id was parsed as a constructor name.
1091 ///
1092 /// \param ClassType the class type referred to by the constructor name.
1093 ///
1094 /// \param ClassNameLoc the location of the class name.
1095 ///
1096 /// \param EndLoc the location of the last token that makes up the type name.
1097 void setConstructorName(ParsedType ClassType,
1098 SourceLocation ClassNameLoc,
1099 SourceLocation EndLoc) {
1100 Kind = UnqualifiedIdKind::IK_ConstructorName;
1101 StartLocation = ClassNameLoc;
1102 EndLocation = EndLoc;
1103 ConstructorName = ClassType;
1104 }
1105
1106 /// Specify that this unqualified-id was parsed as a
1107 /// template-id that names a constructor.
1108 ///
1109 /// \param TemplateId the template-id annotation that describes the parsed
1110 /// template-id. This UnqualifiedId instance will take ownership of the
1111 /// \p TemplateId and will free it on destruction.
1112 void setConstructorTemplateId(TemplateIdAnnotation *TemplateId);
1113
1114 /// Specify that this unqualified-id was parsed as a destructor name.
1115 ///
1116 /// \param TildeLoc the location of the '~' that introduces the destructor
1117 /// name.
1118 ///
1119 /// \param ClassType the name of the class referred to by the destructor name.
1120 void setDestructorName(SourceLocation TildeLoc,
1121 ParsedType ClassType,
1122 SourceLocation EndLoc) {
1123 Kind = UnqualifiedIdKind::IK_DestructorName;
1124 StartLocation = TildeLoc;
1125 EndLocation = EndLoc;
1126 DestructorName = ClassType;
1127 }
1128
1129 /// Specify that this unqualified-id was parsed as a template-id.
1130 ///
1131 /// \param TemplateId the template-id annotation that describes the parsed
1132 /// template-id. This UnqualifiedId instance will take ownership of the
1133 /// \p TemplateId and will free it on destruction.
1134 void setTemplateId(TemplateIdAnnotation *TemplateId);
1135
1136 /// Specify that this unqualified-id was parsed as a template-name for
1137 /// a deduction-guide.
1138 ///
1139 /// \param Template The parsed template-name.
1140 /// \param TemplateLoc The location of the parsed template-name.
1141 void setDeductionGuideName(ParsedTemplateTy Template,
1142 SourceLocation TemplateLoc) {
1143 Kind = UnqualifiedIdKind::IK_DeductionGuideName;
1144 TemplateName = Template;
1145 StartLocation = EndLocation = TemplateLoc;
1146 }
1147
1148 /// Specify that this unqualified-id is an implicit 'self'
1149 /// parameter.
1150 ///
1151 /// \param Id the identifier.
1152 void setImplicitSelfParam(const IdentifierInfo *Id) {
1153 Kind = UnqualifiedIdKind::IK_ImplicitSelfParam;
1154 Identifier = const_cast<IdentifierInfo *>(Id);
1155 StartLocation = EndLocation = SourceLocation();
1156 }
1157
1158 /// Return the source range that covers this unqualified-id.
1159 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) {
1160 return SourceRange(StartLocation, EndLocation);
1161 }
1162 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return StartLocation; }
1163 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return EndLocation; }
1164};
1165
1166/// A set of tokens that has been cached for later parsing.
1167typedef SmallVector<Token, 4> CachedTokens;
1168
1169/// One instance of this struct is used for each type in a
1170/// declarator that is parsed.
1171///
1172/// This is intended to be a small value object.
1173struct DeclaratorChunk {
1174 DeclaratorChunk() {};
1175
1176 enum {
1177 Pointer, Reference, Array, Function, BlockPointer, MemberPointer, Paren, Pipe
1178 } Kind;
1179
1180 /// Loc - The place where this type was defined.
1181 SourceLocation Loc;
1182 /// EndLoc - If valid, the place where this chunck ends.
1183 SourceLocation EndLoc;
1184
1185 SourceRange getSourceRange() const {
1186 if (EndLoc.isInvalid())
1187 return SourceRange(Loc, Loc);
1188 return SourceRange(Loc, EndLoc);
1189 }
1190
1191 ParsedAttributesView AttrList;
1192
1193 struct PointerTypeInfo {
1194 /// The type qualifiers: const/volatile/restrict/unaligned/atomic.
1195 unsigned TypeQuals : 5;
1196
1197 /// The location of the const-qualifier, if any.
1198 SourceLocation ConstQualLoc;
1199
1200 /// The location of the volatile-qualifier, if any.
1201 SourceLocation VolatileQualLoc;
1202
1203 /// The location of the restrict-qualifier, if any.
1204 SourceLocation RestrictQualLoc;
1205
1206 /// The location of the _Atomic-qualifier, if any.
1207 SourceLocation AtomicQualLoc;
1208
1209 /// The location of the __unaligned-qualifier, if any.
1210 SourceLocation UnalignedQualLoc;
1211
1212 void destroy() {
1213 }
1214 };
1215
1216 struct ReferenceTypeInfo {
1217 /// The type qualifier: restrict. [GNU] C++ extension
1218 bool HasRestrict : 1;
1219 /// True if this is an lvalue reference, false if it's an rvalue reference.
1220 bool LValueRef : 1;
1221 void destroy() {
1222 }
1223 };
1224
1225 struct ArrayTypeInfo {
1226 /// The type qualifiers for the array:
1227 /// const/volatile/restrict/__unaligned/_Atomic.
1228 unsigned TypeQuals : 5;
1229
1230 /// True if this dimension included the 'static' keyword.
1231 unsigned hasStatic : 1;
1232
1233 /// True if this dimension was [*]. In this case, NumElts is null.
1234 unsigned isStar : 1;
1235
1236 /// This is the size of the array, or null if [] or [*] was specified.
1237 /// Since the parser is multi-purpose, and we don't want to impose a root
1238 /// expression class on all clients, NumElts is untyped.
1239 Expr *NumElts;
1240
1241 void destroy() {}
1242 };
1243
1244 /// ParamInfo - An array of paraminfo objects is allocated whenever a function
1245 /// declarator is parsed. There are two interesting styles of parameters
1246 /// here:
1247 /// K&R-style identifier lists and parameter type lists. K&R-style identifier
1248 /// lists will have information about the identifier, but no type information.
1249 /// Parameter type lists will have type info (if the actions module provides
1250 /// it), but may have null identifier info: e.g. for 'void foo(int X, int)'.
1251 struct ParamInfo {
1252 IdentifierInfo *Ident;
1253 SourceLocation IdentLoc;
1254 Decl *Param;
1255
1256 /// DefaultArgTokens - When the parameter's default argument
1257 /// cannot be parsed immediately (because it occurs within the
1258 /// declaration of a member function), it will be stored here as a
1259 /// sequence of tokens to be parsed once the class definition is
1260 /// complete. Non-NULL indicates that there is a default argument.
1261 std::unique_ptr<CachedTokens> DefaultArgTokens;
1262
1263 ParamInfo() = default;
1264 ParamInfo(IdentifierInfo *ident, SourceLocation iloc,
1265 Decl *param,
1266 std::unique_ptr<CachedTokens> DefArgTokens = nullptr)
1267 : Ident(ident), IdentLoc(iloc), Param(param),
1268 DefaultArgTokens(std::move(DefArgTokens)) {}
1269 };
1270
1271 struct TypeAndRange {
1272 ParsedType Ty;
1273 SourceRange Range;
1274 };
1275
1276 struct FunctionTypeInfo {
1277 /// hasPrototype - This is true if the function had at least one typed
1278 /// parameter. If the function is () or (a,b,c), then it has no prototype,
1279 /// and is treated as a K&R-style function.
1280 unsigned hasPrototype : 1;
1281
1282 /// isVariadic - If this function has a prototype, and if that
1283 /// proto ends with ',...)', this is true. When true, EllipsisLoc
1284 /// contains the location of the ellipsis.
1285 unsigned isVariadic : 1;
1286
1287 /// Can this declaration be a constructor-style initializer?
1288 unsigned isAmbiguous : 1;
1289
1290 /// Whether the ref-qualifier (if any) is an lvalue reference.
1291 /// Otherwise, it's an rvalue reference.
1292 unsigned RefQualifierIsLValueRef : 1;
1293
1294 /// ExceptionSpecType - An ExceptionSpecificationType value.
1295 unsigned ExceptionSpecType : 4;
1296
1297 /// DeleteParams - If this is true, we need to delete[] Params.
1298 unsigned DeleteParams : 1;
1299
1300 /// HasTrailingReturnType - If this is true, a trailing return type was
1301 /// specified.
1302 unsigned HasTrailingReturnType : 1;
1303
1304 /// The location of the left parenthesis in the source.
1305 SourceLocation LParenLoc;
1306
1307 /// When isVariadic is true, the location of the ellipsis in the source.
1308 SourceLocation EllipsisLoc;
1309
1310 /// The location of the right parenthesis in the source.
1311 SourceLocation RParenLoc;
1312
1313 /// NumParams - This is the number of formal parameters specified by the
1314 /// declarator.
1315 unsigned NumParams;
1316
1317 /// NumExceptionsOrDecls - This is the number of types in the
1318 /// dynamic-exception-decl, if the function has one. In C, this is the
1319 /// number of declarations in the function prototype.
1320 unsigned NumExceptionsOrDecls;
1321
1322 /// The location of the ref-qualifier, if any.
1323 ///
1324 /// If this is an invalid location, there is no ref-qualifier.
1325 SourceLocation RefQualifierLoc;
1326
1327 /// The location of the 'mutable' qualifer in a lambda-declarator, if
1328 /// any.
1329 SourceLocation MutableLoc;
1330
1331 /// The beginning location of the exception specification, if any.
1332 SourceLocation ExceptionSpecLocBeg;
1333
1334 /// The end location of the exception specification, if any.
1335 SourceLocation ExceptionSpecLocEnd;
1336
1337 /// Params - This is a pointer to a new[]'d array of ParamInfo objects that
1338 /// describe the parameters specified by this function declarator. null if
1339 /// there are no parameters specified.
1340 ParamInfo *Params;
1341
1342 /// DeclSpec for the function with the qualifier related info.
1343 DeclSpec *MethodQualifiers;
1344
1345 /// AtttibuteFactory for the MethodQualifiers.
1346 AttributeFactory *QualAttrFactory;
1347
1348 union {
1349 /// Pointer to a new[]'d array of TypeAndRange objects that
1350 /// contain the types in the function's dynamic exception specification
1351 /// and their locations, if there is one.
1352 TypeAndRange *Exceptions;
1353
1354 /// Pointer to the expression in the noexcept-specifier of this
1355 /// function, if it has one.
1356 Expr *NoexceptExpr;
1357
1358 /// Pointer to the cached tokens for an exception-specification
1359 /// that has not yet been parsed.
1360 CachedTokens *ExceptionSpecTokens;
1361
1362 /// Pointer to a new[]'d array of declarations that need to be available
1363 /// for lookup inside the function body, if one exists. Does not exist in
1364 /// C++.
1365 NamedDecl **DeclsInPrototype;
1366 };
1367
1368 /// If HasTrailingReturnType is true, this is the trailing return
1369 /// type specified.
1370 UnionParsedType TrailingReturnType;
1371
1372 /// If HasTrailingReturnType is true, this is the location of the trailing
1373 /// return type.
1374 SourceLocation TrailingReturnTypeLoc;
1375
1376 /// Reset the parameter list to having zero parameters.
1377 ///
1378 /// This is used in various places for error recovery.
1379 void freeParams() {
1380 for (unsigned I = 0; I < NumParams; ++I)
1381 Params[I].DefaultArgTokens.reset();
1382 if (DeleteParams) {
1383 delete[] Params;
1384 DeleteParams = false;
1385 }
1386 NumParams = 0;
1387 }
1388
1389 void destroy() {
1390 freeParams();
1391 delete QualAttrFactory;
1392 delete MethodQualifiers;
1393 switch (getExceptionSpecType()) {
1394 default:
1395 break;
1396 case EST_Dynamic:
1397 delete[] Exceptions;
1398 break;
1399 case EST_Unparsed:
1400 delete ExceptionSpecTokens;
1401 break;
1402 case EST_None:
1403 if (NumExceptionsOrDecls != 0)
1404 delete[] DeclsInPrototype;
1405 break;
1406 }
1407 }
1408
1409 DeclSpec &getOrCreateMethodQualifiers() {
1410 if (!MethodQualifiers) {
1411 QualAttrFactory = new AttributeFactory();
1412 MethodQualifiers = new DeclSpec(*QualAttrFactory);
1413 }
1414 return *MethodQualifiers;
1415 }
1416
1417 /// isKNRPrototype - Return true if this is a K&R style identifier list,
1418 /// like "void foo(a,b,c)". In a function definition, this will be followed
1419 /// by the parameter type definitions.
1420 bool isKNRPrototype() const { return !hasPrototype && NumParams != 0; }
1421
1422 SourceLocation getLParenLoc() const { return LParenLoc; }
1423
1424 SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
1425
1426 SourceLocation getRParenLoc() const { return RParenLoc; }
1427
1428 SourceLocation getExceptionSpecLocBeg() const {
1429 return ExceptionSpecLocBeg;
1430 }
1431
1432 SourceLocation getExceptionSpecLocEnd() const {
1433 return ExceptionSpecLocEnd;
1434 }
1435
1436 SourceRange getExceptionSpecRange() const {
1437 return SourceRange(getExceptionSpecLocBeg(), getExceptionSpecLocEnd());
1438 }
1439
1440 /// Retrieve the location of the ref-qualifier, if any.
1441 SourceLocation getRefQualifierLoc() const { return RefQualifierLoc; }
1442
1443 /// Retrieve the location of the 'const' qualifier.
1444 SourceLocation getConstQualifierLoc() const {
1445 assert(MethodQualifiers)((MethodQualifiers) ? static_cast<void> (0) : __assert_fail
("MethodQualifiers", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Sema/DeclSpec.h"
, 1445, __PRETTY_FUNCTION__))
;
1446 return MethodQualifiers->getConstSpecLoc();
1447 }
1448
1449 /// Retrieve the location of the 'volatile' qualifier.
1450 SourceLocation getVolatileQualifierLoc() const {
1451 assert(MethodQualifiers)((MethodQualifiers) ? static_cast<void> (0) : __assert_fail
("MethodQualifiers", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Sema/DeclSpec.h"
, 1451, __PRETTY_FUNCTION__))
;
1452 return MethodQualifiers->getVolatileSpecLoc();
1453 }
1454
1455 /// Retrieve the location of the 'restrict' qualifier.
1456 SourceLocation getRestrictQualifierLoc() const {
1457 assert(MethodQualifiers)((MethodQualifiers) ? static_cast<void> (0) : __assert_fail
("MethodQualifiers", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Sema/DeclSpec.h"
, 1457, __PRETTY_FUNCTION__))
;
1458 return MethodQualifiers->getRestrictSpecLoc();
1459 }
1460
1461 /// Retrieve the location of the 'mutable' qualifier, if any.
1462 SourceLocation getMutableLoc() const { return MutableLoc; }
1463
1464 /// Determine whether this function declaration contains a
1465 /// ref-qualifier.
1466 bool hasRefQualifier() const { return getRefQualifierLoc().isValid(); }
1467
1468 /// Determine whether this lambda-declarator contains a 'mutable'
1469 /// qualifier.
1470 bool hasMutableQualifier() const { return getMutableLoc().isValid(); }
1471
1472 /// Determine whether this method has qualifiers.
1473 bool hasMethodTypeQualifiers() const {
1474 return MethodQualifiers && (MethodQualifiers->getTypeQualifiers() ||
1475 MethodQualifiers->getAttributes().size());
1476 }
1477
1478 /// Get the type of exception specification this function has.
1479 ExceptionSpecificationType getExceptionSpecType() const {
1480 return static_cast<ExceptionSpecificationType>(ExceptionSpecType);
1481 }
1482
1483 /// Get the number of dynamic exception specifications.
1484 unsigned getNumExceptions() const {
1485 assert(ExceptionSpecType != EST_None)((ExceptionSpecType != EST_None) ? static_cast<void> (0
) : __assert_fail ("ExceptionSpecType != EST_None", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Sema/DeclSpec.h"
, 1485, __PRETTY_FUNCTION__))
;
1486 return NumExceptionsOrDecls;
1487 }
1488
1489 /// Get the non-parameter decls defined within this function
1490 /// prototype. Typically these are tag declarations.
1491 ArrayRef<NamedDecl *> getDeclsInPrototype() const {
1492 assert(ExceptionSpecType == EST_None)((ExceptionSpecType == EST_None) ? static_cast<void> (0
) : __assert_fail ("ExceptionSpecType == EST_None", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Sema/DeclSpec.h"
, 1492, __PRETTY_FUNCTION__))
;
1493 return llvm::makeArrayRef(DeclsInPrototype, NumExceptionsOrDecls);
1494 }
1495
1496 /// Determine whether this function declarator had a
1497 /// trailing-return-type.
1498 bool hasTrailingReturnType() const { return HasTrailingReturnType; }
1499
1500 /// Get the trailing-return-type for this function declarator.
1501 ParsedType getTrailingReturnType() const {
1502 assert(HasTrailingReturnType)((HasTrailingReturnType) ? static_cast<void> (0) : __assert_fail
("HasTrailingReturnType", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Sema/DeclSpec.h"
, 1502, __PRETTY_FUNCTION__))
;
1503 return TrailingReturnType;
1504 }
1505
1506 /// Get the trailing-return-type location for this function declarator.
1507 SourceLocation getTrailingReturnTypeLoc() const {
1508 assert(HasTrailingReturnType)((HasTrailingReturnType) ? static_cast<void> (0) : __assert_fail
("HasTrailingReturnType", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Sema/DeclSpec.h"
, 1508, __PRETTY_FUNCTION__))
;
1509 return TrailingReturnTypeLoc;
1510 }
1511 };
1512
1513 struct BlockPointerTypeInfo {
1514 /// For now, sema will catch these as invalid.
1515 /// The type qualifiers: const/volatile/restrict/__unaligned/_Atomic.
1516 unsigned TypeQuals : 5;
1517
1518 void destroy() {
1519 }
1520 };
1521
1522 struct MemberPointerTypeInfo {
1523 /// The type qualifiers: const/volatile/restrict/__unaligned/_Atomic.
1524 unsigned TypeQuals : 5;
1525 /// Location of the '*' token.
1526 SourceLocation StarLoc;
1527 // CXXScopeSpec has a constructor, so it can't be a direct member.
1528 // So we need some pointer-aligned storage and a bit of trickery.
1529 alignas(CXXScopeSpec) char ScopeMem[sizeof(CXXScopeSpec)];
1530 CXXScopeSpec &Scope() {
1531 return *reinterpret_cast<CXXScopeSpec *>(ScopeMem);
1532 }
1533 const CXXScopeSpec &Scope() const {
1534 return *reinterpret_cast<const CXXScopeSpec *>(ScopeMem);
1535 }
1536 void destroy() {
1537 Scope().~CXXScopeSpec();
1538 }
1539 };
1540
1541 struct PipeTypeInfo {
1542 /// The access writes.
1543 unsigned AccessWrites : 3;
1544
1545 void destroy() {}
1546 };
1547
1548 union {
1549 PointerTypeInfo Ptr;
1550 ReferenceTypeInfo Ref;
1551 ArrayTypeInfo Arr;
1552 FunctionTypeInfo Fun;
1553 BlockPointerTypeInfo Cls;
1554 MemberPointerTypeInfo Mem;
1555 PipeTypeInfo PipeInfo;
1556 };
1557
1558 void destroy() {
1559 switch (Kind) {
1560 case DeclaratorChunk::Function: return Fun.destroy();
1561 case DeclaratorChunk::Pointer: return Ptr.destroy();
1562 case DeclaratorChunk::BlockPointer: return Cls.destroy();
1563 case DeclaratorChunk::Reference: return Ref.destroy();
1564 case DeclaratorChunk::Array: return Arr.destroy();
1565 case DeclaratorChunk::MemberPointer: return Mem.destroy();
1566 case DeclaratorChunk::Paren: return;
1567 case DeclaratorChunk::Pipe: return PipeInfo.destroy();
1568 }
1569 }
1570
1571 /// If there are attributes applied to this declaratorchunk, return
1572 /// them.
1573 const ParsedAttributesView &getAttrs() const { return AttrList; }
1574 ParsedAttributesView &getAttrs() { return AttrList; }
1575
1576 /// Return a DeclaratorChunk for a pointer.
1577 static DeclaratorChunk getPointer(unsigned TypeQuals, SourceLocation Loc,
1578 SourceLocation ConstQualLoc,
1579 SourceLocation VolatileQualLoc,
1580 SourceLocation RestrictQualLoc,
1581 SourceLocation AtomicQualLoc,
1582 SourceLocation UnalignedQualLoc) {
1583 DeclaratorChunk I;
1584 I.Kind = Pointer;
1585 I.Loc = Loc;
1586 new (&I.Ptr) PointerTypeInfo;
1587 I.Ptr.TypeQuals = TypeQuals;
1588 I.Ptr.ConstQualLoc = ConstQualLoc;
1589 I.Ptr.VolatileQualLoc = VolatileQualLoc;
1590 I.Ptr.RestrictQualLoc = RestrictQualLoc;
1591 I.Ptr.AtomicQualLoc = AtomicQualLoc;
1592 I.Ptr.UnalignedQualLoc = UnalignedQualLoc;
1593 return I;
1594 }
1595
1596 /// Return a DeclaratorChunk for a reference.
1597 static DeclaratorChunk getReference(unsigned TypeQuals, SourceLocation Loc,
1598 bool lvalue) {
1599 DeclaratorChunk I;
1600 I.Kind = Reference;
1601 I.Loc = Loc;
1602 I.Ref.HasRestrict = (TypeQuals & DeclSpec::TQ_restrict) != 0;
1603 I.Ref.LValueRef = lvalue;
1604 return I;
1605 }
1606
1607 /// Return a DeclaratorChunk for an array.
1608 static DeclaratorChunk getArray(unsigned TypeQuals,
1609 bool isStatic, bool isStar, Expr *NumElts,
1610 SourceLocation LBLoc, SourceLocation RBLoc) {
1611 DeclaratorChunk I;
1612 I.Kind = Array;
1613 I.Loc = LBLoc;
1614 I.EndLoc = RBLoc;
1615 I.Arr.TypeQuals = TypeQuals;
1616 I.Arr.hasStatic = isStatic;
1617 I.Arr.isStar = isStar;
1618 I.Arr.NumElts = NumElts;
1619 return I;
1620 }
1621
1622 /// DeclaratorChunk::getFunction - Return a DeclaratorChunk for a function.
1623 /// "TheDeclarator" is the declarator that this will be added to.
1624 static DeclaratorChunk getFunction(bool HasProto,
1625 bool IsAmbiguous,
1626 SourceLocation LParenLoc,
1627 ParamInfo *Params, unsigned NumParams,
1628 SourceLocation EllipsisLoc,
1629 SourceLocation RParenLoc,
1630 bool RefQualifierIsLvalueRef,
1631 SourceLocation RefQualifierLoc,
1632 SourceLocation MutableLoc,
1633 ExceptionSpecificationType ESpecType,
1634 SourceRange ESpecRange,
1635 ParsedType *Exceptions,
1636 SourceRange *ExceptionRanges,
1637 unsigned NumExceptions,
1638 Expr *NoexceptExpr,
1639 CachedTokens *ExceptionSpecTokens,
1640 ArrayRef<NamedDecl *> DeclsInPrototype,
1641 SourceLocation LocalRangeBegin,
1642 SourceLocation LocalRangeEnd,
1643 Declarator &TheDeclarator,
1644 TypeResult TrailingReturnType =
1645 TypeResult(),
1646 SourceLocation TrailingReturnTypeLoc =
1647 SourceLocation(),
1648 DeclSpec *MethodQualifiers = nullptr);
1649
1650 /// Return a DeclaratorChunk for a block.
1651 static DeclaratorChunk getBlockPointer(unsigned TypeQuals,
1652 SourceLocation Loc) {
1653 DeclaratorChunk I;
1654 I.Kind = BlockPointer;
1655 I.Loc = Loc;
1656 I.Cls.TypeQuals = TypeQuals;
1657 return I;
1658 }
1659
1660 /// Return a DeclaratorChunk for a block.
1661 static DeclaratorChunk getPipe(unsigned TypeQuals,
1662 SourceLocation Loc) {
1663 DeclaratorChunk I;
1664 I.Kind = Pipe;
1665 I.Loc = Loc;
1666 I.Cls.TypeQuals = TypeQuals;
1667 return I;
1668 }
1669
1670 static DeclaratorChunk getMemberPointer(const CXXScopeSpec &SS,
1671 unsigned TypeQuals,
1672 SourceLocation StarLoc,
1673 SourceLocation EndLoc) {
1674 DeclaratorChunk I;
1675 I.Kind = MemberPointer;
1676 I.Loc = SS.getBeginLoc();
1677 I.EndLoc = EndLoc;
1678 new (&I.Mem) MemberPointerTypeInfo;
1679 I.Mem.StarLoc = StarLoc;
1680 I.Mem.TypeQuals = TypeQuals;
1681 new (I.Mem.ScopeMem) CXXScopeSpec(SS);
1682 return I;
1683 }
1684
1685 /// Return a DeclaratorChunk for a paren.
1686 static DeclaratorChunk getParen(SourceLocation LParenLoc,
1687 SourceLocation RParenLoc) {
1688 DeclaratorChunk I;
1689 I.Kind = Paren;
1690 I.Loc = LParenLoc;
1691 I.EndLoc = RParenLoc;
1692 return I;
1693 }
1694
1695 bool isParen() const {
1696 return Kind == Paren;
1697 }
1698};
1699
1700/// A parsed C++17 decomposition declarator of the form
1701/// '[' identifier-list ']'
1702class DecompositionDeclarator {
1703public:
1704 struct Binding {
1705 IdentifierInfo *Name;
1706 SourceLocation NameLoc;
1707 };
1708
1709private:
1710 /// The locations of the '[' and ']' tokens.
1711 SourceLocation LSquareLoc, RSquareLoc;
1712
1713 /// The bindings.
1714 Binding *Bindings;
1715 unsigned NumBindings : 31;
1716 unsigned DeleteBindings : 1;
1717
1718 friend class Declarator;
1719
1720public:
1721 DecompositionDeclarator()
1722 : Bindings(nullptr), NumBindings(0), DeleteBindings(false) {}
1723 DecompositionDeclarator(const DecompositionDeclarator &G) = delete;
1724 DecompositionDeclarator &operator=(const DecompositionDeclarator &G) = delete;
1725 ~DecompositionDeclarator() {
1726 if (DeleteBindings)
1727 delete[] Bindings;
1728 }
1729
1730 void clear() {
1731 LSquareLoc = RSquareLoc = SourceLocation();
1732 if (DeleteBindings)
1733 delete[] Bindings;
1734 Bindings = nullptr;
1735 NumBindings = 0;
1736 DeleteBindings = false;
1737 }
1738
1739 ArrayRef<Binding> bindings() const {
1740 return llvm::makeArrayRef(Bindings, NumBindings);
1741 }
1742
1743 bool isSet() const { return LSquareLoc.isValid(); }
6
Calling 'SourceLocation::isValid'
9
Returning from 'SourceLocation::isValid'
10
Returning zero, which participates in a condition later
1744
1745 SourceLocation getLSquareLoc() const { return LSquareLoc; }
1746 SourceLocation getRSquareLoc() const { return RSquareLoc; }
1747 SourceRange getSourceRange() const {
1748 return SourceRange(LSquareLoc, RSquareLoc);
1749 }
1750};
1751
1752/// Described the kind of function definition (if any) provided for
1753/// a function.
1754enum class FunctionDefinitionKind {
1755 Declaration,
1756 Definition,
1757 Defaulted,
1758 Deleted
1759};
1760
1761enum class DeclaratorContext {
1762 File, // File scope declaration.
1763 Prototype, // Within a function prototype.
1764 ObjCResult, // An ObjC method result type.
1765 ObjCParameter, // An ObjC method parameter type.
1766 KNRTypeList, // K&R type definition list for formals.
1767 TypeName, // Abstract declarator for types.
1768 FunctionalCast, // Type in a C++ functional cast expression.
1769 Member, // Struct/Union field.
1770 Block, // Declaration within a block in a function.
1771 ForInit, // Declaration within first part of a for loop.
1772 SelectionInit, // Declaration within optional init stmt of if/switch.
1773 Condition, // Condition declaration in a C++ if/switch/while/for.
1774 TemplateParam, // Within a template parameter list.
1775 CXXNew, // C++ new-expression.
1776 CXXCatch, // C++ catch exception-declaration
1777 ObjCCatch, // Objective-C catch exception-declaration
1778 BlockLiteral, // Block literal declarator.
1779 LambdaExpr, // Lambda-expression declarator.
1780 LambdaExprParameter, // Lambda-expression parameter declarator.
1781 ConversionId, // C++ conversion-type-id.
1782 TrailingReturn, // C++11 trailing-type-specifier.
1783 TrailingReturnVar, // C++11 trailing-type-specifier for variable.
1784 TemplateArg, // Any template argument (in template argument list).
1785 TemplateTypeArg, // Template type argument (in default argument).
1786 AliasDecl, // C++11 alias-declaration.
1787 AliasTemplate, // C++11 alias-declaration template.
1788 RequiresExpr // C++2a requires-expression.
1789};
1790
1791/// Information about one declarator, including the parsed type
1792/// information and the identifier.
1793///
1794/// When the declarator is fully formed, this is turned into the appropriate
1795/// Decl object.
1796///
1797/// Declarators come in two types: normal declarators and abstract declarators.
1798/// Abstract declarators are used when parsing types, and don't have an
1799/// identifier. Normal declarators do have ID's.
1800///
1801/// Instances of this class should be a transient object that lives on the
1802/// stack, not objects that are allocated in large quantities on the heap.
1803class Declarator {
1804
1805private:
1806 const DeclSpec &DS;
1807 CXXScopeSpec SS;
1808 UnqualifiedId Name;
1809 SourceRange Range;
1810
1811 /// Where we are parsing this declarator.
1812 DeclaratorContext Context;
1813
1814 /// The C++17 structured binding, if any. This is an alternative to a Name.
1815 DecompositionDeclarator BindingGroup;
1816
1817 /// DeclTypeInfo - This holds each type that the declarator includes as it is
1818 /// parsed. This is pushed from the identifier out, which means that element
1819 /// #0 will be the most closely bound to the identifier, and
1820 /// DeclTypeInfo.back() will be the least closely bound.
1821 SmallVector<DeclaratorChunk, 8> DeclTypeInfo;
1822
1823 /// InvalidType - Set by Sema::GetTypeForDeclarator().
1824 unsigned InvalidType : 1;
1825
1826 /// GroupingParens - Set by Parser::ParseParenDeclarator().
1827 unsigned GroupingParens : 1;
1828
1829 /// FunctionDefinition - Is this Declarator for a function or member
1830 /// definition and, if so, what kind?
1831 ///
1832 /// Actually a FunctionDefinitionKind.
1833 unsigned FunctionDefinition : 2;
1834
1835 /// Is this Declarator a redeclaration?
1836 unsigned Redeclaration : 1;
1837
1838 /// true if the declaration is preceded by \c __extension__.
1839 unsigned Extension : 1;
1840
1841 /// Indicates whether this is an Objective-C instance variable.
1842 unsigned ObjCIvar : 1;
1843
1844 /// Indicates whether this is an Objective-C 'weak' property.
1845 unsigned ObjCWeakProperty : 1;
1846
1847 /// Indicates whether the InlineParams / InlineBindings storage has been used.
1848 unsigned InlineStorageUsed : 1;
1849
1850 /// Indicates whether this declarator has an initializer.
1851 unsigned HasInitializer : 1;
1852
1853 /// Attrs - Attributes.
1854 ParsedAttributes Attrs;
1855
1856 /// The asm label, if specified.
1857 Expr *AsmLabel;
1858
1859 /// \brief The constraint-expression specified by the trailing
1860 /// requires-clause, or null if no such clause was specified.
1861 Expr *TrailingRequiresClause;
1862
1863 /// If this declarator declares a template, its template parameter lists.
1864 ArrayRef<TemplateParameterList *> TemplateParameterLists;
1865
1866 /// If the declarator declares an abbreviated function template, the innermost
1867 /// template parameter list containing the invented and explicit template
1868 /// parameters (if any).
1869 TemplateParameterList *InventedTemplateParameterList;
1870
1871#ifndef _MSC_VER
1872 union {
1873#endif
1874 /// InlineParams - This is a local array used for the first function decl
1875 /// chunk to avoid going to the heap for the common case when we have one
1876 /// function chunk in the declarator.
1877 DeclaratorChunk::ParamInfo InlineParams[16];
1878 DecompositionDeclarator::Binding InlineBindings[16];
1879#ifndef _MSC_VER
1880 };
1881#endif
1882
1883 /// If this is the second or subsequent declarator in this declaration,
1884 /// the location of the comma before this declarator.
1885 SourceLocation CommaLoc;
1886
1887 /// If provided, the source location of the ellipsis used to describe
1888 /// this declarator as a parameter pack.
1889 SourceLocation EllipsisLoc;
1890
1891 friend struct DeclaratorChunk;
1892
1893public:
1894 Declarator(const DeclSpec &ds, DeclaratorContext C)
1895 : DS(ds), Range(ds.getSourceRange()), Context(C),
1896 InvalidType(DS.getTypeSpecType() == DeclSpec::TST_error),
1897 GroupingParens(false), FunctionDefinition(static_cast<unsigned>(
1898 FunctionDefinitionKind::Declaration)),
1899 Redeclaration(false), Extension(false), ObjCIvar(false),
1900 ObjCWeakProperty(false), InlineStorageUsed(false),
1901 HasInitializer(false), Attrs(ds.getAttributePool().getFactory()),
1902 AsmLabel(nullptr), TrailingRequiresClause(nullptr),
1903 InventedTemplateParameterList(nullptr) {}
1904
1905 ~Declarator() {
1906 clear();
1907 }
1908 /// getDeclSpec - Return the declaration-specifier that this declarator was
1909 /// declared with.
1910 const DeclSpec &getDeclSpec() const { return DS; }
1911
1912 /// getMutableDeclSpec - Return a non-const version of the DeclSpec. This
1913 /// should be used with extreme care: declspecs can often be shared between
1914 /// multiple declarators, so mutating the DeclSpec affects all of the
1915 /// Declarators. This should only be done when the declspec is known to not
1916 /// be shared or when in error recovery etc.
1917 DeclSpec &getMutableDeclSpec() { return const_cast<DeclSpec &>(DS); }
1918
1919 AttributePool &getAttributePool() const {
1920 return Attrs.getPool();
1921 }
1922
1923 /// getCXXScopeSpec - Return the C++ scope specifier (global scope or
1924 /// nested-name-specifier) that is part of the declarator-id.
1925 const CXXScopeSpec &getCXXScopeSpec() const { return SS; }
1926 CXXScopeSpec &getCXXScopeSpec() { return SS; }
1927
1928 /// Retrieve the name specified by this declarator.
1929 UnqualifiedId &getName() { return Name; }
1930
1931 const DecompositionDeclarator &getDecompositionDeclarator() const {
1932 return BindingGroup;
1933 }
1934
1935 DeclaratorContext getContext() const { return Context; }
1936
1937 bool isPrototypeContext() const {
1938 return (Context == DeclaratorContext::Prototype ||
1939 Context == DeclaratorContext::ObjCParameter ||
1940 Context == DeclaratorContext::ObjCResult ||
1941 Context == DeclaratorContext::LambdaExprParameter);
1942 }
1943
1944 /// Get the source range that spans this declarator.
1945 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) { return Range; }
1946 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getBegin(); }
1947 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getEnd(); }
1948
1949 void SetSourceRange(SourceRange R) { Range = R; }
1950 /// SetRangeBegin - Set the start of the source range to Loc, unless it's
1951 /// invalid.
1952 void SetRangeBegin(SourceLocation Loc) {
1953 if (!Loc.isInvalid())
1954 Range.setBegin(Loc);
1955 }
1956 /// SetRangeEnd - Set the end of the source range to Loc, unless it's invalid.
1957 void SetRangeEnd(SourceLocation Loc) {
1958 if (!Loc.isInvalid())
1959 Range.setEnd(Loc);
1960 }
1961 /// ExtendWithDeclSpec - Extend the declarator source range to include the
1962 /// given declspec, unless its location is invalid. Adopts the range start if
1963 /// the current range start is invalid.
1964 void ExtendWithDeclSpec(const DeclSpec &DS) {
1965 SourceRange SR = DS.getSourceRange();
1966 if (Range.getBegin().isInvalid())
1967 Range.setBegin(SR.getBegin());
1968 if (!SR.getEnd().isInvalid())
1969 Range.setEnd(SR.getEnd());
1970 }
1971
1972 /// Reset the contents of this Declarator.
1973 void clear() {
1974 SS.clear();
1975 Name.clear();
1976 Range = DS.getSourceRange();
1977 BindingGroup.clear();
1978
1979 for (unsigned i = 0, e = DeclTypeInfo.size(); i != e; ++i)
1980 DeclTypeInfo[i].destroy();
1981 DeclTypeInfo.clear();
1982 Attrs.clear();
1983 AsmLabel = nullptr;
1984 InlineStorageUsed = false;
1985 HasInitializer = false;
1986 ObjCIvar = false;
1987 ObjCWeakProperty = false;
1988 CommaLoc = SourceLocation();
1989 EllipsisLoc = SourceLocation();
1990 }
1991
1992 /// mayOmitIdentifier - Return true if the identifier is either optional or
1993 /// not allowed. This is true for typenames, prototypes, and template
1994 /// parameter lists.
1995 bool mayOmitIdentifier() const {
1996 switch (Context) {
1997 case DeclaratorContext::File:
1998 case DeclaratorContext::KNRTypeList:
1999 case DeclaratorContext::Member:
2000 case DeclaratorContext::Block:
2001 case DeclaratorContext::ForInit:
2002 case DeclaratorContext::SelectionInit:
2003 case DeclaratorContext::Condition:
2004 return false;
2005
2006 case DeclaratorContext::TypeName:
2007 case DeclaratorContext::FunctionalCast:
2008 case DeclaratorContext::AliasDecl:
2009 case DeclaratorContext::AliasTemplate:
2010 case DeclaratorContext::Prototype:
2011 case DeclaratorContext::LambdaExprParameter:
2012 case DeclaratorContext::ObjCParameter:
2013 case DeclaratorContext::ObjCResult:
2014 case DeclaratorContext::TemplateParam:
2015 case DeclaratorContext::CXXNew:
2016 case DeclaratorContext::CXXCatch:
2017 case DeclaratorContext::ObjCCatch:
2018 case DeclaratorContext::BlockLiteral:
2019 case DeclaratorContext::LambdaExpr:
2020 case DeclaratorContext::ConversionId:
2021 case DeclaratorContext::TemplateArg:
2022 case DeclaratorContext::TemplateTypeArg:
2023 case DeclaratorContext::TrailingReturn:
2024 case DeclaratorContext::TrailingReturnVar:
2025 case DeclaratorContext::RequiresExpr:
2026 return true;
2027 }
2028 llvm_unreachable("unknown context kind!")::llvm::llvm_unreachable_internal("unknown context kind!", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Sema/DeclSpec.h"
, 2028)
;
2029 }
2030
2031 /// mayHaveIdentifier - Return true if the identifier is either optional or
2032 /// required. This is true for normal declarators and prototypes, but not
2033 /// typenames.
2034 bool mayHaveIdentifier() const {
2035 switch (Context) {
2036 case DeclaratorContext::File:
2037 case DeclaratorContext::KNRTypeList:
2038 case DeclaratorContext::Member:
2039 case DeclaratorContext::Block:
2040 case DeclaratorContext::ForInit:
2041 case DeclaratorContext::SelectionInit:
2042 case DeclaratorContext::Condition:
2043 case DeclaratorContext::Prototype:
2044 case DeclaratorContext::LambdaExprParameter:
2045 case DeclaratorContext::TemplateParam:
2046 case DeclaratorContext::CXXCatch:
2047 case DeclaratorContext::ObjCCatch:
2048 case DeclaratorContext::RequiresExpr:
2049 return true;
2050
2051 case DeclaratorContext::TypeName:
2052 case DeclaratorContext::FunctionalCast:
2053 case DeclaratorContext::CXXNew:
2054 case DeclaratorContext::AliasDecl:
2055 case DeclaratorContext::AliasTemplate:
2056 case DeclaratorContext::ObjCParameter:
2057 case DeclaratorContext::ObjCResult:
2058 case DeclaratorContext::BlockLiteral:
2059 case DeclaratorContext::LambdaExpr:
2060 case DeclaratorContext::ConversionId:
2061 case DeclaratorContext::TemplateArg:
2062 case DeclaratorContext::TemplateTypeArg:
2063 case DeclaratorContext::TrailingReturn:
2064 case DeclaratorContext::TrailingReturnVar:
2065 return false;
2066 }
2067 llvm_unreachable("unknown context kind!")::llvm::llvm_unreachable_internal("unknown context kind!", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Sema/DeclSpec.h"
, 2067)
;
2068 }
2069
2070 /// Return true if the context permits a C++17 decomposition declarator.
2071 bool mayHaveDecompositionDeclarator() const {
2072 switch (Context) {
2073 case DeclaratorContext::File:
2074 // FIXME: It's not clear that the proposal meant to allow file-scope
2075 // structured bindings, but it does.
2076 case DeclaratorContext::Block:
2077 case DeclaratorContext::ForInit:
2078 case DeclaratorContext::SelectionInit:
2079 case DeclaratorContext::Condition:
2080 return true;
2081
2082 case DeclaratorContext::Member:
2083 case DeclaratorContext::Prototype:
2084 case DeclaratorContext::TemplateParam:
2085 case DeclaratorContext::RequiresExpr:
2086 // Maybe one day...
2087 return false;
2088
2089 // These contexts don't allow any kind of non-abstract declarator.
2090 case DeclaratorContext::KNRTypeList:
2091 case DeclaratorContext::TypeName:
2092 case DeclaratorContext::FunctionalCast:
2093 case DeclaratorContext::AliasDecl:
2094 case DeclaratorContext::AliasTemplate:
2095 case DeclaratorContext::LambdaExprParameter:
2096 case DeclaratorContext::ObjCParameter:
2097 case DeclaratorContext::ObjCResult:
2098 case DeclaratorContext::CXXNew:
2099 case DeclaratorContext::CXXCatch:
2100 case DeclaratorContext::ObjCCatch:
2101 case DeclaratorContext::BlockLiteral:
2102 case DeclaratorContext::LambdaExpr:
2103 case DeclaratorContext::ConversionId:
2104 case DeclaratorContext::TemplateArg:
2105 case DeclaratorContext::TemplateTypeArg:
2106 case DeclaratorContext::TrailingReturn:
2107 case DeclaratorContext::TrailingReturnVar:
2108 return false;
2109 }
2110 llvm_unreachable("unknown context kind!")::llvm::llvm_unreachable_internal("unknown context kind!", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Sema/DeclSpec.h"
, 2110)
;
2111 }
2112
2113 /// mayBeFollowedByCXXDirectInit - Return true if the declarator can be
2114 /// followed by a C++ direct initializer, e.g. "int x(1);".
2115 bool mayBeFollowedByCXXDirectInit() const {
2116 if (hasGroupingParens()) return false;
2117
2118 if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2119 return false;
2120
2121 if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern &&
2122 Context != DeclaratorContext::File)
2123 return false;
2124
2125 // Special names can't have direct initializers.
2126 if (Name.getKind() != UnqualifiedIdKind::IK_Identifier)
2127 return false;
2128
2129 switch (Context) {
2130 case DeclaratorContext::File:
2131 case DeclaratorContext::Block:
2132 case DeclaratorContext::ForInit:
2133 case DeclaratorContext::SelectionInit:
2134 case DeclaratorContext::TrailingReturnVar:
2135 return true;
2136
2137 case DeclaratorContext::Condition:
2138 // This may not be followed by a direct initializer, but it can't be a
2139 // function declaration either, and we'd prefer to perform a tentative
2140 // parse in order to produce the right diagnostic.
2141 return true;
2142
2143 case DeclaratorContext::KNRTypeList:
2144 case DeclaratorContext::Member:
2145 case DeclaratorContext::Prototype:
2146 case DeclaratorContext::LambdaExprParameter:
2147 case DeclaratorContext::ObjCParameter:
2148 case DeclaratorContext::ObjCResult:
2149 case DeclaratorContext::TemplateParam:
2150 case DeclaratorContext::CXXCatch:
2151 case DeclaratorContext::ObjCCatch:
2152 case DeclaratorContext::TypeName:
2153 case DeclaratorContext::FunctionalCast: // FIXME
2154 case DeclaratorContext::CXXNew:
2155 case DeclaratorContext::AliasDecl:
2156 case DeclaratorContext::AliasTemplate:
2157 case DeclaratorContext::BlockLiteral:
2158 case DeclaratorContext::LambdaExpr:
2159 case DeclaratorContext::ConversionId:
2160 case DeclaratorContext::TemplateArg:
2161 case DeclaratorContext::TemplateTypeArg:
2162 case DeclaratorContext::TrailingReturn:
2163 case DeclaratorContext::RequiresExpr:
2164 return false;
2165 }
2166 llvm_unreachable("unknown context kind!")::llvm::llvm_unreachable_internal("unknown context kind!", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Sema/DeclSpec.h"
, 2166)
;
2167 }
2168
2169 /// isPastIdentifier - Return true if we have parsed beyond the point where
2170 /// the name would appear. (This may happen even if we haven't actually parsed
2171 /// a name, perhaps because this context doesn't require one.)
2172 bool isPastIdentifier() const { return Name.isValid(); }
2173
2174 /// hasName - Whether this declarator has a name, which might be an
2175 /// identifier (accessible via getIdentifier()) or some kind of
2176 /// special C++ name (constructor, destructor, etc.), or a structured
2177 /// binding (which is not exactly a name, but occupies the same position).
2178 bool hasName() const {
2179 return Name.getKind() != UnqualifiedIdKind::IK_Identifier ||
2180 Name.Identifier || isDecompositionDeclarator();
2181 }
2182
2183 /// Return whether this declarator is a decomposition declarator.
2184 bool isDecompositionDeclarator() const {
2185 return BindingGroup.isSet();
5
Calling 'DecompositionDeclarator::isSet'
11
Returning from 'DecompositionDeclarator::isSet'
12
Returning zero, which participates in a condition later
2186 }
2187
2188 IdentifierInfo *getIdentifier() const {
2189 if (Name.getKind() == UnqualifiedIdKind::IK_Identifier)
2190 return Name.Identifier;
2191
2192 return nullptr;
2193 }
2194 SourceLocation getIdentifierLoc() const { return Name.StartLocation; }
2195
2196 /// Set the name of this declarator to be the given identifier.
2197 void SetIdentifier(IdentifierInfo *Id, SourceLocation IdLoc) {
2198 Name.setIdentifier(Id, IdLoc);
2199 }
2200
2201 /// Set the decomposition bindings for this declarator.
2202 void
2203 setDecompositionBindings(SourceLocation LSquareLoc,
2204 ArrayRef<DecompositionDeclarator::Binding> Bindings,
2205 SourceLocation RSquareLoc);
2206
2207 /// AddTypeInfo - Add a chunk to this declarator. Also extend the range to
2208 /// EndLoc, which should be the last token of the chunk.
2209 /// This function takes attrs by R-Value reference because it takes ownership
2210 /// of those attributes from the parameter.
2211 void AddTypeInfo(const DeclaratorChunk &TI, ParsedAttributes &&attrs,
2212 SourceLocation EndLoc) {
2213 DeclTypeInfo.push_back(TI);
2214 DeclTypeInfo.back().getAttrs().addAll(attrs.begin(), attrs.end());
2215 getAttributePool().takeAllFrom(attrs.getPool());
2216
2217 if (!EndLoc.isInvalid())
2218 SetRangeEnd(EndLoc);
2219 }
2220
2221 /// AddTypeInfo - Add a chunk to this declarator. Also extend the range to
2222 /// EndLoc, which should be the last token of the chunk.
2223 void AddTypeInfo(const DeclaratorChunk &TI, SourceLocation EndLoc) {
2224 DeclTypeInfo.push_back(TI);
2225
2226 if (!EndLoc.isInvalid())
2227 SetRangeEnd(EndLoc);
2228 }
2229
2230 /// Add a new innermost chunk to this declarator.
2231 void AddInnermostTypeInfo(const DeclaratorChunk &TI) {
2232 DeclTypeInfo.insert(DeclTypeInfo.begin(), TI);
2233 }
2234
2235 /// Return the number of types applied to this declarator.
2236 unsigned getNumTypeObjects() const { return DeclTypeInfo.size(); }
2237
2238 /// Return the specified TypeInfo from this declarator. TypeInfo #0 is
2239 /// closest to the identifier.
2240 const DeclaratorChunk &getTypeObject(unsigned i) const {
2241 assert(i < DeclTypeInfo.size() && "Invalid type chunk")((i < DeclTypeInfo.size() && "Invalid type chunk")
? static_cast<void> (0) : __assert_fail ("i < DeclTypeInfo.size() && \"Invalid type chunk\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Sema/DeclSpec.h"
, 2241, __PRETTY_FUNCTION__))
;
2242 return DeclTypeInfo[i];
2243 }
2244 DeclaratorChunk &getTypeObject(unsigned i) {
2245 assert(i < DeclTypeInfo.size() && "Invalid type chunk")((i < DeclTypeInfo.size() && "Invalid type chunk")
? static_cast<void> (0) : __assert_fail ("i < DeclTypeInfo.size() && \"Invalid type chunk\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Sema/DeclSpec.h"
, 2245, __PRETTY_FUNCTION__))
;
2246 return DeclTypeInfo[i];
2247 }
2248
2249 typedef SmallVectorImpl<DeclaratorChunk>::const_iterator type_object_iterator;
2250 typedef llvm::iterator_range<type_object_iterator> type_object_range;
2251
2252 /// Returns the range of type objects, from the identifier outwards.
2253 type_object_range type_objects() const {
2254 return type_object_range(DeclTypeInfo.begin(), DeclTypeInfo.end());
2255 }
2256
2257 void DropFirstTypeObject() {
2258 assert(!DeclTypeInfo.empty() && "No type chunks to drop.")((!DeclTypeInfo.empty() && "No type chunks to drop.")
? static_cast<void> (0) : __assert_fail ("!DeclTypeInfo.empty() && \"No type chunks to drop.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Sema/DeclSpec.h"
, 2258, __PRETTY_FUNCTION__))
;
2259 DeclTypeInfo.front().destroy();
2260 DeclTypeInfo.erase(DeclTypeInfo.begin());
2261 }
2262
2263 /// Return the innermost (closest to the declarator) chunk of this
2264 /// declarator that is not a parens chunk, or null if there are no
2265 /// non-parens chunks.
2266 const DeclaratorChunk *getInnermostNonParenChunk() const {
2267 for (unsigned i = 0, i_end = DeclTypeInfo.size(); i < i_end; ++i) {
2268 if (!DeclTypeInfo[i].isParen())
2269 return &DeclTypeInfo[i];
2270 }
2271 return nullptr;
2272 }
2273
2274 /// Return the outermost (furthest from the declarator) chunk of
2275 /// this declarator that is not a parens chunk, or null if there are
2276 /// no non-parens chunks.
2277 const DeclaratorChunk *getOutermostNonParenChunk() const {
2278 for (unsigned i = DeclTypeInfo.size(), i_end = 0; i != i_end; --i) {
2279 if (!DeclTypeInfo[i-1].isParen())
2280 return &DeclTypeInfo[i-1];
2281 }
2282 return nullptr;
2283 }
2284
2285 /// isArrayOfUnknownBound - This method returns true if the declarator
2286 /// is a declarator for an array of unknown bound (looking through
2287 /// parentheses).
2288 bool isArrayOfUnknownBound() const {
2289 const DeclaratorChunk *chunk = getInnermostNonParenChunk();
2290 return (chunk && chunk->Kind == DeclaratorChunk::Array &&
2291 !chunk->Arr.NumElts);
2292 }
2293
2294 /// isFunctionDeclarator - This method returns true if the declarator
2295 /// is a function declarator (looking through parentheses).
2296 /// If true is returned, then the reference type parameter idx is
2297 /// assigned with the index of the declaration chunk.
2298 bool isFunctionDeclarator(unsigned& idx) const {
2299 for (unsigned i = 0, i_end = DeclTypeInfo.size(); i < i_end; ++i) {
2300 switch (DeclTypeInfo[i].Kind) {
2301 case DeclaratorChunk::Function:
2302 idx = i;
2303 return true;
2304 case DeclaratorChunk::Paren:
2305 continue;
2306 case DeclaratorChunk::Pointer:
2307 case DeclaratorChunk::Reference:
2308 case DeclaratorChunk::Array:
2309 case DeclaratorChunk::BlockPointer:
2310 case DeclaratorChunk::MemberPointer:
2311 case DeclaratorChunk::Pipe:
2312 return false;
2313 }
2314 llvm_unreachable("Invalid type chunk")::llvm::llvm_unreachable_internal("Invalid type chunk", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Sema/DeclSpec.h"
, 2314)
;
2315 }
2316 return false;
2317 }
2318
2319 /// isFunctionDeclarator - Once this declarator is fully parsed and formed,
2320 /// this method returns true if the identifier is a function declarator
2321 /// (looking through parentheses).
2322 bool isFunctionDeclarator() const {
2323 unsigned index;
2324 return isFunctionDeclarator(index);
2325 }
2326
2327 /// getFunctionTypeInfo - Retrieves the function type info object
2328 /// (looking through parentheses).
2329 DeclaratorChunk::FunctionTypeInfo &getFunctionTypeInfo() {
2330 assert(isFunctionDeclarator() && "Not a function declarator!")((isFunctionDeclarator() && "Not a function declarator!"
) ? static_cast<void> (0) : __assert_fail ("isFunctionDeclarator() && \"Not a function declarator!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Sema/DeclSpec.h"
, 2330, __PRETTY_FUNCTION__))
;
2331 unsigned index = 0;
2332 isFunctionDeclarator(index);
2333 return DeclTypeInfo[index].Fun;
2334 }
2335
2336 /// getFunctionTypeInfo - Retrieves the function type info object
2337 /// (looking through parentheses).
2338 const DeclaratorChunk::FunctionTypeInfo &getFunctionTypeInfo() const {
2339 return const_cast<Declarator*>(this)->getFunctionTypeInfo();
2340 }
2341
2342 /// Determine whether the declaration that will be produced from
2343 /// this declaration will be a function.
2344 ///
2345 /// A declaration can declare a function even if the declarator itself
2346 /// isn't a function declarator, if the type specifier refers to a function
2347 /// type. This routine checks for both cases.
2348 bool isDeclarationOfFunction() const;
2349
2350 /// Return true if this declaration appears in a context where a
2351 /// function declarator would be a function declaration.
2352 bool isFunctionDeclarationContext() const {
2353 if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2354 return false;
2355
2356 switch (Context) {
2357 case DeclaratorContext::File:
2358 case DeclaratorContext::Member:
2359 case DeclaratorContext::Block:
2360 case DeclaratorContext::ForInit:
2361 case DeclaratorContext::SelectionInit:
2362 return true;
2363
2364 case DeclaratorContext::Condition:
2365 case DeclaratorContext::KNRTypeList:
2366 case DeclaratorContext::TypeName:
2367 case DeclaratorContext::FunctionalCast:
2368 case DeclaratorContext::AliasDecl:
2369 case DeclaratorContext::AliasTemplate:
2370 case DeclaratorContext::Prototype:
2371 case DeclaratorContext::LambdaExprParameter:
2372 case DeclaratorContext::ObjCParameter:
2373 case DeclaratorContext::ObjCResult:
2374 case DeclaratorContext::TemplateParam:
2375 case DeclaratorContext::CXXNew:
2376 case DeclaratorContext::CXXCatch:
2377 case DeclaratorContext::ObjCCatch:
2378 case DeclaratorContext::BlockLiteral:
2379 case DeclaratorContext::LambdaExpr:
2380 case DeclaratorContext::ConversionId:
2381 case DeclaratorContext::TemplateArg:
2382 case DeclaratorContext::TemplateTypeArg:
2383 case DeclaratorContext::TrailingReturn:
2384 case DeclaratorContext::TrailingReturnVar:
2385 case DeclaratorContext::RequiresExpr:
2386 return false;
2387 }
2388 llvm_unreachable("unknown context kind!")::llvm::llvm_unreachable_internal("unknown context kind!", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Sema/DeclSpec.h"
, 2388)
;
2389 }
2390
2391 /// Determine whether this declaration appears in a context where an
2392 /// expression could appear.
2393 bool isExpressionContext() const {
2394 switch (Context) {
2395 case DeclaratorContext::File:
2396 case DeclaratorContext::KNRTypeList:
2397 case DeclaratorContext::Member:
2398
2399 // FIXME: sizeof(...) permits an expression.
2400 case DeclaratorContext::TypeName:
2401
2402 case DeclaratorContext::FunctionalCast:
2403 case DeclaratorContext::AliasDecl:
2404 case DeclaratorContext::AliasTemplate:
2405 case DeclaratorContext::Prototype:
2406 case DeclaratorContext::LambdaExprParameter:
2407 case DeclaratorContext::ObjCParameter:
2408 case DeclaratorContext::ObjCResult:
2409 case DeclaratorContext::TemplateParam:
2410 case DeclaratorContext::CXXNew:
2411 case DeclaratorContext::CXXCatch:
2412 case DeclaratorContext::ObjCCatch:
2413 case DeclaratorContext::BlockLiteral:
2414 case DeclaratorContext::LambdaExpr:
2415 case DeclaratorContext::ConversionId:
2416 case DeclaratorContext::TrailingReturn:
2417 case DeclaratorContext::TrailingReturnVar:
2418 case DeclaratorContext::TemplateTypeArg:
2419 case DeclaratorContext::RequiresExpr:
2420 return false;
2421
2422 case DeclaratorContext::Block:
2423 case DeclaratorContext::ForInit:
2424 case DeclaratorContext::SelectionInit:
2425 case DeclaratorContext::Condition:
2426 case DeclaratorContext::TemplateArg:
2427 return true;
2428 }
2429
2430 llvm_unreachable("unknown context kind!")::llvm::llvm_unreachable_internal("unknown context kind!", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Sema/DeclSpec.h"
, 2430)
;
2431 }
2432
2433 /// Return true if a function declarator at this position would be a
2434 /// function declaration.
2435 bool isFunctionDeclaratorAFunctionDeclaration() const {
2436 if (!isFunctionDeclarationContext())
2437 return false;
2438
2439 for (unsigned I = 0, N = getNumTypeObjects(); I != N; ++I)
2440 if (getTypeObject(I).Kind != DeclaratorChunk::Paren)
2441 return false;
2442
2443 return true;
2444 }
2445
2446 /// Determine whether a trailing return type was written (at any
2447 /// level) within this declarator.
2448 bool hasTrailingReturnType() const {
2449 for (const auto &Chunk : type_objects())
2450 if (Chunk.Kind == DeclaratorChunk::Function &&
2451 Chunk.Fun.hasTrailingReturnType())
2452 return true;
2453 return false;
2454 }
2455 /// Get the trailing return type appearing (at any level) within this
2456 /// declarator.
2457 ParsedType getTrailingReturnType() const {
2458 for (const auto &Chunk : type_objects())
2459 if (Chunk.Kind == DeclaratorChunk::Function &&
2460 Chunk.Fun.hasTrailingReturnType())
2461 return Chunk.Fun.getTrailingReturnType();
2462 return ParsedType();
2463 }
2464
2465 /// \brief Sets a trailing requires clause for this declarator.
2466 void setTrailingRequiresClause(Expr *TRC) {
2467 TrailingRequiresClause = TRC;
2468
2469 SetRangeEnd(TRC->getEndLoc());
2470 }
2471
2472 /// \brief Sets a trailing requires clause for this declarator.
2473 Expr *getTrailingRequiresClause() {
2474 return TrailingRequiresClause;
2475 }
2476
2477 /// \brief Determine whether a trailing requires clause was written in this
2478 /// declarator.
2479 bool hasTrailingRequiresClause() const {
2480 return TrailingRequiresClause != nullptr;
2481 }
2482
2483 /// Sets the template parameter lists that preceded the declarator.
2484 void setTemplateParameterLists(ArrayRef<TemplateParameterList *> TPLs) {
2485 TemplateParameterLists = TPLs;
2486 }
2487
2488 /// The template parameter lists that preceded the declarator.
2489 ArrayRef<TemplateParameterList *> getTemplateParameterLists() const {
2490 return TemplateParameterLists;
2491 }
2492
2493 /// Sets the template parameter list generated from the explicit template
2494 /// parameters along with any invented template parameters from
2495 /// placeholder-typed parameters.
2496 void setInventedTemplateParameterList(TemplateParameterList *Invented) {
2497 InventedTemplateParameterList = Invented;
2498 }
2499
2500 /// The template parameter list generated from the explicit template
2501 /// parameters along with any invented template parameters from
2502 /// placeholder-typed parameters, if there were any such parameters.
2503 TemplateParameterList * getInventedTemplateParameterList() const {
2504 return InventedTemplateParameterList;
2505 }
2506
2507 /// takeAttributes - Takes attributes from the given parsed-attributes
2508 /// set and add them to this declarator.
2509 ///
2510 /// These examples both add 3 attributes to "var":
2511 /// short int var __attribute__((aligned(16),common,deprecated));
2512 /// short int x, __attribute__((aligned(16)) var
2513 /// __attribute__((common,deprecated));
2514 ///
2515 /// Also extends the range of the declarator.
2516 void takeAttributes(ParsedAttributes &attrs, SourceLocation lastLoc) {
2517 Attrs.takeAllFrom(attrs);
2518
2519 if (!lastLoc.isInvalid())
2520 SetRangeEnd(lastLoc);
2521 }
2522
2523 const ParsedAttributes &getAttributes() const { return Attrs; }
2524 ParsedAttributes &getAttributes() { return Attrs; }
2525
2526 /// hasAttributes - do we contain any attributes?
2527 bool hasAttributes() const {
2528 if (!getAttributes().empty() || getDeclSpec().hasAttributes())
2529 return true;
2530 for (unsigned i = 0, e = getNumTypeObjects(); i != e; ++i)
2531 if (!getTypeObject(i).getAttrs().empty())
2532 return true;
2533 return false;
2534 }
2535
2536 /// Return a source range list of C++11 attributes associated
2537 /// with the declarator.
2538 void getCXX11AttributeRanges(SmallVectorImpl<SourceRange> &Ranges) {
2539 for (const ParsedAttr &AL : Attrs)
2540 if (AL.isCXX11Attribute())
2541 Ranges.push_back(AL.getRange());
2542 }
2543
2544 void setAsmLabel(Expr *E) { AsmLabel = E; }
2545 Expr *getAsmLabel() const { return AsmLabel; }
2546
2547 void setExtension(bool Val = true) { Extension = Val; }
2548 bool getExtension() const { return Extension; }
2549
2550 void setObjCIvar(bool Val = true) { ObjCIvar = Val; }
2551 bool isObjCIvar() const { return ObjCIvar; }
2552
2553 void setObjCWeakProperty(bool Val = true) { ObjCWeakProperty = Val; }
2554 bool isObjCWeakProperty() const { return ObjCWeakProperty; }
2555
2556 void setInvalidType(bool Val = true) { InvalidType = Val; }
2557 bool isInvalidType() const {
2558 return InvalidType || DS.getTypeSpecType() == DeclSpec::TST_error;
29
Assuming field 'InvalidType' is 0
30
Assuming the condition is false
31
Returning zero, which participates in a condition later
2559 }
2560
2561 void setGroupingParens(bool flag) { GroupingParens = flag; }
2562 bool hasGroupingParens() const { return GroupingParens; }
2563
2564 bool isFirstDeclarator() const { return !CommaLoc.isValid(); }
2565 SourceLocation getCommaLoc() const { return CommaLoc; }
2566 void setCommaLoc(SourceLocation CL) { CommaLoc = CL; }
2567
2568 bool hasEllipsis() const { return EllipsisLoc.isValid(); }
2569 SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
2570 void setEllipsisLoc(SourceLocation EL) { EllipsisLoc = EL; }
2571
2572 void setFunctionDefinitionKind(FunctionDefinitionKind Val) {
2573 FunctionDefinition = static_cast<unsigned>(Val);
2574 }
2575
2576 bool isFunctionDefinition() const {
2577 return getFunctionDefinitionKind() != FunctionDefinitionKind::Declaration;
2578 }
2579
2580 FunctionDefinitionKind getFunctionDefinitionKind() const {
2581 return (FunctionDefinitionKind)FunctionDefinition;
2582 }
2583
2584 void setHasInitializer(bool Val = true) { HasInitializer = Val; }
2585 bool hasInitializer() const { return HasInitializer; }
2586
2587 /// Returns true if this declares a real member and not a friend.
2588 bool isFirstDeclarationOfMember() {
2589 return getContext() == DeclaratorContext::Member &&
2590 !getDeclSpec().isFriendSpecified();
2591 }
2592
2593 /// Returns true if this declares a static member. This cannot be called on a
2594 /// declarator outside of a MemberContext because we won't know until
2595 /// redeclaration time if the decl is static.
2596 bool isStaticMember();
2597
2598 /// Returns true if this declares a constructor or a destructor.
2599 bool isCtorOrDtor();
2600
2601 void setRedeclaration(bool Val) { Redeclaration = Val; }
2602 bool isRedeclaration() const { return Redeclaration; }
2603};
2604
2605/// This little struct is used to capture information about
2606/// structure field declarators, which is basically just a bitfield size.
2607struct FieldDeclarator {
2608 Declarator D;
2609 Expr *BitfieldSize;
2610 explicit FieldDeclarator(const DeclSpec &DS)
2611 : D(DS, DeclaratorContext::Member), BitfieldSize(nullptr) {}
2612};
2613
2614/// Represents a C++11 virt-specifier-seq.
2615class VirtSpecifiers {
2616public:
2617 enum Specifier {
2618 VS_None = 0,
2619 VS_Override = 1,
2620 VS_Final = 2,
2621 VS_Sealed = 4,
2622 // Represents the __final keyword, which is legal for gcc in pre-C++11 mode.
2623 VS_GNU_Final = 8
2624 };
2625
2626 VirtSpecifiers() : Specifiers(0), LastSpecifier(VS_None) { }
2627
2628 bool SetSpecifier(Specifier VS, SourceLocation Loc,
2629 const char *&PrevSpec);
2630
2631 bool isUnset() const { return Specifiers == 0; }
2632
2633 bool isOverrideSpecified() const { return Specifiers & VS_Override; }
2634 SourceLocation getOverrideLoc() const { return VS_overrideLoc; }
2635
2636 bool isFinalSpecified() const { return Specifiers & (VS_Final | VS_Sealed | VS_GNU_Final); }
2637 bool isFinalSpelledSealed() const { return Specifiers & VS_Sealed; }
2638 SourceLocation getFinalLoc() const { return VS_finalLoc; }
2639
2640 void clear() { Specifiers = 0; }
2641
2642 static const char *getSpecifierName(Specifier VS);
2643
2644 SourceLocation getFirstLocation() const { return FirstLocation; }
2645 SourceLocation getLastLocation() const { return LastLocation; }
2646 Specifier getLastSpecifier() const { return LastSpecifier; }
2647
2648private:
2649 unsigned Specifiers;
2650 Specifier LastSpecifier;
2651
2652 SourceLocation VS_overrideLoc, VS_finalLoc;
2653 SourceLocation FirstLocation;
2654 SourceLocation LastLocation;
2655};
2656
2657enum class LambdaCaptureInitKind {
2658 NoInit, //!< [a]
2659 CopyInit, //!< [a = b], [a = {b}]
2660 DirectInit, //!< [a(b)]
2661 ListInit //!< [a{b}]
2662};
2663
2664/// Represents a complete lambda introducer.
2665struct LambdaIntroducer {
2666 /// An individual capture in a lambda introducer.
2667 struct LambdaCapture {
2668 LambdaCaptureKind Kind;
2669 SourceLocation Loc;
2670 IdentifierInfo *Id;
2671 SourceLocation EllipsisLoc;
2672 LambdaCaptureInitKind InitKind;
2673 ExprResult Init;
2674 ParsedType InitCaptureType;
2675 SourceRange ExplicitRange;
2676
2677 LambdaCapture(LambdaCaptureKind Kind, SourceLocation Loc,
2678 IdentifierInfo *Id, SourceLocation EllipsisLoc,
2679 LambdaCaptureInitKind InitKind, ExprResult Init,
2680 ParsedType InitCaptureType,
2681 SourceRange ExplicitRange)
2682 : Kind(Kind), Loc(Loc), Id(Id), EllipsisLoc(EllipsisLoc),
2683 InitKind(InitKind), Init(Init), InitCaptureType(InitCaptureType),
2684 ExplicitRange(ExplicitRange) {}
2685 };
2686
2687 SourceRange Range;
2688 SourceLocation DefaultLoc;
2689 LambdaCaptureDefault Default;
2690 SmallVector<LambdaCapture, 4> Captures;
2691
2692 LambdaIntroducer()
2693 : Default(LCD_None) {}
2694
2695 /// Append a capture in a lambda introducer.
2696 void addCapture(LambdaCaptureKind Kind,
2697 SourceLocation Loc,
2698 IdentifierInfo* Id,
2699 SourceLocation EllipsisLoc,
2700 LambdaCaptureInitKind InitKind,
2701 ExprResult Init,
2702 ParsedType InitCaptureType,
2703 SourceRange ExplicitRange) {
2704 Captures.push_back(LambdaCapture(Kind, Loc, Id, EllipsisLoc, InitKind, Init,
2705 InitCaptureType, ExplicitRange));
2706 }
2707};
2708
2709struct InventedTemplateParameterInfo {
2710 /// The number of parameters in the template parameter list that were
2711 /// explicitly specified by the user, as opposed to being invented by use
2712 /// of an auto parameter.
2713 unsigned NumExplicitTemplateParams = 0;
2714
2715 /// If this is a generic lambda or abbreviated function template, use this
2716 /// as the depth of each 'auto' parameter, during initial AST construction.
2717 unsigned AutoTemplateParameterDepth = 0;
2718
2719 /// Store the list of the template parameters for a generic lambda or an
2720 /// abbreviated function template.
2721 /// If this is a generic lambda or abbreviated function template, this holds
2722 /// the explicit template parameters followed by the auto parameters
2723 /// converted into TemplateTypeParmDecls.
2724 /// It can be used to construct the generic lambda or abbreviated template's
2725 /// template parameter list during initial AST construction.
2726 SmallVector<NamedDecl*, 4> TemplateParams;
2727};
2728
2729} // end namespace clang
2730
2731#endif // LLVM_CLANG_SEMA_DECLSPEC_H

/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Basic/SourceLocation.h

1//===- SourceLocation.h - Compact identifier for Source Files ---*- 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/// \file
10/// Defines the clang::SourceLocation class and associated facilities.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_BASIC_SOURCELOCATION_H
15#define LLVM_CLANG_BASIC_SOURCELOCATION_H
16
17#include "clang/Basic/LLVM.h"
18#include "llvm/ADT/StringRef.h"
19#include "llvm/Support/PointerLikeTypeTraits.h"
20#include <cassert>
21#include <cstdint>
22#include <string>
23#include <utility>
24
25namespace llvm {
26
27template <typename T> struct DenseMapInfo;
28
29class FoldingSetNodeID;
30template <typename T> struct FoldingSetTrait;
31
32} // namespace llvm
33
34namespace clang {
35
36class SourceManager;
37
38/// An opaque identifier used by SourceManager which refers to a
39/// source file (MemoryBuffer) along with its \#include path and \#line data.
40///
41class FileID {
42 /// A mostly-opaque identifier, where 0 is "invalid", >0 is
43 /// this module, and <-1 is something loaded from another module.
44 int ID = 0;
45
46public:
47 bool isValid() const { return ID != 0; }
48 bool isInvalid() const { return ID == 0; }
49
50 bool operator==(const FileID &RHS) const { return ID == RHS.ID; }
51 bool operator<(const FileID &RHS) const { return ID < RHS.ID; }
52 bool operator<=(const FileID &RHS) const { return ID <= RHS.ID; }
53 bool operator!=(const FileID &RHS) const { return !(*this == RHS); }
54 bool operator>(const FileID &RHS) const { return RHS < *this; }
55 bool operator>=(const FileID &RHS) const { return RHS <= *this; }
56
57 static FileID getSentinel() { return get(-1); }
58 unsigned getHashValue() const { return static_cast<unsigned>(ID); }
59
60private:
61 friend class ASTWriter;
62 friend class ASTReader;
63 friend class SourceManager;
64
65 static FileID get(int V) {
66 FileID F;
67 F.ID = V;
68 return F;
69 }
70
71 int getOpaqueValue() const { return ID; }
72};
73
74/// Encodes a location in the source. The SourceManager can decode this
75/// to get at the full include stack, line and column information.
76///
77/// Technically, a source location is simply an offset into the manager's view
78/// of the input source, which is all input buffers (including macro
79/// expansions) concatenated in an effectively arbitrary order. The manager
80/// actually maintains two blocks of input buffers. One, starting at offset
81/// 0 and growing upwards, contains all buffers from this module. The other,
82/// starting at the highest possible offset and growing downwards, contains
83/// buffers of loaded modules.
84///
85/// In addition, one bit of SourceLocation is used for quick access to the
86/// information whether the location is in a file or a macro expansion.
87///
88/// It is important that this type remains small. It is currently 32 bits wide.
89class SourceLocation {
90 friend class ASTReader;
91 friend class ASTWriter;
92 friend class SourceManager;
93 friend struct llvm::FoldingSetTrait<SourceLocation>;
94
95 unsigned ID = 0;
96
97 enum : unsigned {
98 MacroIDBit = 1U << 31
99 };
100
101public:
102 bool isFileID() const { return (ID & MacroIDBit) == 0; }
103 bool isMacroID() const { return (ID & MacroIDBit) != 0; }
104
105 /// Return true if this is a valid SourceLocation object.
106 ///
107 /// Invalid SourceLocations are often used when events have no corresponding
108 /// location in the source (e.g. a diagnostic is required for a command line
109 /// option).
110 bool isValid() const { return ID != 0; }
7
Assuming field 'ID' is equal to 0
8
Returning zero, which participates in a condition later
111 bool isInvalid() const { return ID == 0; }
112
113private:
114 /// Return the offset into the manager's global input view.
115 unsigned getOffset() const {
116 return ID & ~MacroIDBit;
117 }
118
119 static SourceLocation getFileLoc(unsigned ID) {
120 assert((ID & MacroIDBit) == 0 && "Ran out of source locations!")(((ID & MacroIDBit) == 0 && "Ran out of source locations!"
) ? static_cast<void> (0) : __assert_fail ("(ID & MacroIDBit) == 0 && \"Ran out of source locations!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Basic/SourceLocation.h"
, 120, __PRETTY_FUNCTION__))
;
121 SourceLocation L;
122 L.ID = ID;
123 return L;
124 }
125
126 static SourceLocation getMacroLoc(unsigned ID) {
127 assert((ID & MacroIDBit) == 0 && "Ran out of source locations!")(((ID & MacroIDBit) == 0 && "Ran out of source locations!"
) ? static_cast<void> (0) : __assert_fail ("(ID & MacroIDBit) == 0 && \"Ran out of source locations!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Basic/SourceLocation.h"
, 127, __PRETTY_FUNCTION__))
;
128 SourceLocation L;
129 L.ID = MacroIDBit | ID;
130 return L;
131 }
132
133public:
134 /// Return a source location with the specified offset from this
135 /// SourceLocation.
136 SourceLocation getLocWithOffset(int Offset) const {
137 assert(((getOffset()+Offset) & MacroIDBit) == 0 && "offset overflow")((((getOffset()+Offset) & MacroIDBit) == 0 && "offset overflow"
) ? static_cast<void> (0) : __assert_fail ("((getOffset()+Offset) & MacroIDBit) == 0 && \"offset overflow\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Basic/SourceLocation.h"
, 137, __PRETTY_FUNCTION__))
;
138 SourceLocation L;
139 L.ID = ID+Offset;
140 return L;
141 }
142
143 /// When a SourceLocation itself cannot be used, this returns
144 /// an (opaque) 32-bit integer encoding for it.
145 ///
146 /// This should only be passed to SourceLocation::getFromRawEncoding, it
147 /// should not be inspected directly.
148 unsigned getRawEncoding() const { return ID; }
149
150 /// Turn a raw encoding of a SourceLocation object into
151 /// a real SourceLocation.
152 ///
153 /// \see getRawEncoding.
154 static SourceLocation getFromRawEncoding(unsigned Encoding) {
155 SourceLocation X;
156 X.ID = Encoding;
157 return X;
158 }
159
160 /// When a SourceLocation itself cannot be used, this returns
161 /// an (opaque) pointer encoding for it.
162 ///
163 /// This should only be passed to SourceLocation::getFromPtrEncoding, it
164 /// should not be inspected directly.
165 void* getPtrEncoding() const {
166 // Double cast to avoid a warning "cast to pointer from integer of different
167 // size".
168 return (void*)(uintptr_t)getRawEncoding();
169 }
170
171 /// Turn a pointer encoding of a SourceLocation object back
172 /// into a real SourceLocation.
173 static SourceLocation getFromPtrEncoding(const void *Encoding) {
174 return getFromRawEncoding((unsigned)(uintptr_t)Encoding);
175 }
176
177 static bool isPairOfFileLocations(SourceLocation Start, SourceLocation End) {
178 return Start.isValid() && Start.isFileID() && End.isValid() &&
179 End.isFileID();
180 }
181
182 unsigned getHashValue() const;
183 void print(raw_ostream &OS, const SourceManager &SM) const;
184 std::string printToString(const SourceManager &SM) const;
185 void dump(const SourceManager &SM) const;
186};
187
188inline bool operator==(const SourceLocation &LHS, const SourceLocation &RHS) {
189 return LHS.getRawEncoding() == RHS.getRawEncoding();
190}
191
192inline bool operator!=(const SourceLocation &LHS, const SourceLocation &RHS) {
193 return !(LHS == RHS);
194}
195
196// Ordering is meaningful only if LHS and RHS have the same FileID!
197// Otherwise use SourceManager::isBeforeInTranslationUnit().
198inline bool operator<(const SourceLocation &LHS, const SourceLocation &RHS) {
199 return LHS.getRawEncoding() < RHS.getRawEncoding();
200}
201inline bool operator>(const SourceLocation &LHS, const SourceLocation &RHS) {
202 return LHS.getRawEncoding() > RHS.getRawEncoding();
203}
204inline bool operator<=(const SourceLocation &LHS, const SourceLocation &RHS) {
205 return LHS.getRawEncoding() <= RHS.getRawEncoding();
206}
207inline bool operator>=(const SourceLocation &LHS, const SourceLocation &RHS) {
208 return LHS.getRawEncoding() >= RHS.getRawEncoding();
209}
210
211/// A trivial tuple used to represent a source range.
212class SourceRange {
213 SourceLocation B;
214 SourceLocation E;
215
216public:
217 SourceRange() = default;
218 SourceRange(SourceLocation loc) : B(loc), E(loc) {}
219 SourceRange(SourceLocation begin, SourceLocation end) : B(begin), E(end) {}
220
221 SourceLocation getBegin() const { return B; }
222 SourceLocation getEnd() const { return E; }
223
224 void setBegin(SourceLocation b) { B = b; }
225 void setEnd(SourceLocation e) { E = e; }
226
227 bool isValid() const { return B.isValid() && E.isValid(); }
228 bool isInvalid() const { return !isValid(); }
229
230 bool operator==(const SourceRange &X) const {
231 return B == X.B && E == X.E;
232 }
233
234 bool operator!=(const SourceRange &X) const {
235 return B != X.B || E != X.E;
236 }
237
238 // Returns true iff other is wholly contained within this range.
239 bool fullyContains(const SourceRange &other) const {
240 return B <= other.B && E >= other.E;
241 }
242
243 void print(raw_ostream &OS, const SourceManager &SM) const;
244 std::string printToString(const SourceManager &SM) const;
245 void dump(const SourceManager &SM) const;
246};
247
248/// Represents a character-granular source range.
249///
250/// The underlying SourceRange can either specify the starting/ending character
251/// of the range, or it can specify the start of the range and the start of the
252/// last token of the range (a "token range"). In the token range case, the
253/// size of the last token must be measured to determine the actual end of the
254/// range.
255class CharSourceRange {
256 SourceRange Range;
257 bool IsTokenRange = false;
258
259public:
260 CharSourceRange() = default;
261 CharSourceRange(SourceRange R, bool ITR) : Range(R), IsTokenRange(ITR) {}
262
263 static CharSourceRange getTokenRange(SourceRange R) {
264 return CharSourceRange(R, true);
265 }
266
267 static CharSourceRange getCharRange(SourceRange R) {
268 return CharSourceRange(R, false);
269 }
270
271 static CharSourceRange getTokenRange(SourceLocation B, SourceLocation E) {
272 return getTokenRange(SourceRange(B, E));
273 }
274
275 static CharSourceRange getCharRange(SourceLocation B, SourceLocation E) {
276 return getCharRange(SourceRange(B, E));
277 }
278
279 /// Return true if the end of this range specifies the start of
280 /// the last token. Return false if the end of this range specifies the last
281 /// character in the range.
282 bool isTokenRange() const { return IsTokenRange; }
283 bool isCharRange() const { return !IsTokenRange; }
284
285 SourceLocation getBegin() const { return Range.getBegin(); }
286 SourceLocation getEnd() const { return Range.getEnd(); }
287 SourceRange getAsRange() const { return Range; }
288
289 void setBegin(SourceLocation b) { Range.setBegin(b); }
290 void setEnd(SourceLocation e) { Range.setEnd(e); }
291 void setTokenRange(bool TR) { IsTokenRange = TR; }
292
293 bool isValid() const { return Range.isValid(); }
294 bool isInvalid() const { return !isValid(); }
295};
296
297/// Represents an unpacked "presumed" location which can be presented
298/// to the user.
299///
300/// A 'presumed' location can be modified by \#line and GNU line marker
301/// directives and is always the expansion point of a normal location.
302///
303/// You can get a PresumedLoc from a SourceLocation with SourceManager.
304class PresumedLoc {
305 const char *Filename = nullptr;
306 FileID ID;
307 unsigned Line, Col;
308 SourceLocation IncludeLoc;
309
310public:
311 PresumedLoc() = default;
312 PresumedLoc(const char *FN, FileID FID, unsigned Ln, unsigned Co,
313 SourceLocation IL)
314 : Filename(FN), ID(FID), Line(Ln), Col(Co), IncludeLoc(IL) {}
315
316 /// Return true if this object is invalid or uninitialized.
317 ///
318 /// This occurs when created with invalid source locations or when walking
319 /// off the top of a \#include stack.
320 bool isInvalid() const { return Filename == nullptr; }
321 bool isValid() const { return Filename != nullptr; }
322
323 /// Return the presumed filename of this location.
324 ///
325 /// This can be affected by \#line etc.
326 const char *getFilename() const {
327 assert(isValid())((isValid()) ? static_cast<void> (0) : __assert_fail ("isValid()"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Basic/SourceLocation.h"
, 327, __PRETTY_FUNCTION__))
;
328 return Filename;
329 }
330
331 FileID getFileID() const {
332 assert(isValid())((isValid()) ? static_cast<void> (0) : __assert_fail ("isValid()"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Basic/SourceLocation.h"
, 332, __PRETTY_FUNCTION__))
;
333 return ID;
334 }
335
336 /// Return the presumed line number of this location.
337 ///
338 /// This can be affected by \#line etc.
339 unsigned getLine() const {
340 assert(isValid())((isValid()) ? static_cast<void> (0) : __assert_fail ("isValid()"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Basic/SourceLocation.h"
, 340, __PRETTY_FUNCTION__))
;
341 return Line;
342 }
343
344 /// Return the presumed column number of this location.
345 ///
346 /// This cannot be affected by \#line, but is packaged here for convenience.
347 unsigned getColumn() const {
348 assert(isValid())((isValid()) ? static_cast<void> (0) : __assert_fail ("isValid()"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Basic/SourceLocation.h"
, 348, __PRETTY_FUNCTION__))
;
349 return Col;
350 }
351
352 /// Return the presumed include location of this location.
353 ///
354 /// This can be affected by GNU linemarker directives.
355 SourceLocation getIncludeLoc() const {
356 assert(isValid())((isValid()) ? static_cast<void> (0) : __assert_fail ("isValid()"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Basic/SourceLocation.h"
, 356, __PRETTY_FUNCTION__))
;
357 return IncludeLoc;
358 }
359};
360
361class FileEntry;
362
363/// A SourceLocation and its associated SourceManager.
364///
365/// This is useful for argument passing to functions that expect both objects.
366class FullSourceLoc : public SourceLocation {
367 const SourceManager *SrcMgr = nullptr;
368
369public:
370 /// Creates a FullSourceLoc where isValid() returns \c false.
371 FullSourceLoc() = default;
372
373 explicit FullSourceLoc(SourceLocation Loc, const SourceManager &SM)
374 : SourceLocation(Loc), SrcMgr(&SM) {}
375
376 bool hasManager() const {
377 bool hasSrcMgr = SrcMgr != nullptr;
378 assert(hasSrcMgr == isValid() && "FullSourceLoc has location but no manager")((hasSrcMgr == isValid() && "FullSourceLoc has location but no manager"
) ? static_cast<void> (0) : __assert_fail ("hasSrcMgr == isValid() && \"FullSourceLoc has location but no manager\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Basic/SourceLocation.h"
, 378, __PRETTY_FUNCTION__))
;
379 return hasSrcMgr;
380 }
381
382 /// \pre This FullSourceLoc has an associated SourceManager.
383 const SourceManager &getManager() const {
384 assert(SrcMgr && "SourceManager is NULL.")((SrcMgr && "SourceManager is NULL.") ? static_cast<
void> (0) : __assert_fail ("SrcMgr && \"SourceManager is NULL.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Basic/SourceLocation.h"
, 384, __PRETTY_FUNCTION__))
;
385 return *SrcMgr;
386 }
387
388 FileID getFileID() const;
389
390 FullSourceLoc getExpansionLoc() const;
391 FullSourceLoc getSpellingLoc() const;
392 FullSourceLoc getFileLoc() const;
393 PresumedLoc getPresumedLoc(bool UseLineDirectives = true) const;
394 bool isMacroArgExpansion(FullSourceLoc *StartLoc = nullptr) const;
395 FullSourceLoc getImmediateMacroCallerLoc() const;
396 std::pair<FullSourceLoc, StringRef> getModuleImportLoc() const;
397 unsigned getFileOffset() const;
398
399 unsigned getExpansionLineNumber(bool *Invalid = nullptr) const;
400 unsigned getExpansionColumnNumber(bool *Invalid = nullptr) const;
401
402 unsigned getSpellingLineNumber(bool *Invalid = nullptr) const;
403 unsigned getSpellingColumnNumber(bool *Invalid = nullptr) const;
404
405 const char *getCharacterData(bool *Invalid = nullptr) const;
406
407 unsigned getLineNumber(bool *Invalid = nullptr) const;
408 unsigned getColumnNumber(bool *Invalid = nullptr) const;
409
410 const FileEntry *getFileEntry() const;
411
412 /// Return a StringRef to the source buffer data for the
413 /// specified FileID.
414 StringRef getBufferData(bool *Invalid = nullptr) const;
415
416 /// Decompose the specified location into a raw FileID + Offset pair.
417 ///
418 /// The first element is the FileID, the second is the offset from the
419 /// start of the buffer of the location.
420 std::pair<FileID, unsigned> getDecomposedLoc() const;
421
422 bool isInSystemHeader() const;
423
424 /// Determines the order of 2 source locations in the translation unit.
425 ///
426 /// \returns true if this source location comes before 'Loc', false otherwise.
427 bool isBeforeInTranslationUnitThan(SourceLocation Loc) const;
428
429 /// Determines the order of 2 source locations in the translation unit.
430 ///
431 /// \returns true if this source location comes before 'Loc', false otherwise.
432 bool isBeforeInTranslationUnitThan(FullSourceLoc Loc) const {
433 assert(Loc.isValid())((Loc.isValid()) ? static_cast<void> (0) : __assert_fail
("Loc.isValid()", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Basic/SourceLocation.h"
, 433, __PRETTY_FUNCTION__))
;
434 assert(SrcMgr == Loc.SrcMgr && "Loc comes from another SourceManager!")((SrcMgr == Loc.SrcMgr && "Loc comes from another SourceManager!"
) ? static_cast<void> (0) : __assert_fail ("SrcMgr == Loc.SrcMgr && \"Loc comes from another SourceManager!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/Basic/SourceLocation.h"
, 434, __PRETTY_FUNCTION__))
;
435 return isBeforeInTranslationUnitThan((SourceLocation)Loc);
436 }
437
438 /// Comparison function class, useful for sorting FullSourceLocs.
439 struct BeforeThanCompare {
440 bool operator()(const FullSourceLoc& lhs, const FullSourceLoc& rhs) const {
441 return lhs.isBeforeInTranslationUnitThan(rhs);
442 }
443 };
444
445 /// Prints information about this FullSourceLoc to stderr.
446 ///
447 /// This is useful for debugging.
448 void dump() const;
449
450 friend bool
451 operator==(const FullSourceLoc &LHS, const FullSourceLoc &RHS) {
452 return LHS.getRawEncoding() == RHS.getRawEncoding() &&
453 LHS.SrcMgr == RHS.SrcMgr;
454 }
455
456 friend bool
457 operator!=(const FullSourceLoc &LHS, const FullSourceLoc &RHS) {
458 return !(LHS == RHS);
459 }
460};
461
462} // namespace clang
463
464namespace llvm {
465
466 /// Define DenseMapInfo so that FileID's can be used as keys in DenseMap and
467 /// DenseSets.
468 template <>
469 struct DenseMapInfo<clang::FileID> {
470 static clang::FileID getEmptyKey() {
471 return {};
472 }
473
474 static clang::FileID getTombstoneKey() {
475 return clang::FileID::getSentinel();
476 }
477
478 static unsigned getHashValue(clang::FileID S) {
479 return S.getHashValue();
480 }
481
482 static bool isEqual(clang::FileID LHS, clang::FileID RHS) {
483 return LHS == RHS;
484 }
485 };
486
487 /// Define DenseMapInfo so that SourceLocation's can be used as keys in
488 /// DenseMap and DenseSet. This trait class is eqivalent to
489 /// DenseMapInfo<unsigned> which uses SourceLocation::ID is used as a key.
490 template <> struct DenseMapInfo<clang::SourceLocation> {
491 static clang::SourceLocation getEmptyKey() {
492 return clang::SourceLocation::getFromRawEncoding(~0U);
493 }
494
495 static clang::SourceLocation getTombstoneKey() {
496 return clang::SourceLocation::getFromRawEncoding(~0U - 1);
497 }
498
499 static unsigned getHashValue(clang::SourceLocation Loc) {
500 return Loc.getHashValue();
501 }
502
503 static bool isEqual(clang::SourceLocation LHS, clang::SourceLocation RHS) {
504 return LHS == RHS;
505 }
506 };
507
508 // Allow calling FoldingSetNodeID::Add with SourceLocation object as parameter
509 template <> struct FoldingSetTrait<clang::SourceLocation> {
510 static void Profile(const clang::SourceLocation &X, FoldingSetNodeID &ID);
511 };
512
513 // Teach SmallPtrSet how to handle SourceLocation.
514 template<>
515 struct PointerLikeTypeTraits<clang::SourceLocation> {
516 static constexpr int NumLowBitsAvailable = 0;
517
518 static void *getAsVoidPointer(clang::SourceLocation L) {
519 return L.getPtrEncoding();
520 }
521
522 static clang::SourceLocation getFromVoidPointer(void *P) {
523 return clang::SourceLocation::getFromRawEncoding((unsigned)(uintptr_t)P);
524 }
525 };
526
527} // namespace llvm
528
529#endif // LLVM_CLANG_BASIC_SOURCELOCATION_H